file_id
stringlengths
4
10
content
stringlengths
91
42.8k
repo
stringlengths
7
108
path
stringlengths
7
251
token_length
int64
34
8.19k
original_comment
stringlengths
11
11.5k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
34
42.8k
200620_38
package swisseph; /** * Interface for different methods used for transit calculations. */ public abstract class TransitCalculator implements java.io.Serializable { SwissEph sw; // This method changes the offset value for the transit /** * @return Returns true, if one position value is identical to another * position value. E.g., 360 degree is identical to 0 degree in * circular angles. * @see #rolloverVal */ public abstract boolean getRollover(); /** * @return Returns the value, which is identical to zero on the other * end of a linear scale. * @see #rolloverVal */ public double getRolloverVal() { return rolloverVal; } /** * This sets the degree or other value for the position or speed of * the planet to transit. It will be used on the next call to getTransit(). * @param value The desired offset value. * @see #getOffset() */ public abstract void setOffset(double value); /** * This returns the degree or other value of the position or speed of * the planet to transit. * @return The currently set offset value. * @see #setOffset(double) */ public abstract double getOffset(); /** * This returns all the &quot;object identifiers&quot; used in this * TransitCalculator. It may be the planet number or planet numbers, * when calculating planets. * @return An array of identifiers identifying the calculated objects. */ public Object[] getObjectIdentifiers() { return null; } ////////////////////////////////////////////////////////////////////////////// // Rollover from 360 degrees to 0 degrees for planetary longitudinal positions // or similar, or continuous and unlimited values: protected boolean rollover = false; // We need a rollover of 360 degrees being // equal to 0 degrees for longitudinal // position transits only. protected double rolloverVal = 360.; // if rollover, we roll over from 360 to 0 // as default. Other values than 0.0 for the // minimum values are not supported for now. // These methods have to return the maxima of the first derivative of the // function, mathematically spoken... protected abstract double getMaxSpeed(); protected abstract double getMinSpeed(); // This method returns the precision in x-direction in an x-y-coordinate // system for the transit calculation routine. protected abstract double getDegreePrecision(double jdET); // This method returns the precision in y-direction in an x-y-coordinate // system from the x-direction precision. protected abstract double getTimePrecision(double degPrec); // This is the main routine, mathematically speaking: returning f(x): protected abstract double calc(double jdET); // This routine allows for changing jdET before starting calculations. double preprocessDate(double jdET, boolean back) { return jdET; } // These routines check the result if it meets the stop condition protected boolean checkIdenticalResult(double offset, double val) { return val == offset; } protected boolean checkResult(double offset, double lastVal, double val, boolean above, boolean pxway) { return (// transits from higher deg. to lower deg.: ( above && val<=offset && !pxway) || // transits from lower deg. to higher deg.: (!above && val>=offset && pxway)) || (rollover && ( // transits from above the transit degree via rollover over // 0 degrees to a higher degree: (offset<lastVal && val>.9*rolloverVal && lastVal<20. && !pxway) || // transits from below the transit degree via rollover over // 360 degrees to a lower degree: (offset>lastVal && val<20. && lastVal>.9*rolloverVal && pxway) || // transits from below the transit degree via rollover over // 0 degrees to a higher degree: (offset>val && val>.9*rolloverVal && lastVal<20. && !pxway) || // transits from above the transit degree via rollover over // 360 degrees to a lower degree: (offset<val && val<20. && lastVal>.9*rolloverVal && pxway)) ); } // Find next reasonable point to probe. protected double getNextJD(double jdET, double val, double offset, double min, double max, boolean back) { double jdPlus = 0; double jdMinus = 0; if (rollover) { // In most cases here we cannot find out for sure if the distance // is decreasing or increasing. We take the smaller one of these: jdPlus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(max); jdMinus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(min); if (back) { jdET -= SMath.min(jdPlus,jdMinus); } else { jdET += SMath.min(jdPlus,jdMinus); } } else { // Latitude, distance and speed calculations... //jdPlus = (back?(val-offset):(offset-val))/max; //jdMinus = (back?(val-offset):(offset-val))/min; jdPlus = (offset-val)/max; jdMinus = (offset-val)/min; if (back) { if (jdPlus >= 0 && jdMinus >= 0) { throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE, -1, "No transit in ephemeris time range."); // I mean: No transits possible... } else if (jdPlus >= 0) { jdET += jdMinus; } else { // if (jdMinus >= 0) jdET += jdPlus; } } else { if (jdPlus <= 0 && jdMinus <= 0) { throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE, -1, "No transit in ephemeris time range."); // I mean: No transits possible... } else if (jdPlus <= 0) { jdET += jdMinus; } else { // if (jdMinus <= 0) jdET += jdPlus; } } } return jdET; } }
Kibo/AstroAPI
src/main/java/swisseph/TransitCalculator.java
1,590
//jdPlus = (back?(val-offset):(offset-val))/max;
line_comment
nl
package swisseph; /** * Interface for different methods used for transit calculations. */ public abstract class TransitCalculator implements java.io.Serializable { SwissEph sw; // This method changes the offset value for the transit /** * @return Returns true, if one position value is identical to another * position value. E.g., 360 degree is identical to 0 degree in * circular angles. * @see #rolloverVal */ public abstract boolean getRollover(); /** * @return Returns the value, which is identical to zero on the other * end of a linear scale. * @see #rolloverVal */ public double getRolloverVal() { return rolloverVal; } /** * This sets the degree or other value for the position or speed of * the planet to transit. It will be used on the next call to getTransit(). * @param value The desired offset value. * @see #getOffset() */ public abstract void setOffset(double value); /** * This returns the degree or other value of the position or speed of * the planet to transit. * @return The currently set offset value. * @see #setOffset(double) */ public abstract double getOffset(); /** * This returns all the &quot;object identifiers&quot; used in this * TransitCalculator. It may be the planet number or planet numbers, * when calculating planets. * @return An array of identifiers identifying the calculated objects. */ public Object[] getObjectIdentifiers() { return null; } ////////////////////////////////////////////////////////////////////////////// // Rollover from 360 degrees to 0 degrees for planetary longitudinal positions // or similar, or continuous and unlimited values: protected boolean rollover = false; // We need a rollover of 360 degrees being // equal to 0 degrees for longitudinal // position transits only. protected double rolloverVal = 360.; // if rollover, we roll over from 360 to 0 // as default. Other values than 0.0 for the // minimum values are not supported for now. // These methods have to return the maxima of the first derivative of the // function, mathematically spoken... protected abstract double getMaxSpeed(); protected abstract double getMinSpeed(); // This method returns the precision in x-direction in an x-y-coordinate // system for the transit calculation routine. protected abstract double getDegreePrecision(double jdET); // This method returns the precision in y-direction in an x-y-coordinate // system from the x-direction precision. protected abstract double getTimePrecision(double degPrec); // This is the main routine, mathematically speaking: returning f(x): protected abstract double calc(double jdET); // This routine allows for changing jdET before starting calculations. double preprocessDate(double jdET, boolean back) { return jdET; } // These routines check the result if it meets the stop condition protected boolean checkIdenticalResult(double offset, double val) { return val == offset; } protected boolean checkResult(double offset, double lastVal, double val, boolean above, boolean pxway) { return (// transits from higher deg. to lower deg.: ( above && val<=offset && !pxway) || // transits from lower deg. to higher deg.: (!above && val>=offset && pxway)) || (rollover && ( // transits from above the transit degree via rollover over // 0 degrees to a higher degree: (offset<lastVal && val>.9*rolloverVal && lastVal<20. && !pxway) || // transits from below the transit degree via rollover over // 360 degrees to a lower degree: (offset>lastVal && val<20. && lastVal>.9*rolloverVal && pxway) || // transits from below the transit degree via rollover over // 0 degrees to a higher degree: (offset>val && val>.9*rolloverVal && lastVal<20. && !pxway) || // transits from above the transit degree via rollover over // 360 degrees to a lower degree: (offset<val && val<20. && lastVal>.9*rolloverVal && pxway)) ); } // Find next reasonable point to probe. protected double getNextJD(double jdET, double val, double offset, double min, double max, boolean back) { double jdPlus = 0; double jdMinus = 0; if (rollover) { // In most cases here we cannot find out for sure if the distance // is decreasing or increasing. We take the smaller one of these: jdPlus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(max); jdMinus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(min); if (back) { jdET -= SMath.min(jdPlus,jdMinus); } else { jdET += SMath.min(jdPlus,jdMinus); } } else { // Latitude, distance and speed calculations... //jdPlus =<SUF> //jdMinus = (back?(val-offset):(offset-val))/min; jdPlus = (offset-val)/max; jdMinus = (offset-val)/min; if (back) { if (jdPlus >= 0 && jdMinus >= 0) { throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE, -1, "No transit in ephemeris time range."); // I mean: No transits possible... } else if (jdPlus >= 0) { jdET += jdMinus; } else { // if (jdMinus >= 0) jdET += jdPlus; } } else { if (jdPlus <= 0 && jdMinus <= 0) { throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE, -1, "No transit in ephemeris time range."); // I mean: No transits possible... } else if (jdPlus <= 0) { jdET += jdMinus; } else { // if (jdMinus <= 0) jdET += jdPlus; } } } return jdET; } }
200676_29
package org.aisen.weibo.sina.ui.widget.swipeback; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import org.aisen.weibo.sina.R; import java.util.ArrayList; import java.util.List; public class SwipeBackLayout extends FrameLayout { /** * Minimum velocity that will be detected as a fling */ private static final int MIN_FLING_VELOCITY = 400; // dips per second private static final int DEFAULT_SCRIM_COLOR = 0x99000000; private static final int FULL_ALPHA = 255; /** * Edge flag indicating that the left edge should be affected. */ public static final int EDGE_LEFT = ViewDragHelper.EDGE_LEFT; /** * Edge flag indicating that the right edge should be affected. */ public static final int EDGE_RIGHT = ViewDragHelper.EDGE_RIGHT; /** * Edge flag indicating that the bottom edge should be affected. */ public static final int EDGE_BOTTOM = ViewDragHelper.EDGE_BOTTOM; /** * Edge flag set indicating all edges should be affected. */ public static final int EDGE_ALL = EDGE_LEFT | EDGE_RIGHT | EDGE_BOTTOM; /** * A view is not currently being dragged or animating as a result of a * fling/snap. */ public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE; /** * A view is currently being dragged. The position is currently changing as * a result of user input or simulated user input. */ public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING; /** * A view is currently settling into place as a result of a fling or * predefined non-interactive motion. */ public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING; /** * Default threshold of scroll */ private static final float DEFAULT_SCROLL_THRESHOLD = 0.3f; private static final int OVERSCROLL_DISTANCE = 10; private static final int[] EDGE_FLAGS = { EDGE_LEFT, EDGE_RIGHT, EDGE_BOTTOM, EDGE_ALL }; private int mEdgeFlag; /** * Threshold of scroll, we will close the activity, when scrollPercent over * this value; */ private float mScrollThreshold = DEFAULT_SCROLL_THRESHOLD; private Activity mActivity; private boolean mEnable = true; private View mContentView; private ViewDragHelper mDragHelper; private float mScrollPercent; private int mContentLeft; private int mContentTop; /** * The set of listeners to be sent events through. */ private List<SwipeListener> mListeners; private Drawable mShadowLeft; private Drawable mShadowRight; private Drawable mShadowBottom; private float mScrimOpacity; private int mScrimColor = DEFAULT_SCRIM_COLOR; private boolean mInLayout; private Rect mTmpRect = new Rect(); /** * Edge being dragged */ private int mTrackingEdge; public SwipeBackLayout(Context context) { this(context, null); } public SwipeBackLayout(Context context, AttributeSet attrs) { this(context, attrs, R.attr.SwipeBackLayoutStyle); } public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs); mDragHelper = ViewDragHelper.create(this, new ViewDragCallback()); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwipeBackLayout, defStyle, R.style.SwipeBackLayout); int edgeSize = a.getDimensionPixelSize(R.styleable.SwipeBackLayout_edge_size, -1); if (edgeSize > 0) setEdgeSize(edgeSize); int mode = EDGE_FLAGS[a.getInt(R.styleable.SwipeBackLayout_edge_flag, 0)]; setEdgeTrackingEnabled(mode); int shadowLeft = a.getResourceId(R.styleable.SwipeBackLayout_shadow_left, R.drawable.shadow_left); int shadowRight = a.getResourceId(R.styleable.SwipeBackLayout_shadow_right, R.drawable.shadow_right); int shadowBottom = a.getResourceId(R.styleable.SwipeBackLayout_shadow_bottom, R.drawable.shadow_bottom); setShadow(shadowLeft, EDGE_LEFT); setShadow(shadowRight, EDGE_RIGHT); setShadow(shadowBottom, EDGE_BOTTOM); a.recycle(); final float density = getResources().getDisplayMetrics().density; final float minVel = MIN_FLING_VELOCITY * density; mDragHelper.setMinVelocity(minVel); mDragHelper.setMaxVelocity(minVel * 2f); } /** * Sets the sensitivity of the NavigationLayout. * * @param context The application context. * @param sensitivity value between 0 and 1, the final value for touchSlop = * ViewConfiguration.getScaledTouchSlop * (1 / s); */ public void setSensitivity(Context context, float sensitivity) { mDragHelper.setSensitivity(context, sensitivity); } /** * Set up contentView which will be moved by user gesture * * @param view */ private void setContentView(View view) { mContentView = view; } public void setEnableGesture(boolean enable) { mEnable = enable; } /** * Enable edge tracking for the selected edges of the parent view. The * callback's * {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeTouched(int, int)} * and * {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeDragStarted(int, int)} * methods will only be invoked for edges for which edge tracking has been * enabled. * * @param edgeFlags Combination of edge flags describing the edges to watch * @see #EDGE_LEFT * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ public void setEdgeTrackingEnabled(int edgeFlags) { mEdgeFlag = edgeFlags; mDragHelper.setEdgeTrackingEnabled(mEdgeFlag); } /** * Set a color to use for the scrim that obscures primary content while a * drawer is open. * * @param color Color to use in 0xAARRGGBB format. */ public void setScrimColor(int color) { mScrimColor = color; invalidate(); } /** * Set the size of an edge. This is the range in pixels along the edges of * this view that will actively detect edge touches or drags if edge * tracking is enabled. * * @param size The size of an edge in pixels */ public void setEdgeSize(int size) { mDragHelper.setEdgeSize(size); } /** * Register a callback to be invoked when a swipe event is sent to this * view. * * @param listener the swipe listener to attach to this view * @deprecated use {@link #addSwipeListener} instead */ @Deprecated public void setSwipeListener(SwipeListener listener) { addSwipeListener(listener); } /** * Add a callback to be invoked when a swipe event is sent to this view. * * @param listener the swipe listener to attach to this view */ public void addSwipeListener(SwipeListener listener) { if (mListeners == null) { mListeners = new ArrayList<SwipeListener>(); } mListeners.add(listener); } /** * Removes a listener from the set of listeners * * @param listener */ public void removeSwipeListener(SwipeListener listener) { if (mListeners == null) { return; } mListeners.remove(listener); } public static interface SwipeListener { /** * Invoke when state change * * @param state flag to describe scroll state * @param scrollPercent scroll percent of this view * @see #STATE_IDLE * @see #STATE_DRAGGING * @see #STATE_SETTLING */ public void onScrollStateChange(int state, float scrollPercent); /** * Invoke when edge touched * * @param edgeFlag edge flag describing the edge being touched * @see #EDGE_LEFT * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ public void onEdgeTouch(int edgeFlag); /** * Invoke when scroll percent over the threshold for the first time */ public void onScrollOverThreshold(); } /** * Set scroll threshold, we will close the activity, when scrollPercent over * this value * * @param threshold */ public void setScrollThresHold(float threshold) { if (threshold >= 1.0f || threshold <= 0) { throw new IllegalArgumentException("Threshold value should be between 0 and 1.0"); } mScrollThreshold = threshold; } /** * Set a drawable used for edge shadow. * * @param shadow Drawable to use * @param edgeFlags Combination of edge flags describing the edge to set * @see #EDGE_LEFT * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ public void setShadow(Drawable shadow, int edgeFlag) { if ((edgeFlag & EDGE_LEFT) != 0) { mShadowLeft = shadow; } else if ((edgeFlag & EDGE_RIGHT) != 0) { mShadowRight = shadow; } else if ((edgeFlag & EDGE_BOTTOM) != 0) { mShadowBottom = shadow; } invalidate(); } /** * Set a drawable used for edge shadow. * * @param resId Resource of drawable to use * @param edgeFlags Combination of edge flags describing the edge to set * @see #EDGE_LEFT * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ public void setShadow(int resId, int edgeFlag) { setShadow(getResources().getDrawable(resId), edgeFlag); } /** * Scroll out contentView and finish the activity */ public void scrollToFinishActivity() { final int childWidth = mContentView.getWidth(); final int childHeight = mContentView.getHeight(); int left = 0, top = 0; if ((mEdgeFlag & EDGE_LEFT) != 0) { left = childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_LEFT; } else if ((mEdgeFlag & EDGE_RIGHT) != 0) { left = -childWidth - mShadowRight.getIntrinsicWidth() - OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_RIGHT; } else if ((mEdgeFlag & EDGE_BOTTOM) != 0) { top = -childHeight - mShadowBottom.getIntrinsicHeight() - OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_BOTTOM; } mDragHelper.smoothSlideViewTo(mContentView, left, top); invalidate(); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (!mEnable) { return false; } try { return mDragHelper.shouldInterceptTouchEvent(event); } catch (ArrayIndexOutOfBoundsException e) { // FIXME: handle exception // issues #9 return false; } } @Override public boolean onTouchEvent(MotionEvent event) { if (!mEnable) { return false; } mDragHelper.processTouchEvent(event); return true; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { mInLayout = true; // mContentTop = SystemBarUtils.getStatusBarHeight(getContext()); if (mContentView != null) mContentView.layout(mContentLeft, mContentTop, mContentLeft + mContentView.getMeasuredWidth(), mContentTop + mContentView.getMeasuredHeight()); mInLayout = false; } @Override public void requestLayout() { if (!mInLayout) { super.requestLayout(); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { final boolean drawContent = child == mContentView; boolean ret = super.drawChild(canvas, child, drawingTime); if (mScrimOpacity > 0 && drawContent && mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) { drawShadow(canvas, child); drawScrim(canvas, child); } return ret; } private void drawScrim(Canvas canvas, View child) { final int baseAlpha = (mScrimColor & 0xff000000) >>> 24; final int alpha = (int) (baseAlpha * mScrimOpacity); final int color = alpha << 24 | (mScrimColor & 0xffffff); if ((mTrackingEdge & EDGE_LEFT) != 0) { canvas.clipRect(0, 0, child.getLeft(), getHeight()); } else if ((mTrackingEdge & EDGE_RIGHT) != 0) { canvas.clipRect(child.getRight(), 0, getRight(), getHeight()); } else if ((mTrackingEdge & EDGE_BOTTOM) != 0) { canvas.clipRect(child.getLeft(), child.getBottom(), getRight(), getHeight()); } canvas.drawColor(color); } private void drawShadow(Canvas canvas, View child) { final Rect childRect = mTmpRect; child.getHitRect(childRect); if ((mEdgeFlag & EDGE_LEFT) != 0) { mShadowLeft.setBounds(childRect.left - mShadowLeft.getIntrinsicWidth(), childRect.top, childRect.left, childRect.bottom); mShadowLeft.setAlpha((int) (mScrimOpacity * FULL_ALPHA)); mShadowLeft.draw(canvas); } if ((mEdgeFlag & EDGE_RIGHT) != 0) { mShadowRight.setBounds(childRect.right, childRect.top, childRect.right + mShadowRight.getIntrinsicWidth(), childRect.bottom); mShadowRight.setAlpha((int) (mScrimOpacity * FULL_ALPHA)); mShadowRight.draw(canvas); } if ((mEdgeFlag & EDGE_BOTTOM) != 0) { mShadowBottom.setBounds(childRect.left, childRect.bottom, childRect.right, childRect.bottom + mShadowBottom.getIntrinsicHeight()); mShadowBottom.setAlpha((int) (mScrimOpacity * FULL_ALPHA)); mShadowBottom.draw(canvas); } } public void attachToActivity(Activity activity) { mActivity = activity; TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{ android.R.attr.windowBackground }); int background = a.getResourceId(0, 0); a.recycle(); // 这里可以设置背景颜色 ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decor.getChildAt(0); decorChild.setBackgroundResource(background); // decorChild.setBackgroundColor(Color.parseColor("#fffafafa")); decor.removeView(decorChild); addView(decorChild); setContentView(decorChild); decor.addView(this); } @Override public void computeScroll() { mScrimOpacity = 1 - mScrollPercent; if (mDragHelper.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } private class ViewDragCallback extends ViewDragHelper.Callback { private boolean mIsScrollOverValid; @Override public boolean tryCaptureView(View view, int i) { boolean ret = mDragHelper.isEdgeTouched(mEdgeFlag, i); if (ret) { if (mDragHelper.isEdgeTouched(EDGE_LEFT, i)) { mTrackingEdge = EDGE_LEFT; } else if (mDragHelper.isEdgeTouched(EDGE_RIGHT, i)) { mTrackingEdge = EDGE_RIGHT; } else if (mDragHelper.isEdgeTouched(EDGE_BOTTOM, i)) { mTrackingEdge = EDGE_BOTTOM; } if (mListeners != null && !mListeners.isEmpty()) { for (SwipeListener listener : mListeners) { listener.onEdgeTouch(mTrackingEdge); } } mIsScrollOverValid = true; } return ret; } @Override public int getViewHorizontalDragRange(View child) { return mEdgeFlag & (EDGE_LEFT | EDGE_RIGHT); } @Override public int getViewVerticalDragRange(View child) { return mEdgeFlag & EDGE_BOTTOM; } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { super.onViewPositionChanged(changedView, left, top, dx, dy); if ((mTrackingEdge & EDGE_LEFT) != 0) { mScrollPercent = Math.abs((float) left / (mContentView.getWidth() + mShadowLeft.getIntrinsicWidth())); } else if ((mTrackingEdge & EDGE_RIGHT) != 0) { mScrollPercent = Math.abs((float) left / (mContentView.getWidth() + mShadowRight.getIntrinsicWidth())); } else if ((mTrackingEdge & EDGE_BOTTOM) != 0) { mScrollPercent = Math.abs((float) top / (mContentView.getHeight() + mShadowBottom.getIntrinsicHeight())); } mContentLeft = left; mContentTop = top; invalidate(); if (mScrollPercent < mScrollThreshold && !mIsScrollOverValid) { mIsScrollOverValid = true; } if (mListeners != null && !mListeners.isEmpty() && mDragHelper.getViewDragState() == STATE_DRAGGING && mScrollPercent >= mScrollThreshold && mIsScrollOverValid) { mIsScrollOverValid = false; for (SwipeListener listener : mListeners) { listener.onScrollOverThreshold(); } } if (mScrollPercent >= 1) { if (!mActivity.isFinishing()) mActivity.finish(); } } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { final int childWidth = releasedChild.getWidth(); final int childHeight = releasedChild.getHeight(); int left = 0, top = 0; if ((mTrackingEdge & EDGE_LEFT) != 0) { left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE : 0; } else if ((mTrackingEdge & EDGE_RIGHT) != 0) { left = xvel < 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? -(childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0; } else if ((mTrackingEdge & EDGE_BOTTOM) != 0) { top = yvel < 0 || yvel == 0 && mScrollPercent > mScrollThreshold ? -(childHeight + mShadowBottom.getIntrinsicHeight() + OVERSCROLL_DISTANCE) : 0; } mDragHelper.settleCapturedViewAt(left, top); invalidate(); } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { int ret = 0; if ((mTrackingEdge & EDGE_LEFT) != 0) { ret = Math.min(child.getWidth(), Math.max(left, 0)); } else if ((mTrackingEdge & EDGE_RIGHT) != 0) { ret = Math.min(0, Math.max(left, -child.getWidth())); } return ret; } @Override public int clampViewPositionVertical(View child, int top, int dy) { int ret = 0; if ((mTrackingEdge & EDGE_BOTTOM) != 0) { ret = Math.min(0, Math.max(top, -child.getHeight())); } return ret; } @Override public void onViewDragStateChanged(int state) { super.onViewDragStateChanged(state); if (mListeners != null && !mListeners.isEmpty()) { for (SwipeListener listener : mListeners) { listener.onScrollStateChange(state, mScrollPercent); } } } } }
wangdan/AisenWeiBo
app/src/main/java/org/aisen/weibo/sina/ui/widget/swipeback/SwipeBackLayout.java
5,280
// mContentTop = SystemBarUtils.getStatusBarHeight(getContext());
line_comment
nl
package org.aisen.weibo.sina.ui.widget.swipeback; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import org.aisen.weibo.sina.R; import java.util.ArrayList; import java.util.List; public class SwipeBackLayout extends FrameLayout { /** * Minimum velocity that will be detected as a fling */ private static final int MIN_FLING_VELOCITY = 400; // dips per second private static final int DEFAULT_SCRIM_COLOR = 0x99000000; private static final int FULL_ALPHA = 255; /** * Edge flag indicating that the left edge should be affected. */ public static final int EDGE_LEFT = ViewDragHelper.EDGE_LEFT; /** * Edge flag indicating that the right edge should be affected. */ public static final int EDGE_RIGHT = ViewDragHelper.EDGE_RIGHT; /** * Edge flag indicating that the bottom edge should be affected. */ public static final int EDGE_BOTTOM = ViewDragHelper.EDGE_BOTTOM; /** * Edge flag set indicating all edges should be affected. */ public static final int EDGE_ALL = EDGE_LEFT | EDGE_RIGHT | EDGE_BOTTOM; /** * A view is not currently being dragged or animating as a result of a * fling/snap. */ public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE; /** * A view is currently being dragged. The position is currently changing as * a result of user input or simulated user input. */ public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING; /** * A view is currently settling into place as a result of a fling or * predefined non-interactive motion. */ public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING; /** * Default threshold of scroll */ private static final float DEFAULT_SCROLL_THRESHOLD = 0.3f; private static final int OVERSCROLL_DISTANCE = 10; private static final int[] EDGE_FLAGS = { EDGE_LEFT, EDGE_RIGHT, EDGE_BOTTOM, EDGE_ALL }; private int mEdgeFlag; /** * Threshold of scroll, we will close the activity, when scrollPercent over * this value; */ private float mScrollThreshold = DEFAULT_SCROLL_THRESHOLD; private Activity mActivity; private boolean mEnable = true; private View mContentView; private ViewDragHelper mDragHelper; private float mScrollPercent; private int mContentLeft; private int mContentTop; /** * The set of listeners to be sent events through. */ private List<SwipeListener> mListeners; private Drawable mShadowLeft; private Drawable mShadowRight; private Drawable mShadowBottom; private float mScrimOpacity; private int mScrimColor = DEFAULT_SCRIM_COLOR; private boolean mInLayout; private Rect mTmpRect = new Rect(); /** * Edge being dragged */ private int mTrackingEdge; public SwipeBackLayout(Context context) { this(context, null); } public SwipeBackLayout(Context context, AttributeSet attrs) { this(context, attrs, R.attr.SwipeBackLayoutStyle); } public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs); mDragHelper = ViewDragHelper.create(this, new ViewDragCallback()); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SwipeBackLayout, defStyle, R.style.SwipeBackLayout); int edgeSize = a.getDimensionPixelSize(R.styleable.SwipeBackLayout_edge_size, -1); if (edgeSize > 0) setEdgeSize(edgeSize); int mode = EDGE_FLAGS[a.getInt(R.styleable.SwipeBackLayout_edge_flag, 0)]; setEdgeTrackingEnabled(mode); int shadowLeft = a.getResourceId(R.styleable.SwipeBackLayout_shadow_left, R.drawable.shadow_left); int shadowRight = a.getResourceId(R.styleable.SwipeBackLayout_shadow_right, R.drawable.shadow_right); int shadowBottom = a.getResourceId(R.styleable.SwipeBackLayout_shadow_bottom, R.drawable.shadow_bottom); setShadow(shadowLeft, EDGE_LEFT); setShadow(shadowRight, EDGE_RIGHT); setShadow(shadowBottom, EDGE_BOTTOM); a.recycle(); final float density = getResources().getDisplayMetrics().density; final float minVel = MIN_FLING_VELOCITY * density; mDragHelper.setMinVelocity(minVel); mDragHelper.setMaxVelocity(minVel * 2f); } /** * Sets the sensitivity of the NavigationLayout. * * @param context The application context. * @param sensitivity value between 0 and 1, the final value for touchSlop = * ViewConfiguration.getScaledTouchSlop * (1 / s); */ public void setSensitivity(Context context, float sensitivity) { mDragHelper.setSensitivity(context, sensitivity); } /** * Set up contentView which will be moved by user gesture * * @param view */ private void setContentView(View view) { mContentView = view; } public void setEnableGesture(boolean enable) { mEnable = enable; } /** * Enable edge tracking for the selected edges of the parent view. The * callback's * {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeTouched(int, int)} * and * {@link me.imid.swipebacklayout.lib.ViewDragHelper.Callback#onEdgeDragStarted(int, int)} * methods will only be invoked for edges for which edge tracking has been * enabled. * * @param edgeFlags Combination of edge flags describing the edges to watch * @see #EDGE_LEFT * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ public void setEdgeTrackingEnabled(int edgeFlags) { mEdgeFlag = edgeFlags; mDragHelper.setEdgeTrackingEnabled(mEdgeFlag); } /** * Set a color to use for the scrim that obscures primary content while a * drawer is open. * * @param color Color to use in 0xAARRGGBB format. */ public void setScrimColor(int color) { mScrimColor = color; invalidate(); } /** * Set the size of an edge. This is the range in pixels along the edges of * this view that will actively detect edge touches or drags if edge * tracking is enabled. * * @param size The size of an edge in pixels */ public void setEdgeSize(int size) { mDragHelper.setEdgeSize(size); } /** * Register a callback to be invoked when a swipe event is sent to this * view. * * @param listener the swipe listener to attach to this view * @deprecated use {@link #addSwipeListener} instead */ @Deprecated public void setSwipeListener(SwipeListener listener) { addSwipeListener(listener); } /** * Add a callback to be invoked when a swipe event is sent to this view. * * @param listener the swipe listener to attach to this view */ public void addSwipeListener(SwipeListener listener) { if (mListeners == null) { mListeners = new ArrayList<SwipeListener>(); } mListeners.add(listener); } /** * Removes a listener from the set of listeners * * @param listener */ public void removeSwipeListener(SwipeListener listener) { if (mListeners == null) { return; } mListeners.remove(listener); } public static interface SwipeListener { /** * Invoke when state change * * @param state flag to describe scroll state * @param scrollPercent scroll percent of this view * @see #STATE_IDLE * @see #STATE_DRAGGING * @see #STATE_SETTLING */ public void onScrollStateChange(int state, float scrollPercent); /** * Invoke when edge touched * * @param edgeFlag edge flag describing the edge being touched * @see #EDGE_LEFT * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ public void onEdgeTouch(int edgeFlag); /** * Invoke when scroll percent over the threshold for the first time */ public void onScrollOverThreshold(); } /** * Set scroll threshold, we will close the activity, when scrollPercent over * this value * * @param threshold */ public void setScrollThresHold(float threshold) { if (threshold >= 1.0f || threshold <= 0) { throw new IllegalArgumentException("Threshold value should be between 0 and 1.0"); } mScrollThreshold = threshold; } /** * Set a drawable used for edge shadow. * * @param shadow Drawable to use * @param edgeFlags Combination of edge flags describing the edge to set * @see #EDGE_LEFT * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ public void setShadow(Drawable shadow, int edgeFlag) { if ((edgeFlag & EDGE_LEFT) != 0) { mShadowLeft = shadow; } else if ((edgeFlag & EDGE_RIGHT) != 0) { mShadowRight = shadow; } else if ((edgeFlag & EDGE_BOTTOM) != 0) { mShadowBottom = shadow; } invalidate(); } /** * Set a drawable used for edge shadow. * * @param resId Resource of drawable to use * @param edgeFlags Combination of edge flags describing the edge to set * @see #EDGE_LEFT * @see #EDGE_RIGHT * @see #EDGE_BOTTOM */ public void setShadow(int resId, int edgeFlag) { setShadow(getResources().getDrawable(resId), edgeFlag); } /** * Scroll out contentView and finish the activity */ public void scrollToFinishActivity() { final int childWidth = mContentView.getWidth(); final int childHeight = mContentView.getHeight(); int left = 0, top = 0; if ((mEdgeFlag & EDGE_LEFT) != 0) { left = childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_LEFT; } else if ((mEdgeFlag & EDGE_RIGHT) != 0) { left = -childWidth - mShadowRight.getIntrinsicWidth() - OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_RIGHT; } else if ((mEdgeFlag & EDGE_BOTTOM) != 0) { top = -childHeight - mShadowBottom.getIntrinsicHeight() - OVERSCROLL_DISTANCE; mTrackingEdge = EDGE_BOTTOM; } mDragHelper.smoothSlideViewTo(mContentView, left, top); invalidate(); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (!mEnable) { return false; } try { return mDragHelper.shouldInterceptTouchEvent(event); } catch (ArrayIndexOutOfBoundsException e) { // FIXME: handle exception // issues #9 return false; } } @Override public boolean onTouchEvent(MotionEvent event) { if (!mEnable) { return false; } mDragHelper.processTouchEvent(event); return true; } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { mInLayout = true; // mContentTop =<SUF> if (mContentView != null) mContentView.layout(mContentLeft, mContentTop, mContentLeft + mContentView.getMeasuredWidth(), mContentTop + mContentView.getMeasuredHeight()); mInLayout = false; } @Override public void requestLayout() { if (!mInLayout) { super.requestLayout(); } } @Override protected boolean drawChild(Canvas canvas, View child, long drawingTime) { final boolean drawContent = child == mContentView; boolean ret = super.drawChild(canvas, child, drawingTime); if (mScrimOpacity > 0 && drawContent && mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) { drawShadow(canvas, child); drawScrim(canvas, child); } return ret; } private void drawScrim(Canvas canvas, View child) { final int baseAlpha = (mScrimColor & 0xff000000) >>> 24; final int alpha = (int) (baseAlpha * mScrimOpacity); final int color = alpha << 24 | (mScrimColor & 0xffffff); if ((mTrackingEdge & EDGE_LEFT) != 0) { canvas.clipRect(0, 0, child.getLeft(), getHeight()); } else if ((mTrackingEdge & EDGE_RIGHT) != 0) { canvas.clipRect(child.getRight(), 0, getRight(), getHeight()); } else if ((mTrackingEdge & EDGE_BOTTOM) != 0) { canvas.clipRect(child.getLeft(), child.getBottom(), getRight(), getHeight()); } canvas.drawColor(color); } private void drawShadow(Canvas canvas, View child) { final Rect childRect = mTmpRect; child.getHitRect(childRect); if ((mEdgeFlag & EDGE_LEFT) != 0) { mShadowLeft.setBounds(childRect.left - mShadowLeft.getIntrinsicWidth(), childRect.top, childRect.left, childRect.bottom); mShadowLeft.setAlpha((int) (mScrimOpacity * FULL_ALPHA)); mShadowLeft.draw(canvas); } if ((mEdgeFlag & EDGE_RIGHT) != 0) { mShadowRight.setBounds(childRect.right, childRect.top, childRect.right + mShadowRight.getIntrinsicWidth(), childRect.bottom); mShadowRight.setAlpha((int) (mScrimOpacity * FULL_ALPHA)); mShadowRight.draw(canvas); } if ((mEdgeFlag & EDGE_BOTTOM) != 0) { mShadowBottom.setBounds(childRect.left, childRect.bottom, childRect.right, childRect.bottom + mShadowBottom.getIntrinsicHeight()); mShadowBottom.setAlpha((int) (mScrimOpacity * FULL_ALPHA)); mShadowBottom.draw(canvas); } } public void attachToActivity(Activity activity) { mActivity = activity; TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{ android.R.attr.windowBackground }); int background = a.getResourceId(0, 0); a.recycle(); // 这里可以设置背景颜色 ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decor.getChildAt(0); decorChild.setBackgroundResource(background); // decorChild.setBackgroundColor(Color.parseColor("#fffafafa")); decor.removeView(decorChild); addView(decorChild); setContentView(decorChild); decor.addView(this); } @Override public void computeScroll() { mScrimOpacity = 1 - mScrollPercent; if (mDragHelper.continueSettling(true)) { ViewCompat.postInvalidateOnAnimation(this); } } private class ViewDragCallback extends ViewDragHelper.Callback { private boolean mIsScrollOverValid; @Override public boolean tryCaptureView(View view, int i) { boolean ret = mDragHelper.isEdgeTouched(mEdgeFlag, i); if (ret) { if (mDragHelper.isEdgeTouched(EDGE_LEFT, i)) { mTrackingEdge = EDGE_LEFT; } else if (mDragHelper.isEdgeTouched(EDGE_RIGHT, i)) { mTrackingEdge = EDGE_RIGHT; } else if (mDragHelper.isEdgeTouched(EDGE_BOTTOM, i)) { mTrackingEdge = EDGE_BOTTOM; } if (mListeners != null && !mListeners.isEmpty()) { for (SwipeListener listener : mListeners) { listener.onEdgeTouch(mTrackingEdge); } } mIsScrollOverValid = true; } return ret; } @Override public int getViewHorizontalDragRange(View child) { return mEdgeFlag & (EDGE_LEFT | EDGE_RIGHT); } @Override public int getViewVerticalDragRange(View child) { return mEdgeFlag & EDGE_BOTTOM; } @Override public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { super.onViewPositionChanged(changedView, left, top, dx, dy); if ((mTrackingEdge & EDGE_LEFT) != 0) { mScrollPercent = Math.abs((float) left / (mContentView.getWidth() + mShadowLeft.getIntrinsicWidth())); } else if ((mTrackingEdge & EDGE_RIGHT) != 0) { mScrollPercent = Math.abs((float) left / (mContentView.getWidth() + mShadowRight.getIntrinsicWidth())); } else if ((mTrackingEdge & EDGE_BOTTOM) != 0) { mScrollPercent = Math.abs((float) top / (mContentView.getHeight() + mShadowBottom.getIntrinsicHeight())); } mContentLeft = left; mContentTop = top; invalidate(); if (mScrollPercent < mScrollThreshold && !mIsScrollOverValid) { mIsScrollOverValid = true; } if (mListeners != null && !mListeners.isEmpty() && mDragHelper.getViewDragState() == STATE_DRAGGING && mScrollPercent >= mScrollThreshold && mIsScrollOverValid) { mIsScrollOverValid = false; for (SwipeListener listener : mListeners) { listener.onScrollOverThreshold(); } } if (mScrollPercent >= 1) { if (!mActivity.isFinishing()) mActivity.finish(); } } @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { final int childWidth = releasedChild.getWidth(); final int childHeight = releasedChild.getHeight(); int left = 0, top = 0; if ((mTrackingEdge & EDGE_LEFT) != 0) { left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE : 0; } else if ((mTrackingEdge & EDGE_RIGHT) != 0) { left = xvel < 0 || xvel == 0 && mScrollPercent > mScrollThreshold ? -(childWidth + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0; } else if ((mTrackingEdge & EDGE_BOTTOM) != 0) { top = yvel < 0 || yvel == 0 && mScrollPercent > mScrollThreshold ? -(childHeight + mShadowBottom.getIntrinsicHeight() + OVERSCROLL_DISTANCE) : 0; } mDragHelper.settleCapturedViewAt(left, top); invalidate(); } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { int ret = 0; if ((mTrackingEdge & EDGE_LEFT) != 0) { ret = Math.min(child.getWidth(), Math.max(left, 0)); } else if ((mTrackingEdge & EDGE_RIGHT) != 0) { ret = Math.min(0, Math.max(left, -child.getWidth())); } return ret; } @Override public int clampViewPositionVertical(View child, int top, int dy) { int ret = 0; if ((mTrackingEdge & EDGE_BOTTOM) != 0) { ret = Math.min(0, Math.max(top, -child.getHeight())); } return ret; } @Override public void onViewDragStateChanged(int state) { super.onViewDragStateChanged(state); if (mListeners != null && !mListeners.isEmpty()) { for (SwipeListener listener : mListeners) { listener.onScrollStateChange(state, mScrollPercent); } } } } }
200701_12
/* * Hale is highly moddable tactical RPG. * Copyright (C) 2011 Jared Stephen * * 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 hale.view; import hale.AreaListener; import hale.Game; import hale.ability.Targeter; import hale.area.Area; import hale.area.Transition; import hale.entity.Creature; import hale.entity.PC; import hale.entity.Entity; import hale.interfacelock.InterfaceLock; import hale.util.AreaUtil; import hale.util.Point; import hale.widgets.EntityMouseover; import hale.widgets.OverHeadFadeAway; import hale.tileset.AreaTileGrid; import org.lwjgl.opengl.GL11; import de.matthiasmann.twl.AnimationState; import de.matthiasmann.twl.Event; import de.matthiasmann.twl.GUI; import de.matthiasmann.twl.ThemeInfo; import de.matthiasmann.twl.Widget; import de.matthiasmann.twl.renderer.AnimationState.StateKey; import de.matthiasmann.twl.renderer.Image; /** * The widget that comprises the main portion of the Game screen. Views the set * of tiles associated with a given area and all entities within that area. * * @author Jared Stephen */ public class AreaViewer extends Widget implements AreaTileGrid.AreaRenderer { /** * The "active" and enabled GUI state for this AreaViewer, used as a time source * for animations */ public static final StateKey STATE_ACTIVE = StateKey.get("active"); private Image hexAnim; private Image hexFilledBlack, hexFilledGrey; private Image hexWhite, hexRed, hexBlue, hexGreen, hexGrey; public Point mouseHoverTile; public boolean mouseHoverValid; private Area area; private final Point scroll; private final Point maxScroll; private final Point minScroll; private AreaListener areaListener; private DelayedScroll delayedScroll; private ScreenShake screenShake; private long fadeInTime; /** * Creates a new AreaViewer viewing the specified Area. * * @param area the Area to view */ public AreaViewer(Area area) { mouseHoverTile = new Point(); mouseHoverValid = true; this.scroll = new Point(0, 0); this.maxScroll = new Point(0, 0); this.minScroll = new Point(0, 0); this.area = area; fadeInTime = System.currentTimeMillis(); } /** * Sets the area being viewed by this AreaViewer * * @param area the Area to view */ public void setArea(Area area) { this.area = area; this.scroll.x = 0; this.scroll.y = 0; invalidateLayout(); setMaxScroll(); // validate scroll position scroll(0, 0); // load tileset Game.curCampaign.getTileset(area.getTileset()).loadTiles(); area.getTileGrid().cacheSprites(); fadeInTime = System.currentTimeMillis(); Game.timer.resetTime(); } /** * Causes this viewer to fade in, with the fade start time set to the current time. */ public void fadeIn() { fadeInTime = System.currentTimeMillis(); } /** * Returns the Area currently being viewed by this AreaViewer * * @return the Area currently being viewed by this AreaViewer */ @Override public Area getArea() { return area; } /** * Sets the listener which handles all events sent to this AreaViewer * * @param areaListener the listener for this areaViewer */ public void setListener(AreaListener areaListener) { this.areaListener = areaListener; } @Override public void drawInterface(AnimationState as) { if (!Game.interfaceLocker.locked()) { Creature activeCreature = areaListener.getCombatRunner().getActiveCreature(); if (Game.isInTurnMode() && !activeCreature.isPlayerFaction()) { // draw a hex around the active hostile drawBlueHex(areaListener.getCombatRunner().getActiveCreature().getLocation().toPoint(), as); } else { // draw a hex around the selected party member drawBlueHex(Game.curCampaign.party.getSelected().getLocation().toPoint(), as); } } Targeter currentTargeter = areaListener.getTargeterManager().getCurrentTargeter(); if (currentTargeter != null) { currentTargeter.draw(as); } if (mouseHoverValid) { drawWhiteHex(mouseHoverTile, as); } else { drawRedHex(mouseHoverTile, as); } if (Game.isInTurnMode() && !areaListener.getTargeterManager().isInTargetMode()) { Creature active = areaListener.getCombatRunner().getActiveCreature(); if (active != null && !Game.interfaceLocker.locked()) { drawAnimHex(active.getLocation().toPoint(), as); } } GL11.glColor3f(1.0f, 1.0f, 1.0f); } @Override protected void paintWidget(GUI gui) { AnimationState as = this.getAnimationState(); GL11.glPushMatrix(); GL11.glTranslatef((-scroll.x + getX()), (-scroll.y + getY()), 0.0f); GL11.glEnable(GL11.GL_TEXTURE_2D); // compute drawing bounds Point topLeft = AreaUtil.convertScreenToGrid(scroll.x - getX(), scroll.y - getY()); Point bottomRight = AreaUtil.convertScreenToGrid(scroll.x - getX() + getWidth(), scroll.y - getY() + getHeight()); topLeft.x = Math.max(0, topLeft.x - 2); topLeft.y = Math.max(0, topLeft.y - 2); // ensure topLeft.x is even if (topLeft.x % 2 == 1) topLeft.x -= 1; bottomRight.x = Math.min(area.getWidth() - 1, bottomRight.x + 2); bottomRight.y = Math.min(area.getHeight() - 1, bottomRight.y + 2); // draw the area area.getTileGrid().draw(this, as, topLeft, bottomRight); Entity mouseOverEntity = Game.mainViewer.getMouseOver().getSelectedEntity(); if (!Game.isInTurnMode() || !(mouseOverEntity instanceof PC)) { drawVisibility(area.getVisibility(), as, topLeft, bottomRight); } else { drawCreatureVisibility((Creature)mouseOverEntity, as, topLeft, bottomRight); } GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glPopMatrix(); GL11.glColor3f(0.0f, 0.0f, 0.0f); GL11.glBegin(GL11.GL_POLYGON); GL11.glVertex2i((area.getWidth() - 2) * Game.TILE_WIDTH + getX(), 0); GL11.glVertex2i(Game.config.getResolutionX(), 0); GL11.glVertex2i(Game.config.getResolutionX(), Game.config.getResolutionY()); GL11.glVertex2i((area.getWidth() - 2) * Game.TILE_WIDTH + getX(), Game.config.getResolutionY()); GL11.glEnd(); GL11.glBegin(GL11.GL_POLYGON); GL11.glVertex2i(0, (area.getHeight() - 1) * Game.TILE_SIZE - Game.TILE_SIZE / 2); GL11.glVertex2i(Game.config.getResolutionX(), (area.getHeight() - 1) * Game.TILE_SIZE - Game.TILE_SIZE / 2); GL11.glVertex2i(Game.config.getResolutionX(), Game.config.getResolutionY()); GL11.glVertex2i(0, Game.config.getResolutionY()); GL11.glEnd(); // do a fade in if needed if (fadeInTime != 0) { long curTime = System.currentTimeMillis(); float fadeAlpha = Math.min(1.0f, 1.3f - (curTime - fadeInTime) / 1500.0f); if (fadeAlpha > 0.0f) { GL11.glColor4f(0.0f, 0.0f, 0.0f, fadeAlpha); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2i(getX(), getY()); GL11.glVertex2i(getX(), getBottom()); GL11.glVertex2i(getRight(), getBottom()); GL11.glVertex2i(getRight(), getY()); GL11.glEnd(); } else { fadeInTime = 0; } } GL11.glEnable(GL11.GL_TEXTURE_2D); } /** * Performs any delayed scrolls or screen shakes that have been queued up * * @param curTime the current time in milliseconds */ public void update(long curTime) { performDelayedScrolling(curTime); performScreenShake(curTime); } private void performScreenShake(long curTime) { if (screenShake == null) return; if (curTime > screenShake.endTime) { scroll(-screenShake.lastShakeX, -screenShake.lastShakeY, true); screenShake = null; } else if (curTime > screenShake.lastTime + 110) { screenShake.lastTime = curTime; int newShakeX = -1 * ((int)Math.signum(screenShake.lastShakeX)) * Game.dice.rand(20, 35); int newShakeY = Game.dice.rand(-2, 2); scroll(newShakeX - screenShake.lastShakeX, newShakeY - screenShake.lastShakeY, true); screenShake.lastShakeX = newShakeX; screenShake.lastShakeY = newShakeY; } } /** * Performs the classic "screen shake" effect */ public void addScreenShake() { ScreenShake shake = new ScreenShake(); long curTime = System.currentTimeMillis(); shake.endTime = curTime + 600; shake.lastTime = curTime; shake.lastShakeX = 1; this.screenShake = shake; Game.interfaceLocker.add(new InterfaceLock(Game.curCampaign.party.getSelected(), 600)); } /** * Performs any gradual scrolling currently queued up for this AreaViewer * * @param curTime the current time in milliseconds */ private void performDelayedScrolling(long curTime) { if (delayedScroll == null) return; long elapsedTime = curTime - delayedScroll.startTime; float destx = delayedScroll.scrollXPerMilli * elapsedTime + delayedScroll.startScrollX; float desty = delayedScroll.scrollYPerMilli * elapsedTime + delayedScroll.startScrollY; scroll((int)(destx - scroll.x), (int)(desty - scroll.y), true); if (delayedScroll.endTime < curTime) { delayedScroll = null; } } /** * Adds a delayed scroll to the specified point using the DelayedScrollTime. * After the scroll completes, the view will be centered on the specified point * * @param pScreen the point to scroll to */ public void addDelayedScrollToScreenPoint(Point pScreen) { this.delayedScroll = new DelayedScroll(); int destx = pScreen.x - this.getInnerWidth() / 2; int desty = pScreen.y - this.getInnerHeight() / 2; delayedScroll.startScrollX = scroll.x; delayedScroll.startScrollY = scroll.y; float x = destx - scroll.x; float y = desty - scroll.y; int totalTime = Game.config.getCombatDelay() * 2; delayedScroll.scrollXPerMilli = x / totalTime; delayedScroll.scrollYPerMilli = y / totalTime; delayedScroll.startTime = System.currentTimeMillis(); delayedScroll.endTime = delayedScroll.startTime + totalTime; } /** * Adds a delayed scroll to the specified creature using the DelayedScrollTime. * After the scroll completes, the view will be centered on the specified creature * in the same way as {@link #scrollToCreature(Entity)} * * @param creature the creature to scroll to */ public void addDelayedScrollToCreature(Entity creature) { addDelayedScrollToScreenPoint(creature.getLocation().getCenteredScreenPoint()); } /** * Scrolls the view of this area so that it is centered on the specified creature. If the * creature is near the edges of the area and the view cannot center on the creature, the * view is moved as close to centered as possible * * @param creature the entity to center the view on */ public void scrollToCreature(Entity creature) { Point pScreen = creature.getLocation().getCenteredScreenPoint(); int destx = pScreen.x - this.getInnerWidth() / 2; int desty = pScreen.y - this.getInnerHeight() / 2; // clear any delayed scroll delayedScroll = null; scroll(destx - scroll.x, desty - scroll.y); } @Override protected void layout() { super.layout(); setMaxScroll(); // validate scroll position scroll(0, 0); } /** * Sets the maximum and minimum scroll for this AreaViewer based on the * size of the underlying area. This method can be overriden to show a larger * border area, useful for the editor. */ protected void setMaxScroll() { minScroll.x = Game.TILE_SIZE; minScroll.y = Game.TILE_SIZE; maxScroll.x = (area.getWidth() - 1) * Game.TILE_WIDTH - this.getInnerWidth(); maxScroll.y = area.getHeight() * Game.TILE_SIZE - Game.TILE_SIZE / 2 - this.getInnerHeight(); if (maxScroll.x < minScroll.x) maxScroll.x = minScroll.x; if (maxScroll.y < minScroll.y) maxScroll.y = minScroll.y; } /** * Returns the maximum scroll coordinates for this Widget * * @return the maximum scroll coordinates for this widget */ protected Point getMaxScroll() { return maxScroll; } /** * Returns the minimum scroll coordinates for this Widget * * @return the minimum scroll coordinates for this widget */ protected Point getMinScroll() { return minScroll; } /** * Returns the current x scroll coordinate * * @return the current x scroll coordinate */ public int getScrollX() { return scroll.x; } /** * Returns the current y scroll coordinate * * @return the current y scroll coordinate */ public int getScrollY() { return scroll.y; } /** * Scrolls the view of this AreaViewer by the specified amount, capped * by the maximum and minimum scrolls. Also scrolls appropriate widgets * such as overheadfadeaways * * @param x the x scroll amount * @param y the y scroll amount * @return the amount that was actually scrolled by. This can be closer * to 0 than x or y if the scroll was capped by the max or min scrolls. */ public Point scroll(int x, int y) { return scroll(x, y, false); } private Point scroll(int x, int y, boolean delayedScroll) { // don't allow scrolling by other means when a delayed scroll is active if (!delayedScroll && this.delayedScroll != null) { return new Point(); } int scrollXAmount, scrollYAmount; scrollXAmount = Math.min(maxScroll.x - scroll.x, x); scrollXAmount = Math.max(minScroll.x - scroll.x, scrollXAmount); scrollYAmount = Math.min(maxScroll.y - scroll.y, y); scrollYAmount = Math.max(minScroll.y - scroll.y, scrollYAmount); scroll.x += scrollXAmount; scroll.y += scrollYAmount; if (Game.mainViewer != null) { EntityMouseover mo = Game.mainViewer.getMouseOver(); int moX = mo.getX(); int moY = mo.getY(); mo.setPosition(moX - scrollXAmount, moY - scrollYAmount); for (OverHeadFadeAway fadeAway : Game.mainViewer.getFadeAways()) { fadeAway.scroll(scrollXAmount, scrollYAmount); } } return new Point(scrollXAmount, scrollYAmount); } /** * draws the visibility of the Area viewed by this AreaViewer * * @param visibility the visibility matrix to be drawn */ private void drawVisibility(boolean[][] visibility, AnimationState as, Point topLeft, Point bottomRight) { boolean[][] explored = area.getExplored(); for (int x = topLeft.x; x <= bottomRight.x; x++) { for (int y = topLeft.y; y <= bottomRight.y; y++) { Point screenPoint = AreaUtil.convertGridToScreen(x, y); if (!explored[x][y]) { hexFilledBlack.draw(as, screenPoint.x, screenPoint.y); } else if (!visibility[x][y]) { hexFilledGrey.draw(as, screenPoint.x, screenPoint.y); } } } GL11.glColor3f(1.0f, 1.0f, 1.0f); } private void drawCreatureVisibility(Creature creature, AnimationState as, Point topLeft, Point bottomRight) { boolean[][] explored = area.getExplored(); for (int x = topLeft.x; x <= bottomRight.x; x++) { for (int y = topLeft.y; y <= bottomRight.y; y++) { Point screenPoint = AreaUtil.convertGridToScreen(x, y); if (!explored[x][y]) { hexFilledBlack.draw(as, screenPoint.x, screenPoint.y); } else if (!creature.hasVisibilityInCurrentArea(x, y)) { hexFilledGrey.draw(as, screenPoint.x, screenPoint.y); } } } GL11.glColor3f(1.0f, 1.0f, 1.0f); } /** * Draws all Area Transitions within the currently viewed Area */ @Override public void drawTransitions() { GL11.glColor3f(1.0f, 1.0f, 1.0f); for (String s : area.getTransitions()) { Transition transition = Game.curCampaign.getAreaTransition(s); if (!transition.isActivated()) continue; Transition.EndPoint endPoint = transition.getEndPointInArea(area); Point screen = AreaUtil.convertGridToScreen(endPoint.getX(), endPoint.getY()); transition.getIcon().draw(screen.x, screen.y); } } public final void drawRedHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexRed.draw(as, screen.x, screen.y); } public final void drawWhiteHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexWhite.draw(as, screen.x, screen.y); } public final void drawGreenHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexGreen.draw(as, screen.x, screen.y); } public final void drawBlueHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexBlue.draw(as, screen.x, screen.y); } public final void drawGreyHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexGrey.draw(as, screen.x, screen.y); } public final void drawAnimHex(int gridX, int gridY, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridX, gridY); hexAnim.draw(as, screen.x, screen.y); } public final void drawAnimHex(Point point, AnimationState as) { drawAnimHex(point.x, point.y, as); } @Override protected boolean handleEvent(Event evt) { if (super.handleEvent(evt)) return true; return areaListener.handleEvent(evt); } @Override protected void applyTheme(ThemeInfo themeInfo) { super.applyTheme(themeInfo); areaListener.setThemeInfo(themeInfo); hexFilledBlack = themeInfo.getImage("hexfilledblack"); hexFilledGrey = themeInfo.getImage("hexfilledgrey"); hexWhite = themeInfo.getImage("hexwhite"); hexRed = themeInfo.getImage("hexred"); hexBlue = themeInfo.getImage("hexblue"); hexGreen = themeInfo.getImage("hexgreen"); hexGrey = themeInfo.getImage("hexgrey"); hexAnim = themeInfo.getImage("hexanim"); this.getAnimationState().setAnimationState(STATE_ACTIVE, true); } private class DelayedScroll { private int startScrollX; private int startScrollY; private float scrollXPerMilli; private float scrollYPerMilli; private long startTime, endTime; } private class ScreenShake { private long endTime; private long lastTime; private int lastShakeX, lastShakeY; } }
Andres6936/HALE
src/main/java/hale/view/AreaViewer.java
5,729
// ensure topLeft.x is even
line_comment
nl
/* * Hale is highly moddable tactical RPG. * Copyright (C) 2011 Jared Stephen * * 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 hale.view; import hale.AreaListener; import hale.Game; import hale.ability.Targeter; import hale.area.Area; import hale.area.Transition; import hale.entity.Creature; import hale.entity.PC; import hale.entity.Entity; import hale.interfacelock.InterfaceLock; import hale.util.AreaUtil; import hale.util.Point; import hale.widgets.EntityMouseover; import hale.widgets.OverHeadFadeAway; import hale.tileset.AreaTileGrid; import org.lwjgl.opengl.GL11; import de.matthiasmann.twl.AnimationState; import de.matthiasmann.twl.Event; import de.matthiasmann.twl.GUI; import de.matthiasmann.twl.ThemeInfo; import de.matthiasmann.twl.Widget; import de.matthiasmann.twl.renderer.AnimationState.StateKey; import de.matthiasmann.twl.renderer.Image; /** * The widget that comprises the main portion of the Game screen. Views the set * of tiles associated with a given area and all entities within that area. * * @author Jared Stephen */ public class AreaViewer extends Widget implements AreaTileGrid.AreaRenderer { /** * The "active" and enabled GUI state for this AreaViewer, used as a time source * for animations */ public static final StateKey STATE_ACTIVE = StateKey.get("active"); private Image hexAnim; private Image hexFilledBlack, hexFilledGrey; private Image hexWhite, hexRed, hexBlue, hexGreen, hexGrey; public Point mouseHoverTile; public boolean mouseHoverValid; private Area area; private final Point scroll; private final Point maxScroll; private final Point minScroll; private AreaListener areaListener; private DelayedScroll delayedScroll; private ScreenShake screenShake; private long fadeInTime; /** * Creates a new AreaViewer viewing the specified Area. * * @param area the Area to view */ public AreaViewer(Area area) { mouseHoverTile = new Point(); mouseHoverValid = true; this.scroll = new Point(0, 0); this.maxScroll = new Point(0, 0); this.minScroll = new Point(0, 0); this.area = area; fadeInTime = System.currentTimeMillis(); } /** * Sets the area being viewed by this AreaViewer * * @param area the Area to view */ public void setArea(Area area) { this.area = area; this.scroll.x = 0; this.scroll.y = 0; invalidateLayout(); setMaxScroll(); // validate scroll position scroll(0, 0); // load tileset Game.curCampaign.getTileset(area.getTileset()).loadTiles(); area.getTileGrid().cacheSprites(); fadeInTime = System.currentTimeMillis(); Game.timer.resetTime(); } /** * Causes this viewer to fade in, with the fade start time set to the current time. */ public void fadeIn() { fadeInTime = System.currentTimeMillis(); } /** * Returns the Area currently being viewed by this AreaViewer * * @return the Area currently being viewed by this AreaViewer */ @Override public Area getArea() { return area; } /** * Sets the listener which handles all events sent to this AreaViewer * * @param areaListener the listener for this areaViewer */ public void setListener(AreaListener areaListener) { this.areaListener = areaListener; } @Override public void drawInterface(AnimationState as) { if (!Game.interfaceLocker.locked()) { Creature activeCreature = areaListener.getCombatRunner().getActiveCreature(); if (Game.isInTurnMode() && !activeCreature.isPlayerFaction()) { // draw a hex around the active hostile drawBlueHex(areaListener.getCombatRunner().getActiveCreature().getLocation().toPoint(), as); } else { // draw a hex around the selected party member drawBlueHex(Game.curCampaign.party.getSelected().getLocation().toPoint(), as); } } Targeter currentTargeter = areaListener.getTargeterManager().getCurrentTargeter(); if (currentTargeter != null) { currentTargeter.draw(as); } if (mouseHoverValid) { drawWhiteHex(mouseHoverTile, as); } else { drawRedHex(mouseHoverTile, as); } if (Game.isInTurnMode() && !areaListener.getTargeterManager().isInTargetMode()) { Creature active = areaListener.getCombatRunner().getActiveCreature(); if (active != null && !Game.interfaceLocker.locked()) { drawAnimHex(active.getLocation().toPoint(), as); } } GL11.glColor3f(1.0f, 1.0f, 1.0f); } @Override protected void paintWidget(GUI gui) { AnimationState as = this.getAnimationState(); GL11.glPushMatrix(); GL11.glTranslatef((-scroll.x + getX()), (-scroll.y + getY()), 0.0f); GL11.glEnable(GL11.GL_TEXTURE_2D); // compute drawing bounds Point topLeft = AreaUtil.convertScreenToGrid(scroll.x - getX(), scroll.y - getY()); Point bottomRight = AreaUtil.convertScreenToGrid(scroll.x - getX() + getWidth(), scroll.y - getY() + getHeight()); topLeft.x = Math.max(0, topLeft.x - 2); topLeft.y = Math.max(0, topLeft.y - 2); // ensure topLeft.x<SUF> if (topLeft.x % 2 == 1) topLeft.x -= 1; bottomRight.x = Math.min(area.getWidth() - 1, bottomRight.x + 2); bottomRight.y = Math.min(area.getHeight() - 1, bottomRight.y + 2); // draw the area area.getTileGrid().draw(this, as, topLeft, bottomRight); Entity mouseOverEntity = Game.mainViewer.getMouseOver().getSelectedEntity(); if (!Game.isInTurnMode() || !(mouseOverEntity instanceof PC)) { drawVisibility(area.getVisibility(), as, topLeft, bottomRight); } else { drawCreatureVisibility((Creature)mouseOverEntity, as, topLeft, bottomRight); } GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glPopMatrix(); GL11.glColor3f(0.0f, 0.0f, 0.0f); GL11.glBegin(GL11.GL_POLYGON); GL11.glVertex2i((area.getWidth() - 2) * Game.TILE_WIDTH + getX(), 0); GL11.glVertex2i(Game.config.getResolutionX(), 0); GL11.glVertex2i(Game.config.getResolutionX(), Game.config.getResolutionY()); GL11.glVertex2i((area.getWidth() - 2) * Game.TILE_WIDTH + getX(), Game.config.getResolutionY()); GL11.glEnd(); GL11.glBegin(GL11.GL_POLYGON); GL11.glVertex2i(0, (area.getHeight() - 1) * Game.TILE_SIZE - Game.TILE_SIZE / 2); GL11.glVertex2i(Game.config.getResolutionX(), (area.getHeight() - 1) * Game.TILE_SIZE - Game.TILE_SIZE / 2); GL11.glVertex2i(Game.config.getResolutionX(), Game.config.getResolutionY()); GL11.glVertex2i(0, Game.config.getResolutionY()); GL11.glEnd(); // do a fade in if needed if (fadeInTime != 0) { long curTime = System.currentTimeMillis(); float fadeAlpha = Math.min(1.0f, 1.3f - (curTime - fadeInTime) / 1500.0f); if (fadeAlpha > 0.0f) { GL11.glColor4f(0.0f, 0.0f, 0.0f, fadeAlpha); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2i(getX(), getY()); GL11.glVertex2i(getX(), getBottom()); GL11.glVertex2i(getRight(), getBottom()); GL11.glVertex2i(getRight(), getY()); GL11.glEnd(); } else { fadeInTime = 0; } } GL11.glEnable(GL11.GL_TEXTURE_2D); } /** * Performs any delayed scrolls or screen shakes that have been queued up * * @param curTime the current time in milliseconds */ public void update(long curTime) { performDelayedScrolling(curTime); performScreenShake(curTime); } private void performScreenShake(long curTime) { if (screenShake == null) return; if (curTime > screenShake.endTime) { scroll(-screenShake.lastShakeX, -screenShake.lastShakeY, true); screenShake = null; } else if (curTime > screenShake.lastTime + 110) { screenShake.lastTime = curTime; int newShakeX = -1 * ((int)Math.signum(screenShake.lastShakeX)) * Game.dice.rand(20, 35); int newShakeY = Game.dice.rand(-2, 2); scroll(newShakeX - screenShake.lastShakeX, newShakeY - screenShake.lastShakeY, true); screenShake.lastShakeX = newShakeX; screenShake.lastShakeY = newShakeY; } } /** * Performs the classic "screen shake" effect */ public void addScreenShake() { ScreenShake shake = new ScreenShake(); long curTime = System.currentTimeMillis(); shake.endTime = curTime + 600; shake.lastTime = curTime; shake.lastShakeX = 1; this.screenShake = shake; Game.interfaceLocker.add(new InterfaceLock(Game.curCampaign.party.getSelected(), 600)); } /** * Performs any gradual scrolling currently queued up for this AreaViewer * * @param curTime the current time in milliseconds */ private void performDelayedScrolling(long curTime) { if (delayedScroll == null) return; long elapsedTime = curTime - delayedScroll.startTime; float destx = delayedScroll.scrollXPerMilli * elapsedTime + delayedScroll.startScrollX; float desty = delayedScroll.scrollYPerMilli * elapsedTime + delayedScroll.startScrollY; scroll((int)(destx - scroll.x), (int)(desty - scroll.y), true); if (delayedScroll.endTime < curTime) { delayedScroll = null; } } /** * Adds a delayed scroll to the specified point using the DelayedScrollTime. * After the scroll completes, the view will be centered on the specified point * * @param pScreen the point to scroll to */ public void addDelayedScrollToScreenPoint(Point pScreen) { this.delayedScroll = new DelayedScroll(); int destx = pScreen.x - this.getInnerWidth() / 2; int desty = pScreen.y - this.getInnerHeight() / 2; delayedScroll.startScrollX = scroll.x; delayedScroll.startScrollY = scroll.y; float x = destx - scroll.x; float y = desty - scroll.y; int totalTime = Game.config.getCombatDelay() * 2; delayedScroll.scrollXPerMilli = x / totalTime; delayedScroll.scrollYPerMilli = y / totalTime; delayedScroll.startTime = System.currentTimeMillis(); delayedScroll.endTime = delayedScroll.startTime + totalTime; } /** * Adds a delayed scroll to the specified creature using the DelayedScrollTime. * After the scroll completes, the view will be centered on the specified creature * in the same way as {@link #scrollToCreature(Entity)} * * @param creature the creature to scroll to */ public void addDelayedScrollToCreature(Entity creature) { addDelayedScrollToScreenPoint(creature.getLocation().getCenteredScreenPoint()); } /** * Scrolls the view of this area so that it is centered on the specified creature. If the * creature is near the edges of the area and the view cannot center on the creature, the * view is moved as close to centered as possible * * @param creature the entity to center the view on */ public void scrollToCreature(Entity creature) { Point pScreen = creature.getLocation().getCenteredScreenPoint(); int destx = pScreen.x - this.getInnerWidth() / 2; int desty = pScreen.y - this.getInnerHeight() / 2; // clear any delayed scroll delayedScroll = null; scroll(destx - scroll.x, desty - scroll.y); } @Override protected void layout() { super.layout(); setMaxScroll(); // validate scroll position scroll(0, 0); } /** * Sets the maximum and minimum scroll for this AreaViewer based on the * size of the underlying area. This method can be overriden to show a larger * border area, useful for the editor. */ protected void setMaxScroll() { minScroll.x = Game.TILE_SIZE; minScroll.y = Game.TILE_SIZE; maxScroll.x = (area.getWidth() - 1) * Game.TILE_WIDTH - this.getInnerWidth(); maxScroll.y = area.getHeight() * Game.TILE_SIZE - Game.TILE_SIZE / 2 - this.getInnerHeight(); if (maxScroll.x < minScroll.x) maxScroll.x = minScroll.x; if (maxScroll.y < minScroll.y) maxScroll.y = minScroll.y; } /** * Returns the maximum scroll coordinates for this Widget * * @return the maximum scroll coordinates for this widget */ protected Point getMaxScroll() { return maxScroll; } /** * Returns the minimum scroll coordinates for this Widget * * @return the minimum scroll coordinates for this widget */ protected Point getMinScroll() { return minScroll; } /** * Returns the current x scroll coordinate * * @return the current x scroll coordinate */ public int getScrollX() { return scroll.x; } /** * Returns the current y scroll coordinate * * @return the current y scroll coordinate */ public int getScrollY() { return scroll.y; } /** * Scrolls the view of this AreaViewer by the specified amount, capped * by the maximum and minimum scrolls. Also scrolls appropriate widgets * such as overheadfadeaways * * @param x the x scroll amount * @param y the y scroll amount * @return the amount that was actually scrolled by. This can be closer * to 0 than x or y if the scroll was capped by the max or min scrolls. */ public Point scroll(int x, int y) { return scroll(x, y, false); } private Point scroll(int x, int y, boolean delayedScroll) { // don't allow scrolling by other means when a delayed scroll is active if (!delayedScroll && this.delayedScroll != null) { return new Point(); } int scrollXAmount, scrollYAmount; scrollXAmount = Math.min(maxScroll.x - scroll.x, x); scrollXAmount = Math.max(minScroll.x - scroll.x, scrollXAmount); scrollYAmount = Math.min(maxScroll.y - scroll.y, y); scrollYAmount = Math.max(minScroll.y - scroll.y, scrollYAmount); scroll.x += scrollXAmount; scroll.y += scrollYAmount; if (Game.mainViewer != null) { EntityMouseover mo = Game.mainViewer.getMouseOver(); int moX = mo.getX(); int moY = mo.getY(); mo.setPosition(moX - scrollXAmount, moY - scrollYAmount); for (OverHeadFadeAway fadeAway : Game.mainViewer.getFadeAways()) { fadeAway.scroll(scrollXAmount, scrollYAmount); } } return new Point(scrollXAmount, scrollYAmount); } /** * draws the visibility of the Area viewed by this AreaViewer * * @param visibility the visibility matrix to be drawn */ private void drawVisibility(boolean[][] visibility, AnimationState as, Point topLeft, Point bottomRight) { boolean[][] explored = area.getExplored(); for (int x = topLeft.x; x <= bottomRight.x; x++) { for (int y = topLeft.y; y <= bottomRight.y; y++) { Point screenPoint = AreaUtil.convertGridToScreen(x, y); if (!explored[x][y]) { hexFilledBlack.draw(as, screenPoint.x, screenPoint.y); } else if (!visibility[x][y]) { hexFilledGrey.draw(as, screenPoint.x, screenPoint.y); } } } GL11.glColor3f(1.0f, 1.0f, 1.0f); } private void drawCreatureVisibility(Creature creature, AnimationState as, Point topLeft, Point bottomRight) { boolean[][] explored = area.getExplored(); for (int x = topLeft.x; x <= bottomRight.x; x++) { for (int y = topLeft.y; y <= bottomRight.y; y++) { Point screenPoint = AreaUtil.convertGridToScreen(x, y); if (!explored[x][y]) { hexFilledBlack.draw(as, screenPoint.x, screenPoint.y); } else if (!creature.hasVisibilityInCurrentArea(x, y)) { hexFilledGrey.draw(as, screenPoint.x, screenPoint.y); } } } GL11.glColor3f(1.0f, 1.0f, 1.0f); } /** * Draws all Area Transitions within the currently viewed Area */ @Override public void drawTransitions() { GL11.glColor3f(1.0f, 1.0f, 1.0f); for (String s : area.getTransitions()) { Transition transition = Game.curCampaign.getAreaTransition(s); if (!transition.isActivated()) continue; Transition.EndPoint endPoint = transition.getEndPointInArea(area); Point screen = AreaUtil.convertGridToScreen(endPoint.getX(), endPoint.getY()); transition.getIcon().draw(screen.x, screen.y); } } public final void drawRedHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexRed.draw(as, screen.x, screen.y); } public final void drawWhiteHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexWhite.draw(as, screen.x, screen.y); } public final void drawGreenHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexGreen.draw(as, screen.x, screen.y); } public final void drawBlueHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexBlue.draw(as, screen.x, screen.y); } public final void drawGreyHex(Point gridPoint, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridPoint); hexGrey.draw(as, screen.x, screen.y); } public final void drawAnimHex(int gridX, int gridY, AnimationState as) { Point screen = AreaUtil.convertGridToScreen(gridX, gridY); hexAnim.draw(as, screen.x, screen.y); } public final void drawAnimHex(Point point, AnimationState as) { drawAnimHex(point.x, point.y, as); } @Override protected boolean handleEvent(Event evt) { if (super.handleEvent(evt)) return true; return areaListener.handleEvent(evt); } @Override protected void applyTheme(ThemeInfo themeInfo) { super.applyTheme(themeInfo); areaListener.setThemeInfo(themeInfo); hexFilledBlack = themeInfo.getImage("hexfilledblack"); hexFilledGrey = themeInfo.getImage("hexfilledgrey"); hexWhite = themeInfo.getImage("hexwhite"); hexRed = themeInfo.getImage("hexred"); hexBlue = themeInfo.getImage("hexblue"); hexGreen = themeInfo.getImage("hexgreen"); hexGrey = themeInfo.getImage("hexgrey"); hexAnim = themeInfo.getImage("hexanim"); this.getAnimationState().setAnimationState(STATE_ACTIVE, true); } private class DelayedScroll { private int startScrollX; private int startScrollY; private float scrollXPerMilli; private float scrollYPerMilli; private long startTime, endTime; } private class ScreenShake { private long endTime; private long lastTime; private int lastShakeX, lastShakeY; } }
200798_24
package org.mollyproject.android.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.location.Location; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpException; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.protocol.HttpContext; public class Router { protected CookieManager cookieMgr; protected LocationTracker locTracker; protected boolean firstReq; protected MyApplication myApp; protected HttpClient client; protected HttpGet get; protected HttpPost post; public static String mOX = "http://dev.m.ox.ac.uk/"; public static enum OutputFormat { JSON, FRAGMENT, JS, YAML, XML, HTML }; public Router (MyApplication myApp) throws SocketException, IOException, JSONException, ParseException { this.myApp = myApp; cookieMgr = new CookieManager(myApp); firstReq = true; locTracker = new LocationTracker(myApp); locTracker.startLocUpdate(); client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 20000); HttpConnectionParams.setSoTimeout(httpParams, 20000); ((DefaultHttpClient) client).addRequestInterceptor(new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } //TODO: add the location updates header here when it is implemented on the Molly server //e.g: X-Current-Location: -1.6, 51, 100 } }); ((DefaultHttpClient) client).addResponseInterceptor(new HttpResponseInterceptor() { public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity( new GzipDecompressingEntity(response.getEntity())); return; } } } } }); } static class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content is not known return -1; } } public void setApp(MyApplication myApp) { this.myApp = myApp; } //Take an URL String, convert to URL, open connection then process //and return the response public synchronized String getFrom (String urlStr) throws MalformedURLException, IOException, UnknownHostException, SocketException, JSONException, ParseException { String getURL = urlStr; System.out.println("Getting from: " + urlStr); get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { //do something with the response return EntityUtils.toString(resEntityGet); } return null; } public String reverse(String locator, String arg) throws SocketException, MalformedURLException, UnknownHostException, IOException, JSONException, ParseException { //Geting the actual URL from the server using the locator (view name) //and the reverse API in Molly String reverseReq = new String(); if (arg != null) { reverseReq = mOX + "reverse/?name="+locator + arg; } else { reverseReq = mOX + "reverse/?name="+locator; } return getFrom(reverseReq); } public synchronized JSONObject requestJSON(String locator, String arg, String query) throws JSONException, IOException, ParseException { return (new JSONObject(onRequestSent(locator, arg, OutputFormat.JSON, query))); } public synchronized String onRequestSent(String locator, String arg, OutputFormat format, String query) throws JSONException, IOException, ParseException { /*basic method for all GET requests to the Molly server, it sets up a url to be sent to the server as follow: 1. it looks up the url to the required page using the reverse api with either the view_name only or both the view_name and the extra argument (arg) 2. then it returns the url, and open a connection to that one itself 3. get the response */ if (!firstReq) { ((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore()); System.out.println("Cookie set"); if (LocationTracker.autoLoc) { updateCurrentLocation(); } else if (MyApplication.currentLocation != null) { updateLocationManually(MyApplication.currentLocation.getString("name"), MyApplication.currentLocation.getDouble("latitude"), MyApplication.currentLocation.getDouble("longitude"), 10.0); } } System.out.println("GET Request"); String urlStr = reverse(locator,arg); String outputStr = new String(); String formatStr = "?format="; switch(format){ //Depending on the format wanted, get the output case JSON: formatStr+="json"; break; case FRAGMENT: formatStr+="fragment"; break; case JS: formatStr+="js"; break; case HTML: formatStr+="html"; break; case XML: formatStr+="xml"; break; case YAML: formatStr+="yaml"; break; } urlStr = urlStr+formatStr; if (query != null) { urlStr = urlStr+query; } outputStr = getFrom(urlStr); //Check for cookies here, after the first "proper" request, not the reverse request if (firstReq || cookieMgr.getCookieStore().getCookies().size() < ((DefaultHttpClient) client).getCookieStore().getCookies().size()) { //If cookiestore is empty and first request then try storing cookies if this is the first request //or if the session id is added, in which case the size of the cookie store in the app is smaller //than that of the client cookieMgr.storeCookies(((DefaultHttpClient)client).getCookieStore()); ((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore()); firstReq = false; } return outputStr; } public List<String> post(List<NameValuePair> arguments, String url) throws ClientProtocolException, IOException { //take in arguments as a list of name-value pairs and a target url, encode all the arguments, //then do a POST request to the target url, return the output as a list of strings post = new HttpPost(url); UrlEncodedFormEntity ent = new UrlEncodedFormEntity(arguments,HTTP.UTF_8); post.setEntity(ent); HttpResponse responsePOST = client.execute(post); //System.out.println("Location update cookies: " + ((DefaultHttpClient) client).getCookieStore().getCookies()); BufferedReader rd = new BufferedReader (new InputStreamReader(responsePOST.getEntity().getContent())); List<String> output = new ArrayList<String>(); String line; while ((line = rd.readLine()) != null) { System.out.println(line); output.add(line); } rd.close(); return output; } public void updateCurrentLocation() throws JSONException, ParseException, ClientProtocolException, IOException { Location loc = locTracker.getCurrentLoc(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("longitude", new Double(loc.getLongitude()).toString())); params.add(new BasicNameValuePair("latitude", new Double(loc.getLatitude()).toString())); params.add(new BasicNameValuePair("accuracy", new Double(loc.getAccuracy()).toString())); params.add(new BasicNameValuePair("method", "html5request")); params.add(new BasicNameValuePair("format", "json")); params.add(new BasicNameValuePair("force", "True")); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void updateLocationManually(String locationName, Double lat, Double lon, Double accuracy) throws JSONException, ClientProtocolException, SocketException, MalformedURLException, UnknownHostException, IOException, ParseException { //update by coordinates Location loc = locTracker.getCurrentLoc(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("longitude", lon.toString())); params.add(new BasicNameValuePair("latitude", lat.toString())); params.add(new BasicNameValuePair("accuracy", accuracy.toString())); params.add(new BasicNameValuePair("name", locationName)); params.add(new BasicNameValuePair("method", "manual")); params.add(new BasicNameValuePair("format", "json")); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void updateLocationGeocoded(String locationName) throws JSONException, ClientProtocolException, IOException, ParseException { //update by geo code List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("format", "json")); params.add(new BasicNameValuePair("method", "geocoded")); params.add(new BasicNameValuePair("name", locationName)); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void downloadImage(URL url, Bitmap bitmap, int newWidth, int newHeight) throws IOException { HttpURLConnection conn= (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); //matrix used to resize image: int width = bitmap.getWidth(); int height = bitmap.getHeight(); //int newWidth = page.getWindow().getWindowManager().getDefaultDisplay().getWidth(); //int newHeight = page.getWindow().getWindowManager().getDefaultDisplay().getWidth()*3/4; float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); //resize the bitmap matrix.postScale(scaleWidth, scaleHeight); bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); } public void releaseConnection() { if (get != null) { get.abort(); } if (post != null) { post.abort(); } } }
mollyproject/mollyandroid
src/org/mollyproject/android/controller/Router.java
3,489
//int newWidth = page.getWindow().getWindowManager().getDefaultDisplay().getWidth();
line_comment
nl
package org.mollyproject.android.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.location.Location; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpException; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.protocol.HttpContext; public class Router { protected CookieManager cookieMgr; protected LocationTracker locTracker; protected boolean firstReq; protected MyApplication myApp; protected HttpClient client; protected HttpGet get; protected HttpPost post; public static String mOX = "http://dev.m.ox.ac.uk/"; public static enum OutputFormat { JSON, FRAGMENT, JS, YAML, XML, HTML }; public Router (MyApplication myApp) throws SocketException, IOException, JSONException, ParseException { this.myApp = myApp; cookieMgr = new CookieManager(myApp); firstReq = true; locTracker = new LocationTracker(myApp); locTracker.startLocUpdate(); client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 20000); HttpConnectionParams.setSoTimeout(httpParams, 20000); ((DefaultHttpClient) client).addRequestInterceptor(new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } //TODO: add the location updates header here when it is implemented on the Molly server //e.g: X-Current-Location: -1.6, 51, 100 } }); ((DefaultHttpClient) client).addResponseInterceptor(new HttpResponseInterceptor() { public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity( new GzipDecompressingEntity(response.getEntity())); return; } } } } }); } static class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content is not known return -1; } } public void setApp(MyApplication myApp) { this.myApp = myApp; } //Take an URL String, convert to URL, open connection then process //and return the response public synchronized String getFrom (String urlStr) throws MalformedURLException, IOException, UnknownHostException, SocketException, JSONException, ParseException { String getURL = urlStr; System.out.println("Getting from: " + urlStr); get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { //do something with the response return EntityUtils.toString(resEntityGet); } return null; } public String reverse(String locator, String arg) throws SocketException, MalformedURLException, UnknownHostException, IOException, JSONException, ParseException { //Geting the actual URL from the server using the locator (view name) //and the reverse API in Molly String reverseReq = new String(); if (arg != null) { reverseReq = mOX + "reverse/?name="+locator + arg; } else { reverseReq = mOX + "reverse/?name="+locator; } return getFrom(reverseReq); } public synchronized JSONObject requestJSON(String locator, String arg, String query) throws JSONException, IOException, ParseException { return (new JSONObject(onRequestSent(locator, arg, OutputFormat.JSON, query))); } public synchronized String onRequestSent(String locator, String arg, OutputFormat format, String query) throws JSONException, IOException, ParseException { /*basic method for all GET requests to the Molly server, it sets up a url to be sent to the server as follow: 1. it looks up the url to the required page using the reverse api with either the view_name only or both the view_name and the extra argument (arg) 2. then it returns the url, and open a connection to that one itself 3. get the response */ if (!firstReq) { ((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore()); System.out.println("Cookie set"); if (LocationTracker.autoLoc) { updateCurrentLocation(); } else if (MyApplication.currentLocation != null) { updateLocationManually(MyApplication.currentLocation.getString("name"), MyApplication.currentLocation.getDouble("latitude"), MyApplication.currentLocation.getDouble("longitude"), 10.0); } } System.out.println("GET Request"); String urlStr = reverse(locator,arg); String outputStr = new String(); String formatStr = "?format="; switch(format){ //Depending on the format wanted, get the output case JSON: formatStr+="json"; break; case FRAGMENT: formatStr+="fragment"; break; case JS: formatStr+="js"; break; case HTML: formatStr+="html"; break; case XML: formatStr+="xml"; break; case YAML: formatStr+="yaml"; break; } urlStr = urlStr+formatStr; if (query != null) { urlStr = urlStr+query; } outputStr = getFrom(urlStr); //Check for cookies here, after the first "proper" request, not the reverse request if (firstReq || cookieMgr.getCookieStore().getCookies().size() < ((DefaultHttpClient) client).getCookieStore().getCookies().size()) { //If cookiestore is empty and first request then try storing cookies if this is the first request //or if the session id is added, in which case the size of the cookie store in the app is smaller //than that of the client cookieMgr.storeCookies(((DefaultHttpClient)client).getCookieStore()); ((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore()); firstReq = false; } return outputStr; } public List<String> post(List<NameValuePair> arguments, String url) throws ClientProtocolException, IOException { //take in arguments as a list of name-value pairs and a target url, encode all the arguments, //then do a POST request to the target url, return the output as a list of strings post = new HttpPost(url); UrlEncodedFormEntity ent = new UrlEncodedFormEntity(arguments,HTTP.UTF_8); post.setEntity(ent); HttpResponse responsePOST = client.execute(post); //System.out.println("Location update cookies: " + ((DefaultHttpClient) client).getCookieStore().getCookies()); BufferedReader rd = new BufferedReader (new InputStreamReader(responsePOST.getEntity().getContent())); List<String> output = new ArrayList<String>(); String line; while ((line = rd.readLine()) != null) { System.out.println(line); output.add(line); } rd.close(); return output; } public void updateCurrentLocation() throws JSONException, ParseException, ClientProtocolException, IOException { Location loc = locTracker.getCurrentLoc(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("longitude", new Double(loc.getLongitude()).toString())); params.add(new BasicNameValuePair("latitude", new Double(loc.getLatitude()).toString())); params.add(new BasicNameValuePair("accuracy", new Double(loc.getAccuracy()).toString())); params.add(new BasicNameValuePair("method", "html5request")); params.add(new BasicNameValuePair("format", "json")); params.add(new BasicNameValuePair("force", "True")); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void updateLocationManually(String locationName, Double lat, Double lon, Double accuracy) throws JSONException, ClientProtocolException, SocketException, MalformedURLException, UnknownHostException, IOException, ParseException { //update by coordinates Location loc = locTracker.getCurrentLoc(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("longitude", lon.toString())); params.add(new BasicNameValuePair("latitude", lat.toString())); params.add(new BasicNameValuePair("accuracy", accuracy.toString())); params.add(new BasicNameValuePair("name", locationName)); params.add(new BasicNameValuePair("method", "manual")); params.add(new BasicNameValuePair("format", "json")); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void updateLocationGeocoded(String locationName) throws JSONException, ClientProtocolException, IOException, ParseException { //update by geo code List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("format", "json")); params.add(new BasicNameValuePair("method", "geocoded")); params.add(new BasicNameValuePair("name", locationName)); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void downloadImage(URL url, Bitmap bitmap, int newWidth, int newHeight) throws IOException { HttpURLConnection conn= (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); //matrix used to resize image: int width = bitmap.getWidth(); int height = bitmap.getHeight(); //int newWidth<SUF> //int newHeight = page.getWindow().getWindowManager().getDefaultDisplay().getWidth()*3/4; float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); //resize the bitmap matrix.postScale(scaleWidth, scaleHeight); bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); } public void releaseConnection() { if (get != null) { get.abort(); } if (post != null) { post.abort(); } } }
200798_25
package org.mollyproject.android.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.location.Location; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpException; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.protocol.HttpContext; public class Router { protected CookieManager cookieMgr; protected LocationTracker locTracker; protected boolean firstReq; protected MyApplication myApp; protected HttpClient client; protected HttpGet get; protected HttpPost post; public static String mOX = "http://dev.m.ox.ac.uk/"; public static enum OutputFormat { JSON, FRAGMENT, JS, YAML, XML, HTML }; public Router (MyApplication myApp) throws SocketException, IOException, JSONException, ParseException { this.myApp = myApp; cookieMgr = new CookieManager(myApp); firstReq = true; locTracker = new LocationTracker(myApp); locTracker.startLocUpdate(); client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 20000); HttpConnectionParams.setSoTimeout(httpParams, 20000); ((DefaultHttpClient) client).addRequestInterceptor(new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } //TODO: add the location updates header here when it is implemented on the Molly server //e.g: X-Current-Location: -1.6, 51, 100 } }); ((DefaultHttpClient) client).addResponseInterceptor(new HttpResponseInterceptor() { public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity( new GzipDecompressingEntity(response.getEntity())); return; } } } } }); } static class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content is not known return -1; } } public void setApp(MyApplication myApp) { this.myApp = myApp; } //Take an URL String, convert to URL, open connection then process //and return the response public synchronized String getFrom (String urlStr) throws MalformedURLException, IOException, UnknownHostException, SocketException, JSONException, ParseException { String getURL = urlStr; System.out.println("Getting from: " + urlStr); get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { //do something with the response return EntityUtils.toString(resEntityGet); } return null; } public String reverse(String locator, String arg) throws SocketException, MalformedURLException, UnknownHostException, IOException, JSONException, ParseException { //Geting the actual URL from the server using the locator (view name) //and the reverse API in Molly String reverseReq = new String(); if (arg != null) { reverseReq = mOX + "reverse/?name="+locator + arg; } else { reverseReq = mOX + "reverse/?name="+locator; } return getFrom(reverseReq); } public synchronized JSONObject requestJSON(String locator, String arg, String query) throws JSONException, IOException, ParseException { return (new JSONObject(onRequestSent(locator, arg, OutputFormat.JSON, query))); } public synchronized String onRequestSent(String locator, String arg, OutputFormat format, String query) throws JSONException, IOException, ParseException { /*basic method for all GET requests to the Molly server, it sets up a url to be sent to the server as follow: 1. it looks up the url to the required page using the reverse api with either the view_name only or both the view_name and the extra argument (arg) 2. then it returns the url, and open a connection to that one itself 3. get the response */ if (!firstReq) { ((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore()); System.out.println("Cookie set"); if (LocationTracker.autoLoc) { updateCurrentLocation(); } else if (MyApplication.currentLocation != null) { updateLocationManually(MyApplication.currentLocation.getString("name"), MyApplication.currentLocation.getDouble("latitude"), MyApplication.currentLocation.getDouble("longitude"), 10.0); } } System.out.println("GET Request"); String urlStr = reverse(locator,arg); String outputStr = new String(); String formatStr = "?format="; switch(format){ //Depending on the format wanted, get the output case JSON: formatStr+="json"; break; case FRAGMENT: formatStr+="fragment"; break; case JS: formatStr+="js"; break; case HTML: formatStr+="html"; break; case XML: formatStr+="xml"; break; case YAML: formatStr+="yaml"; break; } urlStr = urlStr+formatStr; if (query != null) { urlStr = urlStr+query; } outputStr = getFrom(urlStr); //Check for cookies here, after the first "proper" request, not the reverse request if (firstReq || cookieMgr.getCookieStore().getCookies().size() < ((DefaultHttpClient) client).getCookieStore().getCookies().size()) { //If cookiestore is empty and first request then try storing cookies if this is the first request //or if the session id is added, in which case the size of the cookie store in the app is smaller //than that of the client cookieMgr.storeCookies(((DefaultHttpClient)client).getCookieStore()); ((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore()); firstReq = false; } return outputStr; } public List<String> post(List<NameValuePair> arguments, String url) throws ClientProtocolException, IOException { //take in arguments as a list of name-value pairs and a target url, encode all the arguments, //then do a POST request to the target url, return the output as a list of strings post = new HttpPost(url); UrlEncodedFormEntity ent = new UrlEncodedFormEntity(arguments,HTTP.UTF_8); post.setEntity(ent); HttpResponse responsePOST = client.execute(post); //System.out.println("Location update cookies: " + ((DefaultHttpClient) client).getCookieStore().getCookies()); BufferedReader rd = new BufferedReader (new InputStreamReader(responsePOST.getEntity().getContent())); List<String> output = new ArrayList<String>(); String line; while ((line = rd.readLine()) != null) { System.out.println(line); output.add(line); } rd.close(); return output; } public void updateCurrentLocation() throws JSONException, ParseException, ClientProtocolException, IOException { Location loc = locTracker.getCurrentLoc(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("longitude", new Double(loc.getLongitude()).toString())); params.add(new BasicNameValuePair("latitude", new Double(loc.getLatitude()).toString())); params.add(new BasicNameValuePair("accuracy", new Double(loc.getAccuracy()).toString())); params.add(new BasicNameValuePair("method", "html5request")); params.add(new BasicNameValuePair("format", "json")); params.add(new BasicNameValuePair("force", "True")); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void updateLocationManually(String locationName, Double lat, Double lon, Double accuracy) throws JSONException, ClientProtocolException, SocketException, MalformedURLException, UnknownHostException, IOException, ParseException { //update by coordinates Location loc = locTracker.getCurrentLoc(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("longitude", lon.toString())); params.add(new BasicNameValuePair("latitude", lat.toString())); params.add(new BasicNameValuePair("accuracy", accuracy.toString())); params.add(new BasicNameValuePair("name", locationName)); params.add(new BasicNameValuePair("method", "manual")); params.add(new BasicNameValuePair("format", "json")); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void updateLocationGeocoded(String locationName) throws JSONException, ClientProtocolException, IOException, ParseException { //update by geo code List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("format", "json")); params.add(new BasicNameValuePair("method", "geocoded")); params.add(new BasicNameValuePair("name", locationName)); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void downloadImage(URL url, Bitmap bitmap, int newWidth, int newHeight) throws IOException { HttpURLConnection conn= (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); //matrix used to resize image: int width = bitmap.getWidth(); int height = bitmap.getHeight(); //int newWidth = page.getWindow().getWindowManager().getDefaultDisplay().getWidth(); //int newHeight = page.getWindow().getWindowManager().getDefaultDisplay().getWidth()*3/4; float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); //resize the bitmap matrix.postScale(scaleWidth, scaleHeight); bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); } public void releaseConnection() { if (get != null) { get.abort(); } if (post != null) { post.abort(); } } }
mollyproject/mollyandroid
src/org/mollyproject/android/controller/Router.java
3,489
//int newHeight = page.getWindow().getWindowManager().getDefaultDisplay().getWidth()*3/4;
line_comment
nl
package org.mollyproject.android.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketException; import java.net.URL; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.location.Location; import java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpException; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.protocol.HttpContext; public class Router { protected CookieManager cookieMgr; protected LocationTracker locTracker; protected boolean firstReq; protected MyApplication myApp; protected HttpClient client; protected HttpGet get; protected HttpPost post; public static String mOX = "http://dev.m.ox.ac.uk/"; public static enum OutputFormat { JSON, FRAGMENT, JS, YAML, XML, HTML }; public Router (MyApplication myApp) throws SocketException, IOException, JSONException, ParseException { this.myApp = myApp; cookieMgr = new CookieManager(myApp); firstReq = true; locTracker = new LocationTracker(myApp); locTracker.startLocUpdate(); client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 20000); HttpConnectionParams.setSoTimeout(httpParams, 20000); ((DefaultHttpClient) client).addRequestInterceptor(new HttpRequestInterceptor() { public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } //TODO: add the location updates header here when it is implemented on the Molly server //e.g: X-Current-Location: -1.6, 51, 100 } }); ((DefaultHttpClient) client).addResponseInterceptor(new HttpResponseInterceptor() { public void process( final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity( new GzipDecompressingEntity(response.getEntity())); return; } } } } }); } static class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content is not known return -1; } } public void setApp(MyApplication myApp) { this.myApp = myApp; } //Take an URL String, convert to URL, open connection then process //and return the response public synchronized String getFrom (String urlStr) throws MalformedURLException, IOException, UnknownHostException, SocketException, JSONException, ParseException { String getURL = urlStr; System.out.println("Getting from: " + urlStr); get = new HttpGet(getURL); HttpResponse responseGet = client.execute(get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet != null) { //do something with the response return EntityUtils.toString(resEntityGet); } return null; } public String reverse(String locator, String arg) throws SocketException, MalformedURLException, UnknownHostException, IOException, JSONException, ParseException { //Geting the actual URL from the server using the locator (view name) //and the reverse API in Molly String reverseReq = new String(); if (arg != null) { reverseReq = mOX + "reverse/?name="+locator + arg; } else { reverseReq = mOX + "reverse/?name="+locator; } return getFrom(reverseReq); } public synchronized JSONObject requestJSON(String locator, String arg, String query) throws JSONException, IOException, ParseException { return (new JSONObject(onRequestSent(locator, arg, OutputFormat.JSON, query))); } public synchronized String onRequestSent(String locator, String arg, OutputFormat format, String query) throws JSONException, IOException, ParseException { /*basic method for all GET requests to the Molly server, it sets up a url to be sent to the server as follow: 1. it looks up the url to the required page using the reverse api with either the view_name only or both the view_name and the extra argument (arg) 2. then it returns the url, and open a connection to that one itself 3. get the response */ if (!firstReq) { ((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore()); System.out.println("Cookie set"); if (LocationTracker.autoLoc) { updateCurrentLocation(); } else if (MyApplication.currentLocation != null) { updateLocationManually(MyApplication.currentLocation.getString("name"), MyApplication.currentLocation.getDouble("latitude"), MyApplication.currentLocation.getDouble("longitude"), 10.0); } } System.out.println("GET Request"); String urlStr = reverse(locator,arg); String outputStr = new String(); String formatStr = "?format="; switch(format){ //Depending on the format wanted, get the output case JSON: formatStr+="json"; break; case FRAGMENT: formatStr+="fragment"; break; case JS: formatStr+="js"; break; case HTML: formatStr+="html"; break; case XML: formatStr+="xml"; break; case YAML: formatStr+="yaml"; break; } urlStr = urlStr+formatStr; if (query != null) { urlStr = urlStr+query; } outputStr = getFrom(urlStr); //Check for cookies here, after the first "proper" request, not the reverse request if (firstReq || cookieMgr.getCookieStore().getCookies().size() < ((DefaultHttpClient) client).getCookieStore().getCookies().size()) { //If cookiestore is empty and first request then try storing cookies if this is the first request //or if the session id is added, in which case the size of the cookie store in the app is smaller //than that of the client cookieMgr.storeCookies(((DefaultHttpClient)client).getCookieStore()); ((DefaultHttpClient)client).setCookieStore(cookieMgr.getCookieStore()); firstReq = false; } return outputStr; } public List<String> post(List<NameValuePair> arguments, String url) throws ClientProtocolException, IOException { //take in arguments as a list of name-value pairs and a target url, encode all the arguments, //then do a POST request to the target url, return the output as a list of strings post = new HttpPost(url); UrlEncodedFormEntity ent = new UrlEncodedFormEntity(arguments,HTTP.UTF_8); post.setEntity(ent); HttpResponse responsePOST = client.execute(post); //System.out.println("Location update cookies: " + ((DefaultHttpClient) client).getCookieStore().getCookies()); BufferedReader rd = new BufferedReader (new InputStreamReader(responsePOST.getEntity().getContent())); List<String> output = new ArrayList<String>(); String line; while ((line = rd.readLine()) != null) { System.out.println(line); output.add(line); } rd.close(); return output; } public void updateCurrentLocation() throws JSONException, ParseException, ClientProtocolException, IOException { Location loc = locTracker.getCurrentLoc(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("longitude", new Double(loc.getLongitude()).toString())); params.add(new BasicNameValuePair("latitude", new Double(loc.getLatitude()).toString())); params.add(new BasicNameValuePair("accuracy", new Double(loc.getAccuracy()).toString())); params.add(new BasicNameValuePair("method", "html5request")); params.add(new BasicNameValuePair("format", "json")); params.add(new BasicNameValuePair("force", "True")); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void updateLocationManually(String locationName, Double lat, Double lon, Double accuracy) throws JSONException, ClientProtocolException, SocketException, MalformedURLException, UnknownHostException, IOException, ParseException { //update by coordinates Location loc = locTracker.getCurrentLoc(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("longitude", lon.toString())); params.add(new BasicNameValuePair("latitude", lat.toString())); params.add(new BasicNameValuePair("accuracy", accuracy.toString())); params.add(new BasicNameValuePair("name", locationName)); params.add(new BasicNameValuePair("method", "manual")); params.add(new BasicNameValuePair("format", "json")); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void updateLocationGeocoded(String locationName) throws JSONException, ClientProtocolException, IOException, ParseException { //update by geo code List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("csrfmiddlewaretoken", cookieMgr.getCSRFToken())); params.add(new BasicNameValuePair("format", "json")); params.add(new BasicNameValuePair("method", "geocoded")); params.add(new BasicNameValuePair("name", locationName)); List<String> output = post(params,reverse("geolocation:index", null)); //in this case the result is only one line of text, i.e just the first element of the list is fine MyApplication.currentLocation = new JSONObject(output.get(0)); } public void downloadImage(URL url, Bitmap bitmap, int newWidth, int newHeight) throws IOException { HttpURLConnection conn= (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); //matrix used to resize image: int width = bitmap.getWidth(); int height = bitmap.getHeight(); //int newWidth = page.getWindow().getWindowManager().getDefaultDisplay().getWidth(); //int newHeight<SUF> float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); //resize the bitmap matrix.postScale(scaleWidth, scaleHeight); bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); } public void releaseConnection() { if (get != null) { get.abort(); } if (post != null) { post.abort(); } } }
200847_2
// TODO: 03-05-2024, re-write entire whispercpp.java with standard Android JNI specification // TODO: 03-26-2024, rename this file to ggmljni to unify the JNI of whisper.cpp and llama.cpp, as these projects are all based on ggml package org.ggml; public class ggmljava { private static final String TAG = ggmljava.class.getName(); //keep sync between here and ggml.h // available GGML tensor operations: public enum ggml_op { GGML_OP_NONE, GGML_OP_DUP, GGML_OP_ADD, GGML_OP_ADD1, GGML_OP_ACC, GGML_OP_SUB, GGML_OP_MUL, GGML_OP_DIV, GGML_OP_SQR, GGML_OP_SQRT, GGML_OP_LOG, GGML_OP_SUM, GGML_OP_SUM_ROWS, GGML_OP_MEAN, GGML_OP_ARGMAX, GGML_OP_REPEAT, GGML_OP_REPEAT_BACK, GGML_OP_CONCAT, GGML_OP_SILU_BACK, GGML_OP_NORM, // normalize GGML_OP_RMS_NORM, GGML_OP_RMS_NORM_BACK, GGML_OP_GROUP_NORM, GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID, GGML_OP_OUT_PROD, GGML_OP_SCALE, GGML_OP_SET, GGML_OP_CPY, GGML_OP_CONT, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_PERMUTE, GGML_OP_TRANSPOSE, GGML_OP_GET_ROWS, GGML_OP_GET_ROWS_BACK, GGML_OP_DIAG, GGML_OP_DIAG_MASK_INF, GGML_OP_DIAG_MASK_ZERO, GGML_OP_SOFT_MAX, GGML_OP_SOFT_MAX_BACK, GGML_OP_ROPE, GGML_OP_ROPE_BACK, GGML_OP_ALIBI, GGML_OP_CLAMP, GGML_OP_CONV_TRANSPOSE_1D, GGML_OP_IM2COL, GGML_OP_CONV_TRANSPOSE_2D, GGML_OP_POOL_1D, GGML_OP_POOL_2D, GGML_OP_UPSCALE, // nearest interpolate GGML_OP_PAD, GGML_OP_ARANGE, GGML_OP_TIMESTEP_EMBEDDING, GGML_OP_ARGSORT, GGML_OP_LEAKY_RELU, GGML_OP_FLASH_ATTN, GGML_OP_FLASH_FF, GGML_OP_FLASH_ATTN_BACK, GGML_OP_SSM_CONV, GGML_OP_SSM_SCAN, GGML_OP_WIN_PART, GGML_OP_WIN_UNPART, GGML_OP_GET_REL_POS, GGML_OP_ADD_REL_POS, GGML_OP_UNARY, GGML_OP_MAP_UNARY, GGML_OP_MAP_BINARY, GGML_OP_MAP_CUSTOM1_F32, GGML_OP_MAP_CUSTOM2_F32, GGML_OP_MAP_CUSTOM3_F32, GGML_OP_MAP_CUSTOM1, GGML_OP_MAP_CUSTOM2, GGML_OP_MAP_CUSTOM3, GGML_OP_CROSS_ENTROPY_LOSS, GGML_OP_CROSS_ENTROPY_LOSS_BACK, GGML_OP_COUNT, }; public static native int asr_init(String strModelPath, int nThreadCounts, int nASRMode, int nBackendType); public static native void asr_finalize(); public static native void asr_start(); public static native void asr_stop(); public static native int asr_reset(String strModelPath, int nThreadCounts, int nASRMode, int nBackendType); public static native String asr_get_systeminfo(); public static native int get_cpu_core_counts(); //TODO: not work as expected public static native void asr_set_benchmark_status(int bExitBenchmark); /** * @param modelPath /sdcard/kantv/ggml-xxxxxx.bin or /sdcard/kantv/xxxxxx.gguf or qualcomm's prebuilt dedicated model.so or "" * @param audioPath /sdcard/kantv/jfk.wav * @param nBenchType 0: whisper asr 1: memcpy 2: mulmat 3: whisper full 4: LLAMA 5: stable diffusion 6: QNN sample 7: QNN saver 8: QNN matrix 9: QNN GGML 10: QNN complex 11: QNN GGML OP(QNN UT) 12: QNN UT automation * @param nThreadCounts 1 - 8 * @param nBackendType 0: CPU 1: GPU 2: DSP 3: ggml("fake" QNN backend, just for compare performance) * @param nOpType type of matrix manipulate / GGML OP / type of various complex/complicated computation graph * @return */ public static native String ggml_bench(String modelPath, String audioPath, int nBenchType, int nThreadCounts, int nBackendType, int nOpType); public static native String llm_get_systeminfo(); public static native String llm_inference(String modelPath, String prompt, int nBenchType, int nThreadCounts, int nBackendType); }
zhouwg/kantv
cdeosplayer/cdeosplayer-lib/src/main/java/org/ggml/ggmljava.java
1,493
//keep sync between here and ggml.h
line_comment
nl
// TODO: 03-05-2024, re-write entire whispercpp.java with standard Android JNI specification // TODO: 03-26-2024, rename this file to ggmljni to unify the JNI of whisper.cpp and llama.cpp, as these projects are all based on ggml package org.ggml; public class ggmljava { private static final String TAG = ggmljava.class.getName(); //keep sync<SUF> // available GGML tensor operations: public enum ggml_op { GGML_OP_NONE, GGML_OP_DUP, GGML_OP_ADD, GGML_OP_ADD1, GGML_OP_ACC, GGML_OP_SUB, GGML_OP_MUL, GGML_OP_DIV, GGML_OP_SQR, GGML_OP_SQRT, GGML_OP_LOG, GGML_OP_SUM, GGML_OP_SUM_ROWS, GGML_OP_MEAN, GGML_OP_ARGMAX, GGML_OP_REPEAT, GGML_OP_REPEAT_BACK, GGML_OP_CONCAT, GGML_OP_SILU_BACK, GGML_OP_NORM, // normalize GGML_OP_RMS_NORM, GGML_OP_RMS_NORM_BACK, GGML_OP_GROUP_NORM, GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID, GGML_OP_OUT_PROD, GGML_OP_SCALE, GGML_OP_SET, GGML_OP_CPY, GGML_OP_CONT, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_PERMUTE, GGML_OP_TRANSPOSE, GGML_OP_GET_ROWS, GGML_OP_GET_ROWS_BACK, GGML_OP_DIAG, GGML_OP_DIAG_MASK_INF, GGML_OP_DIAG_MASK_ZERO, GGML_OP_SOFT_MAX, GGML_OP_SOFT_MAX_BACK, GGML_OP_ROPE, GGML_OP_ROPE_BACK, GGML_OP_ALIBI, GGML_OP_CLAMP, GGML_OP_CONV_TRANSPOSE_1D, GGML_OP_IM2COL, GGML_OP_CONV_TRANSPOSE_2D, GGML_OP_POOL_1D, GGML_OP_POOL_2D, GGML_OP_UPSCALE, // nearest interpolate GGML_OP_PAD, GGML_OP_ARANGE, GGML_OP_TIMESTEP_EMBEDDING, GGML_OP_ARGSORT, GGML_OP_LEAKY_RELU, GGML_OP_FLASH_ATTN, GGML_OP_FLASH_FF, GGML_OP_FLASH_ATTN_BACK, GGML_OP_SSM_CONV, GGML_OP_SSM_SCAN, GGML_OP_WIN_PART, GGML_OP_WIN_UNPART, GGML_OP_GET_REL_POS, GGML_OP_ADD_REL_POS, GGML_OP_UNARY, GGML_OP_MAP_UNARY, GGML_OP_MAP_BINARY, GGML_OP_MAP_CUSTOM1_F32, GGML_OP_MAP_CUSTOM2_F32, GGML_OP_MAP_CUSTOM3_F32, GGML_OP_MAP_CUSTOM1, GGML_OP_MAP_CUSTOM2, GGML_OP_MAP_CUSTOM3, GGML_OP_CROSS_ENTROPY_LOSS, GGML_OP_CROSS_ENTROPY_LOSS_BACK, GGML_OP_COUNT, }; public static native int asr_init(String strModelPath, int nThreadCounts, int nASRMode, int nBackendType); public static native void asr_finalize(); public static native void asr_start(); public static native void asr_stop(); public static native int asr_reset(String strModelPath, int nThreadCounts, int nASRMode, int nBackendType); public static native String asr_get_systeminfo(); public static native int get_cpu_core_counts(); //TODO: not work as expected public static native void asr_set_benchmark_status(int bExitBenchmark); /** * @param modelPath /sdcard/kantv/ggml-xxxxxx.bin or /sdcard/kantv/xxxxxx.gguf or qualcomm's prebuilt dedicated model.so or "" * @param audioPath /sdcard/kantv/jfk.wav * @param nBenchType 0: whisper asr 1: memcpy 2: mulmat 3: whisper full 4: LLAMA 5: stable diffusion 6: QNN sample 7: QNN saver 8: QNN matrix 9: QNN GGML 10: QNN complex 11: QNN GGML OP(QNN UT) 12: QNN UT automation * @param nThreadCounts 1 - 8 * @param nBackendType 0: CPU 1: GPU 2: DSP 3: ggml("fake" QNN backend, just for compare performance) * @param nOpType type of matrix manipulate / GGML OP / type of various complex/complicated computation graph * @return */ public static native String ggml_bench(String modelPath, String audioPath, int nBenchType, int nThreadCounts, int nBackendType, int nOpType); public static native String llm_get_systeminfo(); public static native String llm_inference(String modelPath, String prompt, int nBenchType, int nThreadCounts, int nBackendType); }
200855_4
// Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package com.twitter.intellij.pants.service.project.model; import com.intellij.openapi.util.Condition; import com.intellij.util.containers.ContainerUtil; import com.twitter.intellij.pants.model.PantsSourceType; import com.twitter.intellij.pants.model.TargetAddressInfo; import com.twitter.intellij.pants.util.PantsScalaUtil; import com.twitter.intellij.pants.util.PantsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; public class TargetInfo { protected Set<TargetAddressInfo> addressInfos = Collections.emptySet(); /** * List of libraries. Just names. */ protected Set<String> libraries = Collections.emptySet(); /** * List of libraries. Just names. */ protected Set<String> excludes = Collections.emptySet(); /** * List of dependencies. */ protected Set<String> targets = Collections.emptySet(); /** * List of source roots. */ protected Set<ContentRoot> roots = Collections.emptySet(); public TargetInfo(TargetAddressInfo... addressInfos) { setAddressInfos(ContainerUtil.newHashSet(addressInfos)); } public TargetInfo( Set<TargetAddressInfo> addressInfos, Set<String> targets, Set<String> libraries, Set<String> excludes, Set<ContentRoot> roots ) { setAddressInfos(addressInfos); setLibraries(libraries); setExcludes(excludes); setTargets(targets); setRoots(roots); } public Set<TargetAddressInfo> getAddressInfos() { return addressInfos; } public void setAddressInfos(Set<TargetAddressInfo> addressInfos) { this.addressInfos = addressInfos; } @NotNull public Set<String> getLibraries() { return libraries; } public void setLibraries(Set<String> libraries) { this.libraries = new TreeSet<>(libraries); } @NotNull public Set<String> getExcludes() { return excludes; } public void setExcludes(Set<String> excludes) { this.excludes = new TreeSet<>(excludes); } @NotNull public Set<String> getTargets() { return targets; } public void setTargets(Set<String> targets) { this.targets = new TreeSet<>(targets); } @NotNull public Set<ContentRoot> getRoots() { return roots; } public void setRoots(Set<ContentRoot> roots) { this.roots = new TreeSet<>(roots); } public boolean isEmpty() { return libraries.isEmpty() && targets.isEmpty() && roots.isEmpty() && addressInfos.isEmpty(); } @Nullable public String findScalaLibId() { return ContainerUtil.find( libraries, new Condition<String>() { @Override public boolean value(String libraryId) { return PantsScalaUtil.isScalaLibraryLib(libraryId); } } ); } public boolean isTest() { return ContainerUtil.exists( getAddressInfos(), new Condition<TargetAddressInfo>() { @Override public boolean value(TargetAddressInfo info) { return PantsUtil.getSourceTypeForTargetType(info.getTargetType(), info.isSynthetic()).toExternalSystemSourceType().isTest(); } } ); } @NotNull public PantsSourceType getSourcesType() { // In the case where multiple targets get combined into one module, // the type of common module should be in the order of // source -> test source -> resource -> test resources. (like Ranked Value in Pants options) // e.g. if source and resources get combined, the common module should be source type. Set<PantsSourceType> allTypes = getAddressInfos().stream() .map(s -> PantsUtil.getSourceTypeForTargetType(s.getTargetType(), s.isSynthetic())) .collect(Collectors.toSet()); Optional<PantsSourceType> topRankedType = Arrays.stream(PantsSourceType.values()) .filter(allTypes::contains) .findFirst(); if (topRankedType.isPresent()) { return topRankedType.get(); } return PantsSourceType.SOURCE; } public boolean isJarLibrary() { return getAddressInfos().stream().allMatch(TargetAddressInfo::isJarLibrary); } public boolean isScalaTarget() { return getAddressInfos().stream().anyMatch(TargetAddressInfo::isScala) || // TODO(yic): have Pants export `pants_target_type` correctly // because `thrift-scala` also has the type `java_thrift_library` getAddressInfos().stream().anyMatch(s -> s.getTargetAddress().endsWith("-scala")); } public boolean isPythonTarget() { return getAddressInfos().stream().anyMatch(TargetAddressInfo::isPython); } public boolean dependOn(@NotNull String targetName) { return targets.contains(targetName); } public void addDependency(@NotNull String targetName) { if (targets.isEmpty()) { targets = new HashSet<>(Collections.singletonList(targetName)); } else { targets.add(targetName); } } public boolean removeDependency(@NotNull String targetName) { return getTargets().remove(targetName); } public void replaceDependency(@NotNull String targetName, @NotNull String newTargetName) { if (removeDependency(targetName)) { addDependency(newTargetName); } } public TargetInfo union(@NotNull TargetInfo other) { return new TargetInfo( ContainerUtil.union(getAddressInfos(), other.getAddressInfos()), ContainerUtil.union(getTargets(), other.getTargets()), ContainerUtil.union(getLibraries(), other.getLibraries()), ContainerUtil.union(getExcludes(), other.getExcludes()), ContainerUtil.union(getRoots(), other.getRoots()) ); } @Override public String toString() { return "TargetInfo{" + "libraries=" + libraries + ", excludes=" + excludes + ", targets=" + targets + ", roots=" + roots + ", addressInfos='" + addressInfos + '\'' + '}'; } }
pantsbuild/intellij-pants-plugin
src/main/scala/com/twitter/intellij/pants/service/project/model/TargetInfo.java
1,630
/** * List of dependencies. */
block_comment
nl
// Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package com.twitter.intellij.pants.service.project.model; import com.intellij.openapi.util.Condition; import com.intellij.util.containers.ContainerUtil; import com.twitter.intellij.pants.model.PantsSourceType; import com.twitter.intellij.pants.model.TargetAddressInfo; import com.twitter.intellij.pants.util.PantsScalaUtil; import com.twitter.intellij.pants.util.PantsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; public class TargetInfo { protected Set<TargetAddressInfo> addressInfos = Collections.emptySet(); /** * List of libraries. Just names. */ protected Set<String> libraries = Collections.emptySet(); /** * List of libraries. Just names. */ protected Set<String> excludes = Collections.emptySet(); /** * List of dependencies.<SUF>*/ protected Set<String> targets = Collections.emptySet(); /** * List of source roots. */ protected Set<ContentRoot> roots = Collections.emptySet(); public TargetInfo(TargetAddressInfo... addressInfos) { setAddressInfos(ContainerUtil.newHashSet(addressInfos)); } public TargetInfo( Set<TargetAddressInfo> addressInfos, Set<String> targets, Set<String> libraries, Set<String> excludes, Set<ContentRoot> roots ) { setAddressInfos(addressInfos); setLibraries(libraries); setExcludes(excludes); setTargets(targets); setRoots(roots); } public Set<TargetAddressInfo> getAddressInfos() { return addressInfos; } public void setAddressInfos(Set<TargetAddressInfo> addressInfos) { this.addressInfos = addressInfos; } @NotNull public Set<String> getLibraries() { return libraries; } public void setLibraries(Set<String> libraries) { this.libraries = new TreeSet<>(libraries); } @NotNull public Set<String> getExcludes() { return excludes; } public void setExcludes(Set<String> excludes) { this.excludes = new TreeSet<>(excludes); } @NotNull public Set<String> getTargets() { return targets; } public void setTargets(Set<String> targets) { this.targets = new TreeSet<>(targets); } @NotNull public Set<ContentRoot> getRoots() { return roots; } public void setRoots(Set<ContentRoot> roots) { this.roots = new TreeSet<>(roots); } public boolean isEmpty() { return libraries.isEmpty() && targets.isEmpty() && roots.isEmpty() && addressInfos.isEmpty(); } @Nullable public String findScalaLibId() { return ContainerUtil.find( libraries, new Condition<String>() { @Override public boolean value(String libraryId) { return PantsScalaUtil.isScalaLibraryLib(libraryId); } } ); } public boolean isTest() { return ContainerUtil.exists( getAddressInfos(), new Condition<TargetAddressInfo>() { @Override public boolean value(TargetAddressInfo info) { return PantsUtil.getSourceTypeForTargetType(info.getTargetType(), info.isSynthetic()).toExternalSystemSourceType().isTest(); } } ); } @NotNull public PantsSourceType getSourcesType() { // In the case where multiple targets get combined into one module, // the type of common module should be in the order of // source -> test source -> resource -> test resources. (like Ranked Value in Pants options) // e.g. if source and resources get combined, the common module should be source type. Set<PantsSourceType> allTypes = getAddressInfos().stream() .map(s -> PantsUtil.getSourceTypeForTargetType(s.getTargetType(), s.isSynthetic())) .collect(Collectors.toSet()); Optional<PantsSourceType> topRankedType = Arrays.stream(PantsSourceType.values()) .filter(allTypes::contains) .findFirst(); if (topRankedType.isPresent()) { return topRankedType.get(); } return PantsSourceType.SOURCE; } public boolean isJarLibrary() { return getAddressInfos().stream().allMatch(TargetAddressInfo::isJarLibrary); } public boolean isScalaTarget() { return getAddressInfos().stream().anyMatch(TargetAddressInfo::isScala) || // TODO(yic): have Pants export `pants_target_type` correctly // because `thrift-scala` also has the type `java_thrift_library` getAddressInfos().stream().anyMatch(s -> s.getTargetAddress().endsWith("-scala")); } public boolean isPythonTarget() { return getAddressInfos().stream().anyMatch(TargetAddressInfo::isPython); } public boolean dependOn(@NotNull String targetName) { return targets.contains(targetName); } public void addDependency(@NotNull String targetName) { if (targets.isEmpty()) { targets = new HashSet<>(Collections.singletonList(targetName)); } else { targets.add(targetName); } } public boolean removeDependency(@NotNull String targetName) { return getTargets().remove(targetName); } public void replaceDependency(@NotNull String targetName, @NotNull String newTargetName) { if (removeDependency(targetName)) { addDependency(newTargetName); } } public TargetInfo union(@NotNull TargetInfo other) { return new TargetInfo( ContainerUtil.union(getAddressInfos(), other.getAddressInfos()), ContainerUtil.union(getTargets(), other.getTargets()), ContainerUtil.union(getLibraries(), other.getLibraries()), ContainerUtil.union(getExcludes(), other.getExcludes()), ContainerUtil.union(getRoots(), other.getRoots()) ); } @Override public String toString() { return "TargetInfo{" + "libraries=" + libraries + ", excludes=" + excludes + ", targets=" + targets + ", roots=" + roots + ", addressInfos='" + addressInfos + '\'' + '}'; } }
200889_12
/* *************************************************************************************** * Copyright (C) 2006 EsperTech, Inc. All rights reserved. * * http://www.espertech.com/esper * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * *************************************************************************************** */ package com.espertech.esper.common.internal.event.bean.introspect; import com.espertech.esper.common.client.EventPropertyDescriptor; import com.espertech.esper.common.client.configuration.common.ConfigurationCommonEventTypeBean; import com.espertech.esper.common.client.type.EPTypeClass; import com.espertech.esper.common.client.type.EPTypeClassParameterized; import com.espertech.esper.common.client.util.PropertyResolutionStyle; import com.espertech.esper.common.internal.event.bean.core.PropertyStem; import com.espertech.esper.common.internal.event.bean.getter.ReflectionPropFieldGetterFactory; import com.espertech.esper.common.internal.event.bean.getter.ReflectionPropMethodGetterFactory; import com.espertech.esper.common.internal.event.core.EventPropertyType; import com.espertech.esper.common.internal.event.core.EventTypeUtility; import com.espertech.esper.common.internal.util.ClassHelperGenericType; import com.espertech.esper.common.internal.util.JavaClassHelper; import java.util.*; public class BeanEventTypeStemBuilder { private final ConfigurationCommonEventTypeBean optionalConfig; private final PropertyResolutionStyle propertyResolutionStyle; private final boolean smartResolutionStyle; public BeanEventTypeStemBuilder(ConfigurationCommonEventTypeBean optionalConfig, PropertyResolutionStyle defaultPropertyResolutionStyle) { this.optionalConfig = optionalConfig; if (optionalConfig != null) { this.propertyResolutionStyle = optionalConfig.getPropertyResolutionStyle(); } else { this.propertyResolutionStyle = defaultPropertyResolutionStyle; } this.smartResolutionStyle = propertyResolutionStyle.equals(PropertyResolutionStyle.CASE_INSENSITIVE) || propertyResolutionStyle.equals(PropertyResolutionStyle.DISTINCT_CASE_INSENSITIVE); } public BeanEventTypeStem make(EPTypeClass clazz) { EventTypeUtility.validateEventBeanClassVisibility(clazz.getType()); PropertyListBuilder propertyListBuilder = PropertyListBuilderFactory.createBuilder(optionalConfig); List<PropertyStem> properties = propertyListBuilder.assessProperties(clazz.getType()); EventPropertyDescriptor[] propertyDescriptors = new EventPropertyDescriptor[properties.size()]; Map<String, EventPropertyDescriptor> propertyDescriptorMap = new HashMap<>(); String[] propertyNames = new String[properties.size()]; Map<String, PropertyInfo> simpleProperties = new HashMap<>(); Map<String, PropertyStem> mappedPropertyDescriptors = new HashMap<>(); Map<String, PropertyStem> indexedPropertyDescriptors = new HashMap<>(); Map<String, List<PropertyInfo>> simpleSmartPropertyTable = null; Map<String, List<PropertyInfo>> mappedSmartPropertyTable = null; Map<String, List<PropertyInfo>> indexedSmartPropertyTable = null; if (smartResolutionStyle) { simpleSmartPropertyTable = new HashMap<>(); mappedSmartPropertyTable = new HashMap<>(); indexedSmartPropertyTable = new HashMap<>(); } int count = 0; for (PropertyStem desc : properties) { String propertyName = desc.getPropertyName(); EPTypeClass underlyingType; boolean isRequiresIndex; boolean isRequiresMapkey; boolean isIndexed; boolean isMapped; boolean isFragment; if (desc.getPropertyType().equals(EventPropertyType.SIMPLE)) { EventPropertyGetterSPIFactory getter; EPTypeClass type; if (desc.getReadMethod() != null) { getter = new ReflectionPropMethodGetterFactory(desc.getReadMethod()); type = ClassHelperGenericType.getMethodReturnEPType(desc.getReadMethod(), clazz); } else if (desc.getAccessorField() != null) { getter = new ReflectionPropFieldGetterFactory(desc.getAccessorField()); type = ClassHelperGenericType.getFieldEPType(desc.getAccessorField(), clazz); } else { // ignore property continue; } underlyingType = type; isRequiresIndex = false; isRequiresMapkey = false; isIndexed = false; isMapped = false; if (JavaClassHelper.isImplementsInterface(type, Map.class)) { isMapped = true; // We do not yet allow to fragment maps entries. // Class genericType = JavaClassHelper.getGenericReturnTypeMap(desc.getReadMethod(), desc.getAccessorField()); isFragment = false; } else if (type.getType().isArray()) { isIndexed = true; isFragment = JavaClassHelper.isFragmentableType(type.getType().getComponentType()); } else if (JavaClassHelper.isImplementsInterface(type, Iterable.class)) { isIndexed = true; Class genericType; if (type instanceof EPTypeClassParameterized) { genericType = ((EPTypeClassParameterized) type).getParameters()[0].getType(); } else { genericType = Object.class; } isFragment = JavaClassHelper.isFragmentableType(genericType); } else { isMapped = false; isFragment = JavaClassHelper.isFragmentableType(type); } simpleProperties.put(propertyName, new PropertyInfo(type, getter, desc)); // Recognize that there may be properties with overlapping case-insentitive names if (smartResolutionStyle) { // Find the property in the smart property table String smartPropertyName = propertyName.toLowerCase(Locale.ENGLISH); List<PropertyInfo> propertyInfoList = simpleSmartPropertyTable.get(smartPropertyName); if (propertyInfoList == null) { propertyInfoList = new ArrayList<PropertyInfo>(); simpleSmartPropertyTable.put(smartPropertyName, propertyInfoList); } // Enter the property into the smart property list PropertyInfo propertyInfo = new PropertyInfo(type, getter, desc); propertyInfoList.add(propertyInfo); } } else if (desc.getPropertyType().equals(EventPropertyType.MAPPED)) { mappedPropertyDescriptors.put(propertyName, desc); underlyingType = desc.getReturnType(clazz); isRequiresIndex = false; isRequiresMapkey = desc.getReadMethod().getParameterTypes().length > 0; isIndexed = false; isMapped = true; isFragment = false; // Recognize that there may be properties with overlapping case-insentitive names if (smartResolutionStyle) { // Find the property in the smart property table String smartPropertyName = propertyName.toLowerCase(Locale.ENGLISH); List<PropertyInfo> propertyInfoList = mappedSmartPropertyTable.get(smartPropertyName); if (propertyInfoList == null) { propertyInfoList = new ArrayList<PropertyInfo>(); mappedSmartPropertyTable.put(smartPropertyName, propertyInfoList); } // Enter the property into the smart property list PropertyInfo propertyInfo = new PropertyInfo(desc.getReturnType(clazz), null, desc); propertyInfoList.add(propertyInfo); } } else if (desc.getPropertyType().equals(EventPropertyType.INDEXED)) { indexedPropertyDescriptors.put(propertyName, desc); underlyingType = desc.getReturnType(clazz); isRequiresIndex = desc.getReadMethod().getParameterTypes().length > 0; isRequiresMapkey = false; isIndexed = true; isMapped = false; isFragment = JavaClassHelper.isFragmentableType(desc.getReturnType(clazz)); if (smartResolutionStyle) { // Find the property in the smart property table String smartPropertyName = propertyName.toLowerCase(Locale.ENGLISH); List<PropertyInfo> propertyInfoList = indexedSmartPropertyTable.get(smartPropertyName); if (propertyInfoList == null) { propertyInfoList = new ArrayList<PropertyInfo>(); indexedSmartPropertyTable.put(smartPropertyName, propertyInfoList); } // Enter the property into the smart property list PropertyInfo propertyInfo = new PropertyInfo(desc.getReturnType(clazz), null, desc); propertyInfoList.add(propertyInfo); } } else { continue; } propertyNames[count] = desc.getPropertyName(); EventPropertyDescriptor descriptor = new EventPropertyDescriptor(desc.getPropertyName(), underlyingType, isRequiresIndex, isRequiresMapkey, isIndexed, isMapped, isFragment); propertyDescriptors[count++] = descriptor; propertyDescriptorMap.put(descriptor.getPropertyName(), descriptor); } // Determine event type super types EPTypeClass[] superTypes = getSuperTypes(clazz.getType()); if (superTypes != null && superTypes.length == 0) { superTypes = null; } // Determine deep supertypes // Get Java super types (superclasses and interfaces), deep get of all in the tree Set<EPTypeClass> deepSuperTypes = new HashSet<>(); getSuper(clazz.getType(), deepSuperTypes); removeJavaLibInterfaces(deepSuperTypes); // Remove "java." super types return new BeanEventTypeStem(clazz, optionalConfig, propertyNames, simpleProperties, mappedPropertyDescriptors, indexedPropertyDescriptors, superTypes, deepSuperTypes, propertyResolutionStyle, simpleSmartPropertyTable, indexedSmartPropertyTable, mappedSmartPropertyTable, propertyDescriptors, propertyDescriptorMap); } private static EPTypeClass[] getSuperTypes(Class clazz) { List<EPTypeClass> superclasses = new LinkedList<>(); // add superclass Class superClass = clazz.getSuperclass(); if (superClass != null) { superclasses.add(ClassHelperGenericType.getClassEPType(superClass)); } // add interfaces Class[] interfaces = clazz.getInterfaces(); for (Class interfaceItem : interfaces) { superclasses.add(ClassHelperGenericType.getClassEPType(interfaceItem)); } // Build super types, ignoring java language types List<EPTypeClass> superTypes = new LinkedList<>(); for (EPTypeClass superclass : superclasses) { String superclassName = superclass.getType().getName(); if (!superclassName.startsWith("java")) { superTypes.add(superclass); } } return superTypes.toArray(new EPTypeClass[superTypes.size()]); } /** * Add the given class's implemented interfaces and superclasses to the result set of classes. * * @param clazz to introspect * @param result to add classes to */ protected static void getSuper(Class clazz, Set<EPTypeClass> result) { getSuperInterfaces(clazz, result); getSuperClasses(clazz, result); } private static void getSuperInterfaces(Class clazz, Set<EPTypeClass> result) { Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { result.add(ClassHelperGenericType.getClassEPType(interfaces[i])); getSuperInterfaces(interfaces[i], result); } } private static void getSuperClasses(Class clazz, Set<EPTypeClass> result) { Class superClass = clazz.getSuperclass(); if (superClass == null) { return; } result.add(ClassHelperGenericType.getClassEPType(superClass)); getSuper(superClass, result); } private static void removeJavaLibInterfaces(Set<EPTypeClass> classes) { EPTypeClass[] types = classes.toArray(new EPTypeClass[0]); for (EPTypeClass clazz : types) { if (clazz.getType().getName().startsWith("java")) { classes.remove(clazz); } } } }
espertechinc/esper
common/src/main/java/com/espertech/esper/common/internal/event/bean/introspect/BeanEventTypeStemBuilder.java
2,873
// Determine deep supertypes
line_comment
nl
/* *************************************************************************************** * Copyright (C) 2006 EsperTech, Inc. All rights reserved. * * http://www.espertech.com/esper * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * *************************************************************************************** */ package com.espertech.esper.common.internal.event.bean.introspect; import com.espertech.esper.common.client.EventPropertyDescriptor; import com.espertech.esper.common.client.configuration.common.ConfigurationCommonEventTypeBean; import com.espertech.esper.common.client.type.EPTypeClass; import com.espertech.esper.common.client.type.EPTypeClassParameterized; import com.espertech.esper.common.client.util.PropertyResolutionStyle; import com.espertech.esper.common.internal.event.bean.core.PropertyStem; import com.espertech.esper.common.internal.event.bean.getter.ReflectionPropFieldGetterFactory; import com.espertech.esper.common.internal.event.bean.getter.ReflectionPropMethodGetterFactory; import com.espertech.esper.common.internal.event.core.EventPropertyType; import com.espertech.esper.common.internal.event.core.EventTypeUtility; import com.espertech.esper.common.internal.util.ClassHelperGenericType; import com.espertech.esper.common.internal.util.JavaClassHelper; import java.util.*; public class BeanEventTypeStemBuilder { private final ConfigurationCommonEventTypeBean optionalConfig; private final PropertyResolutionStyle propertyResolutionStyle; private final boolean smartResolutionStyle; public BeanEventTypeStemBuilder(ConfigurationCommonEventTypeBean optionalConfig, PropertyResolutionStyle defaultPropertyResolutionStyle) { this.optionalConfig = optionalConfig; if (optionalConfig != null) { this.propertyResolutionStyle = optionalConfig.getPropertyResolutionStyle(); } else { this.propertyResolutionStyle = defaultPropertyResolutionStyle; } this.smartResolutionStyle = propertyResolutionStyle.equals(PropertyResolutionStyle.CASE_INSENSITIVE) || propertyResolutionStyle.equals(PropertyResolutionStyle.DISTINCT_CASE_INSENSITIVE); } public BeanEventTypeStem make(EPTypeClass clazz) { EventTypeUtility.validateEventBeanClassVisibility(clazz.getType()); PropertyListBuilder propertyListBuilder = PropertyListBuilderFactory.createBuilder(optionalConfig); List<PropertyStem> properties = propertyListBuilder.assessProperties(clazz.getType()); EventPropertyDescriptor[] propertyDescriptors = new EventPropertyDescriptor[properties.size()]; Map<String, EventPropertyDescriptor> propertyDescriptorMap = new HashMap<>(); String[] propertyNames = new String[properties.size()]; Map<String, PropertyInfo> simpleProperties = new HashMap<>(); Map<String, PropertyStem> mappedPropertyDescriptors = new HashMap<>(); Map<String, PropertyStem> indexedPropertyDescriptors = new HashMap<>(); Map<String, List<PropertyInfo>> simpleSmartPropertyTable = null; Map<String, List<PropertyInfo>> mappedSmartPropertyTable = null; Map<String, List<PropertyInfo>> indexedSmartPropertyTable = null; if (smartResolutionStyle) { simpleSmartPropertyTable = new HashMap<>(); mappedSmartPropertyTable = new HashMap<>(); indexedSmartPropertyTable = new HashMap<>(); } int count = 0; for (PropertyStem desc : properties) { String propertyName = desc.getPropertyName(); EPTypeClass underlyingType; boolean isRequiresIndex; boolean isRequiresMapkey; boolean isIndexed; boolean isMapped; boolean isFragment; if (desc.getPropertyType().equals(EventPropertyType.SIMPLE)) { EventPropertyGetterSPIFactory getter; EPTypeClass type; if (desc.getReadMethod() != null) { getter = new ReflectionPropMethodGetterFactory(desc.getReadMethod()); type = ClassHelperGenericType.getMethodReturnEPType(desc.getReadMethod(), clazz); } else if (desc.getAccessorField() != null) { getter = new ReflectionPropFieldGetterFactory(desc.getAccessorField()); type = ClassHelperGenericType.getFieldEPType(desc.getAccessorField(), clazz); } else { // ignore property continue; } underlyingType = type; isRequiresIndex = false; isRequiresMapkey = false; isIndexed = false; isMapped = false; if (JavaClassHelper.isImplementsInterface(type, Map.class)) { isMapped = true; // We do not yet allow to fragment maps entries. // Class genericType = JavaClassHelper.getGenericReturnTypeMap(desc.getReadMethod(), desc.getAccessorField()); isFragment = false; } else if (type.getType().isArray()) { isIndexed = true; isFragment = JavaClassHelper.isFragmentableType(type.getType().getComponentType()); } else if (JavaClassHelper.isImplementsInterface(type, Iterable.class)) { isIndexed = true; Class genericType; if (type instanceof EPTypeClassParameterized) { genericType = ((EPTypeClassParameterized) type).getParameters()[0].getType(); } else { genericType = Object.class; } isFragment = JavaClassHelper.isFragmentableType(genericType); } else { isMapped = false; isFragment = JavaClassHelper.isFragmentableType(type); } simpleProperties.put(propertyName, new PropertyInfo(type, getter, desc)); // Recognize that there may be properties with overlapping case-insentitive names if (smartResolutionStyle) { // Find the property in the smart property table String smartPropertyName = propertyName.toLowerCase(Locale.ENGLISH); List<PropertyInfo> propertyInfoList = simpleSmartPropertyTable.get(smartPropertyName); if (propertyInfoList == null) { propertyInfoList = new ArrayList<PropertyInfo>(); simpleSmartPropertyTable.put(smartPropertyName, propertyInfoList); } // Enter the property into the smart property list PropertyInfo propertyInfo = new PropertyInfo(type, getter, desc); propertyInfoList.add(propertyInfo); } } else if (desc.getPropertyType().equals(EventPropertyType.MAPPED)) { mappedPropertyDescriptors.put(propertyName, desc); underlyingType = desc.getReturnType(clazz); isRequiresIndex = false; isRequiresMapkey = desc.getReadMethod().getParameterTypes().length > 0; isIndexed = false; isMapped = true; isFragment = false; // Recognize that there may be properties with overlapping case-insentitive names if (smartResolutionStyle) { // Find the property in the smart property table String smartPropertyName = propertyName.toLowerCase(Locale.ENGLISH); List<PropertyInfo> propertyInfoList = mappedSmartPropertyTable.get(smartPropertyName); if (propertyInfoList == null) { propertyInfoList = new ArrayList<PropertyInfo>(); mappedSmartPropertyTable.put(smartPropertyName, propertyInfoList); } // Enter the property into the smart property list PropertyInfo propertyInfo = new PropertyInfo(desc.getReturnType(clazz), null, desc); propertyInfoList.add(propertyInfo); } } else if (desc.getPropertyType().equals(EventPropertyType.INDEXED)) { indexedPropertyDescriptors.put(propertyName, desc); underlyingType = desc.getReturnType(clazz); isRequiresIndex = desc.getReadMethod().getParameterTypes().length > 0; isRequiresMapkey = false; isIndexed = true; isMapped = false; isFragment = JavaClassHelper.isFragmentableType(desc.getReturnType(clazz)); if (smartResolutionStyle) { // Find the property in the smart property table String smartPropertyName = propertyName.toLowerCase(Locale.ENGLISH); List<PropertyInfo> propertyInfoList = indexedSmartPropertyTable.get(smartPropertyName); if (propertyInfoList == null) { propertyInfoList = new ArrayList<PropertyInfo>(); indexedSmartPropertyTable.put(smartPropertyName, propertyInfoList); } // Enter the property into the smart property list PropertyInfo propertyInfo = new PropertyInfo(desc.getReturnType(clazz), null, desc); propertyInfoList.add(propertyInfo); } } else { continue; } propertyNames[count] = desc.getPropertyName(); EventPropertyDescriptor descriptor = new EventPropertyDescriptor(desc.getPropertyName(), underlyingType, isRequiresIndex, isRequiresMapkey, isIndexed, isMapped, isFragment); propertyDescriptors[count++] = descriptor; propertyDescriptorMap.put(descriptor.getPropertyName(), descriptor); } // Determine event type super types EPTypeClass[] superTypes = getSuperTypes(clazz.getType()); if (superTypes != null && superTypes.length == 0) { superTypes = null; } // Determine deep<SUF> // Get Java super types (superclasses and interfaces), deep get of all in the tree Set<EPTypeClass> deepSuperTypes = new HashSet<>(); getSuper(clazz.getType(), deepSuperTypes); removeJavaLibInterfaces(deepSuperTypes); // Remove "java." super types return new BeanEventTypeStem(clazz, optionalConfig, propertyNames, simpleProperties, mappedPropertyDescriptors, indexedPropertyDescriptors, superTypes, deepSuperTypes, propertyResolutionStyle, simpleSmartPropertyTable, indexedSmartPropertyTable, mappedSmartPropertyTable, propertyDescriptors, propertyDescriptorMap); } private static EPTypeClass[] getSuperTypes(Class clazz) { List<EPTypeClass> superclasses = new LinkedList<>(); // add superclass Class superClass = clazz.getSuperclass(); if (superClass != null) { superclasses.add(ClassHelperGenericType.getClassEPType(superClass)); } // add interfaces Class[] interfaces = clazz.getInterfaces(); for (Class interfaceItem : interfaces) { superclasses.add(ClassHelperGenericType.getClassEPType(interfaceItem)); } // Build super types, ignoring java language types List<EPTypeClass> superTypes = new LinkedList<>(); for (EPTypeClass superclass : superclasses) { String superclassName = superclass.getType().getName(); if (!superclassName.startsWith("java")) { superTypes.add(superclass); } } return superTypes.toArray(new EPTypeClass[superTypes.size()]); } /** * Add the given class's implemented interfaces and superclasses to the result set of classes. * * @param clazz to introspect * @param result to add classes to */ protected static void getSuper(Class clazz, Set<EPTypeClass> result) { getSuperInterfaces(clazz, result); getSuperClasses(clazz, result); } private static void getSuperInterfaces(Class clazz, Set<EPTypeClass> result) { Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { result.add(ClassHelperGenericType.getClassEPType(interfaces[i])); getSuperInterfaces(interfaces[i], result); } } private static void getSuperClasses(Class clazz, Set<EPTypeClass> result) { Class superClass = clazz.getSuperclass(); if (superClass == null) { return; } result.add(ClassHelperGenericType.getClassEPType(superClass)); getSuper(superClass, result); } private static void removeJavaLibInterfaces(Set<EPTypeClass> classes) { EPTypeClass[] types = classes.toArray(new EPTypeClass[0]); for (EPTypeClass clazz : types) { if (clazz.getType().getName().startsWith("java")) { classes.remove(clazz); } } } }
200892_29
// Copyright (c) 2020-2024 ginlo.net GmbH package eu.ginlo_apps.ginlo.util; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import android.webkit.MimeTypeMap; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import eu.ginlo_apps.ginlo.R; import eu.ginlo_apps.ginlo.log.LogUtil; import eu.ginlo_apps.ginlo.model.DecryptedMessage; public class MimeUtil { private static final String TAG = "MimeUtil"; // Image mime types public static final String MIME_TYPE_IMAGE_WILDCARD = "image/*"; public static final String MIME_TYPE_IMAGE_JPEG = "image/jpeg"; public static final String MIME_TYPE_IMAGE_JPG = "image/jpg"; public static final String MIME_TYPE_IMAGE_JPE = "image/jpe"; public static final String MIME_TYPE_IMAGE_APNG = "image/apng"; public static final String MIME_TYPE_IMAGE_AVIF = "image/avif"; public static final String MIME_TYPE_IMAGE_GIF = "image/gif"; public static final String MIME_TYPE_IMAGE_PNG = "image/png"; public static final String MIME_TYPE_IMAGE_PSD = "image/psd"; public static final String MIME_TYPE_IMAGE_BMP = "image/bmp"; public static final String MIME_TYPE_IMAGE_XBMP = "image/x-bmp"; public static final String MIME_TYPE_IMAGE_XMSBMP = "image/x-ms-bmp"; public static final String MIME_TYPE_IMAGE_TIFF = "image/tiff"; public static final String MIME_TYPE_IMAGE_TIF = "image/tif"; public static final String MIME_TYPE_IMAGE_SVG = "image/svg+xml"; public static final String MIME_TYPE_IMAGE_WEBP = "image/webp"; public static final String MIME_TYPE_IMAGE_HEIF = "image/heif"; public static final String MIME_TYPE_IMAGE_HEIC = "image/heic"; public static final String MIME_TYPE_IMAGE_HEIF_SEQUENCE = "image/heif-sequence"; public static final String MIME_TYPE_IMAGE_HEIC_SEQUENCE = "image/heic-sequence"; // Lottie public static final String MIME_TYPE_APP_JSON = "application/json"; // Audio mime types public static final String MIME_TYPE_AUDIO_WILDCARD = "audio/*"; public static final String MIME_TYPE_AUDIO_MPEG = "audio/mpeg"; public static final String MIME_TYPE_AUDIO_3GPP = "audio/3gpp"; public static final String MIME_TYPE_AUDIO_MP3 = "audio/mp3"; public static final String MIME_TYPE_AUDIO_OGG = "audio/ogg"; public static final String MIME_TYPE_AUDIO_FLAC = "audio/flac"; public static final String MIME_TYPE_AUDIO_AAC = "audio/aac"; public static final String MIME_TYPE_AUDIO_MP4 = "audio/mp4"; public static final String MIME_TYPE_AUDIO_WAVE = "audio/wave"; public static final String MIME_TYPE_AUDIO_WAV = "audio/wav"; public static final String MIME_TYPE_AUDIO_WEBM = "audio/webm"; public static final String MIME_TYPE_AUDIO_MATROSKA = "audio/x-matroska"; // Video mime types public static final String MIME_TYPE_VIDEO_WILDCARD = "video/*"; public static final String MIME_TYPE_VIDEO_MPEG = "video/mpeg"; public static final String MIME_TYPE_VIDEO_3GPP = "video/3gpp"; public static final String MIME_TYPE_VIDEO_OGG = "video/ogg"; public static final String MIME_TYPE_VIDEO_MP4 = "video/mp4"; public static final String MIME_TYPE_VIDEO_WEBM = "video/webm"; public static final String MIME_TYPE_VIDEO_MATROSKA = "video/x-matroska"; public static final String MIME_TYPE_VIDEO_QT = "video/quicktime"; public static final String MIME_TYPE_VIDEO_AVI = "video/x-msvideo"; // (Proprietary) document format mime types public static final String MIME_TYPE_APP_PDF = "application/pdf"; public static final String MIME_TYPE_MSPOWERPOINT = "application/mspowerpoint"; public static final String MIME_TYPE_MSPOWERPOINT2 = "application/vnd.ms-powerpoint"; public static final String MIME_TYPE_MSPOWERPOINT_MACRO = "application/vnd.ms-powerpoint.presentation.macroenabled.12"; public static final String MIME_TYPE_OOPOWERPOINT = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; public static final String MIME_TYPE_APPLE_KEYNOTE = "application/x-iwork-keynote-sffkey"; public static final String MIME_TYPE_MSWORD = "application/msword"; public static final String MIME_TYPE_OOWORD = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; public static final String MIME_TYPE_APPLE_PAGES = "application/x-iwork-pages-sffpages"; public static final String MIME_TYPE_MSEXCEL = "application/msexcel"; public static final String MIME_TYPE_VND_MSEXCEL = "application/vnd.ms-excel"; public static final String MIME_TYPE_OOEXCEL = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; public static final String MIME_TYPE_CSV = "text/csv"; public static final String MIME_TYPE_CSV2 = "text/comma-separated-values"; public static final String MIME_TYPE_APPLE_NUMBERS = "application/x-iwork-numbers-sffnumbers"; // Compression public static final String MIME_TYPE_ZIP = "application/zip"; public static final String MIME_TYPE_GZIP = "application/gzip"; public static final String MIME_TYPE_7ZIP = "application/x-7z-compressed"; public static final String MIME_TYPE_RAR = "application/x-rar-compressed"; // ginlo: AVC extensions public static final String MIME_TYPE_TEXT_V_CALL = "text/x-ginlo-call-invite"; public static final String MIME_TYPE_APP_GINLO_CONTROL = "application/x-ginlo-control-message"; // ginlo: Helper type for rich content public static final String MIME_TYPE_APP_GINLO_RICH_CONTENT = "application/x-ginlo-rich-content"; public static final String MIME_TYPE_APP_GINLO_LOTTIE = "application/x-ginlo-lottie"; // Others public static final String MIME_TYPE_TEXT_PLAIN = "text/plain"; public static final String MIME_TYPE_TEXT_RSS = "text/rss"; public static final String MIME_TYPE_TEXT_V_CARD = "text/x-vcard"; public static final String MIME_TYPE_MODEL_LOCATION = "model/location"; // To be compatible to apps with typos public static final String MIME_TYPE_APP_OCTET_STREAM = "application/octetstream"; public static final String MIME_TYPE_APP_OCTETSTREAM = "application/octet-stream"; public static final int MIMETYPE_NOT_FOUND = -1; // Schemas public static final String CONTENT = "content"; public static final String FILE = "file"; private final Context context; private static final ArrayList<String> imageMimeTypes = new ArrayList<>(); private static final ArrayList<String> videoMimeTypes = new ArrayList<>(); private static final ArrayList<String> audioMimeTypes = new ArrayList<>(); private static final ArrayList<String> richContentMimeTypes = new ArrayList<>(); public MimeUtil(Context context) { this.context = context; } /** * Build and/or return a list of compatible image mimetypes * @return */ public static ArrayList<String> getImageMimeTypes() { if(imageMimeTypes.isEmpty()) { imageMimeTypes.add(MIME_TYPE_IMAGE_JPEG); imageMimeTypes.add(MIME_TYPE_IMAGE_JPG); imageMimeTypes.add(MIME_TYPE_IMAGE_JPE); imageMimeTypes.add(MIME_TYPE_IMAGE_APNG); imageMimeTypes.add(MIME_TYPE_IMAGE_AVIF); imageMimeTypes.add(MIME_TYPE_IMAGE_GIF); imageMimeTypes.add(MIME_TYPE_IMAGE_PNG); //imageMimeTypes.add(MIME_TYPE_IMAGE_PSD); imageMimeTypes.add(MIME_TYPE_IMAGE_BMP); imageMimeTypes.add(MIME_TYPE_IMAGE_XBMP); imageMimeTypes.add(MIME_TYPE_IMAGE_XMSBMP); imageMimeTypes.add(MIME_TYPE_IMAGE_TIFF); imageMimeTypes.add(MIME_TYPE_IMAGE_TIF); imageMimeTypes.add(MIME_TYPE_IMAGE_SVG); imageMimeTypes.add(MIME_TYPE_IMAGE_WEBP); imageMimeTypes.add(MIME_TYPE_IMAGE_HEIF); imageMimeTypes.add(MIME_TYPE_IMAGE_HEIC); imageMimeTypes.add(MIME_TYPE_IMAGE_HEIF_SEQUENCE); imageMimeTypes.add(MIME_TYPE_IMAGE_HEIC_SEQUENCE); } return imageMimeTypes; } /** * Build and/or return a list of compatible audio mimetypes * @return */ public static ArrayList<String> getAudioMimeTypes() { if (audioMimeTypes.isEmpty()) { audioMimeTypes.add(MIME_TYPE_AUDIO_MPEG); audioMimeTypes.add(MIME_TYPE_AUDIO_3GPP); audioMimeTypes.add(MIME_TYPE_AUDIO_MP3); audioMimeTypes.add(MIME_TYPE_AUDIO_OGG); audioMimeTypes.add(MIME_TYPE_AUDIO_FLAC); audioMimeTypes.add(MIME_TYPE_AUDIO_AAC); audioMimeTypes.add(MIME_TYPE_AUDIO_MP4); audioMimeTypes.add(MIME_TYPE_AUDIO_MATROSKA); audioMimeTypes.add(MIME_TYPE_AUDIO_WAVE); audioMimeTypes.add(MIME_TYPE_AUDIO_WAV); audioMimeTypes.add(MIME_TYPE_AUDIO_WEBM); } return audioMimeTypes; } /** * Build and/or return a list of compatible video mimetypes * @return */ public static ArrayList<String> getVideoMimeTypes() { if(videoMimeTypes.isEmpty()) { videoMimeTypes.add(MIME_TYPE_VIDEO_MPEG); videoMimeTypes.add(MIME_TYPE_VIDEO_3GPP); videoMimeTypes.add(MIME_TYPE_VIDEO_OGG); videoMimeTypes.add(MIME_TYPE_VIDEO_MP4); videoMimeTypes.add(MIME_TYPE_VIDEO_MATROSKA); videoMimeTypes.add(MIME_TYPE_VIDEO_WEBM); videoMimeTypes.add(MIME_TYPE_VIDEO_QT); videoMimeTypes.add(MIME_TYPE_VIDEO_AVI); } return videoMimeTypes; } /** * Build and/or return a list of compatible rich content (gifs, stickers etc.) mimetypes * @return */ public static ArrayList<String> getRichContentMimeTypes() { if(richContentMimeTypes.isEmpty()) { richContentMimeTypes.add(MIME_TYPE_APP_GINLO_RICH_CONTENT); // proprietary internal type richContentMimeTypes.add(MIME_TYPE_APP_GINLO_LOTTIE); // proprietary internal type richContentMimeTypes.add(MIME_TYPE_APP_JSON); // Used for lottie animations richContentMimeTypes.add(MIME_TYPE_IMAGE_GIF); richContentMimeTypes.add(MIME_TYPE_IMAGE_WEBP); richContentMimeTypes.add(MIME_TYPE_IMAGE_PNG); } return richContentMimeTypes; } /** * Check Uri for known image mimetype * @param context * @param contentUri * @return */ public static boolean checkImageUriMimetype(Context context, Uri contentUri) { return isKnownUriMimeType(context, contentUri, getImageMimeTypes()); } /** * Check Uri for known audio mimetype * @param context * @param contentUri * @return */ public static boolean checkAudioUriMimetype(Context context, Uri contentUri) { return isKnownUriMimeType(context, contentUri, getAudioMimeTypes()); } /** * Check Uri for known video mimetype * @param context * @param contentUri * @return */ public static boolean checkVideoUriMimetype(Context context, Uri contentUri) { return isKnownUriMimeType(context, contentUri, getVideoMimeTypes()); } /** * Check Uri for known rich content mimetypes * @param context * @param contentUri * @return */ public static boolean checkRichContentUriMimetype(Context context, Uri contentUri) { return isKnownUriMimeType(context, contentUri, getRichContentMimeTypes()); } /** * Check Uri for requested mimetype * @param context * @param contentUri * @return */ public static boolean isKnownUriMimeType(Context context, Uri contentUri, ArrayList<String> knownMimeTypes) { if (context == null || contentUri == null) { return false; } LogUtil.d(TAG, "isKnownUriMimeType: Check " + contentUri.getPath() + " against: " + knownMimeTypes); String mimeType = getMimeTypeForUri(context, contentUri); return StringUtil.isInList(mimeType, knownMimeTypes, true); } /** * Is given mimetype for Glide processing? * @param mimeType * @return */ public static boolean isGlideMimetype(String mimeType) { if(StringUtil.isNullOrEmpty(mimeType)) { return false; } return (mimeType.equals(MIME_TYPE_IMAGE_GIF) || mimeType.equals(MIME_TYPE_IMAGE_TIF) || mimeType.equals(MIME_TYPE_IMAGE_TIFF) || mimeType.equals(MIME_TYPE_IMAGE_WEBP) || mimeType.equals(MIME_TYPE_IMAGE_JPEG) || mimeType.equals(MIME_TYPE_IMAGE_JPG) || mimeType.equals(MIME_TYPE_IMAGE_JPE) || mimeType.equals(MIME_TYPE_IMAGE_SVG) || mimeType.equals(MIME_TYPE_IMAGE_BMP) || mimeType.equals(MIME_TYPE_IMAGE_XBMP) || mimeType.equals(MIME_TYPE_IMAGE_XMSBMP) || mimeType.equals(MIME_TYPE_IMAGE_PNG) ); } /** * Must analyze. Lottie files are mostly json files - check "magic bytes" * @param fileToCheck * @return */ public static boolean isLottieFile(String mimeType, File fileToCheck) { boolean returnValue = false; if(mimeType != null && mimeType.equals(MIME_TYPE_APP_GINLO_LOTTIE)) { // Has already been analyzed. Trust that. returnValue = true; } else if (mimeType == null || mimeType.equals(MIME_TYPE_APP_JSON)) { if (fileToCheck != null) { if (fileToCheck.getName().endsWith(".tgs")) { LogUtil.d(TAG, "isLottieFile: Got first hint with file extension .tgs"); // This is possible, but we should dig deeper. //returnValue = true; } LogUtil.d(TAG, "isLottieFile: Analyze " + fileToCheck + " ..."); byte[] magic = "{\"tgs\"".getBytes(StandardCharsets.UTF_8); if (FileUtil.haveFileMagic(fileToCheck, magic)) { LogUtil.d(TAG, "isLottieFile: Yes. Identified by magic " + Arrays.toString(magic)); returnValue = true; } else { magic = "{\"v\"".getBytes(StandardCharsets.UTF_8); if (FileUtil.haveFileMagic(fileToCheck, magic)) { LogUtil.d(TAG, "isLottieFile: Yes. Identified by magic " + Arrays.toString(magic)); returnValue = true; } } } } return returnValue; } /** * Is given mimetype a compatible audio mimetype? * @param mimeType * @return */ public static boolean isAudioMimetype(String mimeType, boolean withWildcard) { boolean haveAudioMimetype = false; if(!StringUtil.isNullOrEmpty(mimeType)) { if(withWildcard && MIME_TYPE_AUDIO_WILDCARD.contains(mimeType)) { haveAudioMimetype = true; } else { haveAudioMimetype = getAudioMimeTypes().contains(mimeType); } } return haveAudioMimetype; } /** * Is given mimetype a compatible image mimetype? * @param mimeType * @return */ public static boolean isImageMimetype(String mimeType, boolean withWildcard) { boolean haveImageMimetype = false; if(!StringUtil.isNullOrEmpty(mimeType)) { if(withWildcard && MIME_TYPE_IMAGE_WILDCARD.contains(mimeType)) { haveImageMimetype = true; } else { haveImageMimetype = getImageMimeTypes().contains(mimeType); } } return haveImageMimetype; } /** * Is given mimetype a compatible video mimetype? * @param mimeType * @return */ public static boolean isVideoMimetype(String mimeType, boolean withWildcard) { boolean haveVideoMimetype = false; if(!StringUtil.isNullOrEmpty(mimeType)) { if(withWildcard && MIME_TYPE_VIDEO_WILDCARD.contains(mimeType)) { haveVideoMimetype = true; } else { haveVideoMimetype = getVideoMimeTypes().contains(mimeType); } } return haveVideoMimetype; } /** * Is given mimetype a compatible rich content mimetype? * These are all we have our internal Glide/RLottie components for. * @param mimeType * @return */ public static boolean isRichContentMimetype(String mimeType) { if(StringUtil.isNullOrEmpty(mimeType)) { return false; } return getRichContentMimeTypes().contains(mimeType); } public static String getMimeTypeForUri(Context context, Uri contentUri) { String type = null; if (contentUri != null) { // First try this ContentResolver cR = context.getContentResolver(); type = cR.getType(contentUri); LogUtil.d(TAG, "getMimeTypeForUri: ContentResolver brought: " + type); if(MimeUtil.hasEmptyOrUnspecificMimeType(type)) { final String keepResult = type; // So we should try that type = getMimeTypeFromFilename(contentUri.getPath()); LogUtil.d(TAG, "getMimeTypeForUri: Pathname brought: " + type); // Step back if the latest result isn't even better ... if(type == null && keepResult != null) { type = keepResult; } } } return type; } public static String getExtensionForUri(Context context, final Uri uri) { String extension = null; String mimetype = getMimeTypeForUri(context, uri); if (!StringUtil.isNullOrEmpty(mimetype)) { MimeTypeMap mime = MimeTypeMap.getSingleton(); extension = mime.getExtensionFromMimeType(mimetype); } return extension; } public static int getIconForMimeType(String mimeType) { int resID = MIMETYPE_NOT_FOUND; switch (mimeType) { case MIME_TYPE_APP_PDF: resID = R.drawable.data_pdf; break; case MIME_TYPE_MSPOWERPOINT: case MIME_TYPE_MSPOWERPOINT2: case MIME_TYPE_MSPOWERPOINT_MACRO: case MIME_TYPE_OOPOWERPOINT: case MIME_TYPE_APPLE_KEYNOTE: resID = R.drawable.data_praesent; break; case MIME_TYPE_MSWORD: case MIME_TYPE_OOWORD: case MIME_TYPE_APPLE_PAGES: resID = R.drawable.data_doc; break; case MIME_TYPE_MSEXCEL: case MIME_TYPE_VND_MSEXCEL: case MIME_TYPE_OOEXCEL: case MIME_TYPE_CSV: case MIME_TYPE_CSV2: case MIME_TYPE_APPLE_NUMBERS: resID = R.drawable.data_xls; break; case MIME_TYPE_ZIP: case MIME_TYPE_GZIP: case MIME_TYPE_7ZIP: case MIME_TYPE_RAR: resID = R.drawable.data_zip; break; default: if (isImageMimetype(mimeType, false)) { resID = R.drawable.media_photo; } else if (isVideoMimetype(mimeType, false)) { resID = R.drawable.media_movie; } else if (isAudioMimetype(mimeType, false)) { resID = R.drawable.media_audio; } } return resID; } public static Boolean hasUnspecificBinaryMimeType(String mimeType) { return MimeUtil.MIME_TYPE_APP_OCTETSTREAM.equals(mimeType) || MimeUtil.MIME_TYPE_APP_OCTET_STREAM.equals(mimeType); } public static Boolean hasEmptyOrUnspecificMimeType(String mimeType) { return StringUtil.isNullOrEmpty(mimeType) || MimeUtil.MIME_TYPE_APP_GINLO_RICH_CONTENT.equals(mimeType) || MimeUtil.MIME_TYPE_TEXT_PLAIN.equals(mimeType) || hasUnspecificBinaryMimeType(mimeType); } public static String grabMimeType(String filename, DecryptedMessage decryptedMsg, String defaultMimeType) { // Use all we have to get a mime type. String mimeType = decryptedMsg.getContentType(); String tmpMimeType = null; LogUtil.d(TAG, "grabMimeType: Check mimetype in ContentType: " + mimeType); if(hasEmptyOrUnspecificMimeType(mimeType)) { tmpMimeType = mimeType; mimeType = decryptedMsg.getFileMimetype(); LogUtil.d(TAG, "grabMimeType: Check mimetype in FileMimetype: " + mimeType); if (hasEmptyOrUnspecificMimeType(mimeType)) { // Only alibi? Dig deeper, but keep what we have if (tmpMimeType == null) { tmpMimeType = mimeType; } mimeType = MimeUtil.getMimeTypeFromFilename(filename); LogUtil.d(TAG, "grabMimeType: Check mimetype in file pathname: " + mimeType); if (StringUtil.isNullOrEmpty(mimeType)) { // Ok, use what we have mimeType = tmpMimeType != null ? tmpMimeType : defaultMimeType; LogUtil.d(TAG, "grabMimeType: No more options - finally we have: " + mimeType); } } } LogUtil.d(TAG, "grabMimeType: Using " + mimeType); return mimeType; } public static String getMimeTypeFromFilename(String filename) { if (filename == null) { return null; } String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(filename.replace(" ", "")); if (StringUtil.isNullOrEmpty(extension)) { int dotIndex = filename.lastIndexOf('.'); if (dotIndex > -1) { extension = filename.substring(dotIndex + 1); } } if (extension != null) { // apple typen werden nicht erkannt... // .key wird als pgp-datei erkannt... switch (extension.toLowerCase(Locale.US)) { case "keynote": case "key": return MIME_TYPE_APPLE_KEYNOTE; case "numbers": return MIME_TYPE_APPLE_NUMBERS; case "pages": return MIME_TYPE_APPLE_PAGES; case "odt": return MIME_TYPE_OOWORD; case "ods": return MIME_TYPE_OOEXCEL; case "odp": return MIME_TYPE_OOPOWERPOINT; case "json": case "tgs": // Stickers / lottie animations come as json-files return MimeUtil.MIME_TYPE_APP_JSON; case "heic": return MimeUtil.MIME_TYPE_IMAGE_HEIC; case "heif": return MimeUtil.MIME_TYPE_IMAGE_HEIF; default: break; } MimeTypeMap mime = MimeTypeMap.getSingleton(); type = mime.getMimeTypeFromExtension(extension.toLowerCase(Locale.US)); } return type; } }
cdskev/ginlo-android
app/src/main/java/eu/ginlo_apps/ginlo/util/MimeUtil.java
6,204
// apple typen werden nicht erkannt...
line_comment
nl
// Copyright (c) 2020-2024 ginlo.net GmbH package eu.ginlo_apps.ginlo.util; import android.content.ContentResolver; import android.content.Context; import android.net.Uri; import android.webkit.MimeTypeMap; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import eu.ginlo_apps.ginlo.R; import eu.ginlo_apps.ginlo.log.LogUtil; import eu.ginlo_apps.ginlo.model.DecryptedMessage; public class MimeUtil { private static final String TAG = "MimeUtil"; // Image mime types public static final String MIME_TYPE_IMAGE_WILDCARD = "image/*"; public static final String MIME_TYPE_IMAGE_JPEG = "image/jpeg"; public static final String MIME_TYPE_IMAGE_JPG = "image/jpg"; public static final String MIME_TYPE_IMAGE_JPE = "image/jpe"; public static final String MIME_TYPE_IMAGE_APNG = "image/apng"; public static final String MIME_TYPE_IMAGE_AVIF = "image/avif"; public static final String MIME_TYPE_IMAGE_GIF = "image/gif"; public static final String MIME_TYPE_IMAGE_PNG = "image/png"; public static final String MIME_TYPE_IMAGE_PSD = "image/psd"; public static final String MIME_TYPE_IMAGE_BMP = "image/bmp"; public static final String MIME_TYPE_IMAGE_XBMP = "image/x-bmp"; public static final String MIME_TYPE_IMAGE_XMSBMP = "image/x-ms-bmp"; public static final String MIME_TYPE_IMAGE_TIFF = "image/tiff"; public static final String MIME_TYPE_IMAGE_TIF = "image/tif"; public static final String MIME_TYPE_IMAGE_SVG = "image/svg+xml"; public static final String MIME_TYPE_IMAGE_WEBP = "image/webp"; public static final String MIME_TYPE_IMAGE_HEIF = "image/heif"; public static final String MIME_TYPE_IMAGE_HEIC = "image/heic"; public static final String MIME_TYPE_IMAGE_HEIF_SEQUENCE = "image/heif-sequence"; public static final String MIME_TYPE_IMAGE_HEIC_SEQUENCE = "image/heic-sequence"; // Lottie public static final String MIME_TYPE_APP_JSON = "application/json"; // Audio mime types public static final String MIME_TYPE_AUDIO_WILDCARD = "audio/*"; public static final String MIME_TYPE_AUDIO_MPEG = "audio/mpeg"; public static final String MIME_TYPE_AUDIO_3GPP = "audio/3gpp"; public static final String MIME_TYPE_AUDIO_MP3 = "audio/mp3"; public static final String MIME_TYPE_AUDIO_OGG = "audio/ogg"; public static final String MIME_TYPE_AUDIO_FLAC = "audio/flac"; public static final String MIME_TYPE_AUDIO_AAC = "audio/aac"; public static final String MIME_TYPE_AUDIO_MP4 = "audio/mp4"; public static final String MIME_TYPE_AUDIO_WAVE = "audio/wave"; public static final String MIME_TYPE_AUDIO_WAV = "audio/wav"; public static final String MIME_TYPE_AUDIO_WEBM = "audio/webm"; public static final String MIME_TYPE_AUDIO_MATROSKA = "audio/x-matroska"; // Video mime types public static final String MIME_TYPE_VIDEO_WILDCARD = "video/*"; public static final String MIME_TYPE_VIDEO_MPEG = "video/mpeg"; public static final String MIME_TYPE_VIDEO_3GPP = "video/3gpp"; public static final String MIME_TYPE_VIDEO_OGG = "video/ogg"; public static final String MIME_TYPE_VIDEO_MP4 = "video/mp4"; public static final String MIME_TYPE_VIDEO_WEBM = "video/webm"; public static final String MIME_TYPE_VIDEO_MATROSKA = "video/x-matroska"; public static final String MIME_TYPE_VIDEO_QT = "video/quicktime"; public static final String MIME_TYPE_VIDEO_AVI = "video/x-msvideo"; // (Proprietary) document format mime types public static final String MIME_TYPE_APP_PDF = "application/pdf"; public static final String MIME_TYPE_MSPOWERPOINT = "application/mspowerpoint"; public static final String MIME_TYPE_MSPOWERPOINT2 = "application/vnd.ms-powerpoint"; public static final String MIME_TYPE_MSPOWERPOINT_MACRO = "application/vnd.ms-powerpoint.presentation.macroenabled.12"; public static final String MIME_TYPE_OOPOWERPOINT = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; public static final String MIME_TYPE_APPLE_KEYNOTE = "application/x-iwork-keynote-sffkey"; public static final String MIME_TYPE_MSWORD = "application/msword"; public static final String MIME_TYPE_OOWORD = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; public static final String MIME_TYPE_APPLE_PAGES = "application/x-iwork-pages-sffpages"; public static final String MIME_TYPE_MSEXCEL = "application/msexcel"; public static final String MIME_TYPE_VND_MSEXCEL = "application/vnd.ms-excel"; public static final String MIME_TYPE_OOEXCEL = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; public static final String MIME_TYPE_CSV = "text/csv"; public static final String MIME_TYPE_CSV2 = "text/comma-separated-values"; public static final String MIME_TYPE_APPLE_NUMBERS = "application/x-iwork-numbers-sffnumbers"; // Compression public static final String MIME_TYPE_ZIP = "application/zip"; public static final String MIME_TYPE_GZIP = "application/gzip"; public static final String MIME_TYPE_7ZIP = "application/x-7z-compressed"; public static final String MIME_TYPE_RAR = "application/x-rar-compressed"; // ginlo: AVC extensions public static final String MIME_TYPE_TEXT_V_CALL = "text/x-ginlo-call-invite"; public static final String MIME_TYPE_APP_GINLO_CONTROL = "application/x-ginlo-control-message"; // ginlo: Helper type for rich content public static final String MIME_TYPE_APP_GINLO_RICH_CONTENT = "application/x-ginlo-rich-content"; public static final String MIME_TYPE_APP_GINLO_LOTTIE = "application/x-ginlo-lottie"; // Others public static final String MIME_TYPE_TEXT_PLAIN = "text/plain"; public static final String MIME_TYPE_TEXT_RSS = "text/rss"; public static final String MIME_TYPE_TEXT_V_CARD = "text/x-vcard"; public static final String MIME_TYPE_MODEL_LOCATION = "model/location"; // To be compatible to apps with typos public static final String MIME_TYPE_APP_OCTET_STREAM = "application/octetstream"; public static final String MIME_TYPE_APP_OCTETSTREAM = "application/octet-stream"; public static final int MIMETYPE_NOT_FOUND = -1; // Schemas public static final String CONTENT = "content"; public static final String FILE = "file"; private final Context context; private static final ArrayList<String> imageMimeTypes = new ArrayList<>(); private static final ArrayList<String> videoMimeTypes = new ArrayList<>(); private static final ArrayList<String> audioMimeTypes = new ArrayList<>(); private static final ArrayList<String> richContentMimeTypes = new ArrayList<>(); public MimeUtil(Context context) { this.context = context; } /** * Build and/or return a list of compatible image mimetypes * @return */ public static ArrayList<String> getImageMimeTypes() { if(imageMimeTypes.isEmpty()) { imageMimeTypes.add(MIME_TYPE_IMAGE_JPEG); imageMimeTypes.add(MIME_TYPE_IMAGE_JPG); imageMimeTypes.add(MIME_TYPE_IMAGE_JPE); imageMimeTypes.add(MIME_TYPE_IMAGE_APNG); imageMimeTypes.add(MIME_TYPE_IMAGE_AVIF); imageMimeTypes.add(MIME_TYPE_IMAGE_GIF); imageMimeTypes.add(MIME_TYPE_IMAGE_PNG); //imageMimeTypes.add(MIME_TYPE_IMAGE_PSD); imageMimeTypes.add(MIME_TYPE_IMAGE_BMP); imageMimeTypes.add(MIME_TYPE_IMAGE_XBMP); imageMimeTypes.add(MIME_TYPE_IMAGE_XMSBMP); imageMimeTypes.add(MIME_TYPE_IMAGE_TIFF); imageMimeTypes.add(MIME_TYPE_IMAGE_TIF); imageMimeTypes.add(MIME_TYPE_IMAGE_SVG); imageMimeTypes.add(MIME_TYPE_IMAGE_WEBP); imageMimeTypes.add(MIME_TYPE_IMAGE_HEIF); imageMimeTypes.add(MIME_TYPE_IMAGE_HEIC); imageMimeTypes.add(MIME_TYPE_IMAGE_HEIF_SEQUENCE); imageMimeTypes.add(MIME_TYPE_IMAGE_HEIC_SEQUENCE); } return imageMimeTypes; } /** * Build and/or return a list of compatible audio mimetypes * @return */ public static ArrayList<String> getAudioMimeTypes() { if (audioMimeTypes.isEmpty()) { audioMimeTypes.add(MIME_TYPE_AUDIO_MPEG); audioMimeTypes.add(MIME_TYPE_AUDIO_3GPP); audioMimeTypes.add(MIME_TYPE_AUDIO_MP3); audioMimeTypes.add(MIME_TYPE_AUDIO_OGG); audioMimeTypes.add(MIME_TYPE_AUDIO_FLAC); audioMimeTypes.add(MIME_TYPE_AUDIO_AAC); audioMimeTypes.add(MIME_TYPE_AUDIO_MP4); audioMimeTypes.add(MIME_TYPE_AUDIO_MATROSKA); audioMimeTypes.add(MIME_TYPE_AUDIO_WAVE); audioMimeTypes.add(MIME_TYPE_AUDIO_WAV); audioMimeTypes.add(MIME_TYPE_AUDIO_WEBM); } return audioMimeTypes; } /** * Build and/or return a list of compatible video mimetypes * @return */ public static ArrayList<String> getVideoMimeTypes() { if(videoMimeTypes.isEmpty()) { videoMimeTypes.add(MIME_TYPE_VIDEO_MPEG); videoMimeTypes.add(MIME_TYPE_VIDEO_3GPP); videoMimeTypes.add(MIME_TYPE_VIDEO_OGG); videoMimeTypes.add(MIME_TYPE_VIDEO_MP4); videoMimeTypes.add(MIME_TYPE_VIDEO_MATROSKA); videoMimeTypes.add(MIME_TYPE_VIDEO_WEBM); videoMimeTypes.add(MIME_TYPE_VIDEO_QT); videoMimeTypes.add(MIME_TYPE_VIDEO_AVI); } return videoMimeTypes; } /** * Build and/or return a list of compatible rich content (gifs, stickers etc.) mimetypes * @return */ public static ArrayList<String> getRichContentMimeTypes() { if(richContentMimeTypes.isEmpty()) { richContentMimeTypes.add(MIME_TYPE_APP_GINLO_RICH_CONTENT); // proprietary internal type richContentMimeTypes.add(MIME_TYPE_APP_GINLO_LOTTIE); // proprietary internal type richContentMimeTypes.add(MIME_TYPE_APP_JSON); // Used for lottie animations richContentMimeTypes.add(MIME_TYPE_IMAGE_GIF); richContentMimeTypes.add(MIME_TYPE_IMAGE_WEBP); richContentMimeTypes.add(MIME_TYPE_IMAGE_PNG); } return richContentMimeTypes; } /** * Check Uri for known image mimetype * @param context * @param contentUri * @return */ public static boolean checkImageUriMimetype(Context context, Uri contentUri) { return isKnownUriMimeType(context, contentUri, getImageMimeTypes()); } /** * Check Uri for known audio mimetype * @param context * @param contentUri * @return */ public static boolean checkAudioUriMimetype(Context context, Uri contentUri) { return isKnownUriMimeType(context, contentUri, getAudioMimeTypes()); } /** * Check Uri for known video mimetype * @param context * @param contentUri * @return */ public static boolean checkVideoUriMimetype(Context context, Uri contentUri) { return isKnownUriMimeType(context, contentUri, getVideoMimeTypes()); } /** * Check Uri for known rich content mimetypes * @param context * @param contentUri * @return */ public static boolean checkRichContentUriMimetype(Context context, Uri contentUri) { return isKnownUriMimeType(context, contentUri, getRichContentMimeTypes()); } /** * Check Uri for requested mimetype * @param context * @param contentUri * @return */ public static boolean isKnownUriMimeType(Context context, Uri contentUri, ArrayList<String> knownMimeTypes) { if (context == null || contentUri == null) { return false; } LogUtil.d(TAG, "isKnownUriMimeType: Check " + contentUri.getPath() + " against: " + knownMimeTypes); String mimeType = getMimeTypeForUri(context, contentUri); return StringUtil.isInList(mimeType, knownMimeTypes, true); } /** * Is given mimetype for Glide processing? * @param mimeType * @return */ public static boolean isGlideMimetype(String mimeType) { if(StringUtil.isNullOrEmpty(mimeType)) { return false; } return (mimeType.equals(MIME_TYPE_IMAGE_GIF) || mimeType.equals(MIME_TYPE_IMAGE_TIF) || mimeType.equals(MIME_TYPE_IMAGE_TIFF) || mimeType.equals(MIME_TYPE_IMAGE_WEBP) || mimeType.equals(MIME_TYPE_IMAGE_JPEG) || mimeType.equals(MIME_TYPE_IMAGE_JPG) || mimeType.equals(MIME_TYPE_IMAGE_JPE) || mimeType.equals(MIME_TYPE_IMAGE_SVG) || mimeType.equals(MIME_TYPE_IMAGE_BMP) || mimeType.equals(MIME_TYPE_IMAGE_XBMP) || mimeType.equals(MIME_TYPE_IMAGE_XMSBMP) || mimeType.equals(MIME_TYPE_IMAGE_PNG) ); } /** * Must analyze. Lottie files are mostly json files - check "magic bytes" * @param fileToCheck * @return */ public static boolean isLottieFile(String mimeType, File fileToCheck) { boolean returnValue = false; if(mimeType != null && mimeType.equals(MIME_TYPE_APP_GINLO_LOTTIE)) { // Has already been analyzed. Trust that. returnValue = true; } else if (mimeType == null || mimeType.equals(MIME_TYPE_APP_JSON)) { if (fileToCheck != null) { if (fileToCheck.getName().endsWith(".tgs")) { LogUtil.d(TAG, "isLottieFile: Got first hint with file extension .tgs"); // This is possible, but we should dig deeper. //returnValue = true; } LogUtil.d(TAG, "isLottieFile: Analyze " + fileToCheck + " ..."); byte[] magic = "{\"tgs\"".getBytes(StandardCharsets.UTF_8); if (FileUtil.haveFileMagic(fileToCheck, magic)) { LogUtil.d(TAG, "isLottieFile: Yes. Identified by magic " + Arrays.toString(magic)); returnValue = true; } else { magic = "{\"v\"".getBytes(StandardCharsets.UTF_8); if (FileUtil.haveFileMagic(fileToCheck, magic)) { LogUtil.d(TAG, "isLottieFile: Yes. Identified by magic " + Arrays.toString(magic)); returnValue = true; } } } } return returnValue; } /** * Is given mimetype a compatible audio mimetype? * @param mimeType * @return */ public static boolean isAudioMimetype(String mimeType, boolean withWildcard) { boolean haveAudioMimetype = false; if(!StringUtil.isNullOrEmpty(mimeType)) { if(withWildcard && MIME_TYPE_AUDIO_WILDCARD.contains(mimeType)) { haveAudioMimetype = true; } else { haveAudioMimetype = getAudioMimeTypes().contains(mimeType); } } return haveAudioMimetype; } /** * Is given mimetype a compatible image mimetype? * @param mimeType * @return */ public static boolean isImageMimetype(String mimeType, boolean withWildcard) { boolean haveImageMimetype = false; if(!StringUtil.isNullOrEmpty(mimeType)) { if(withWildcard && MIME_TYPE_IMAGE_WILDCARD.contains(mimeType)) { haveImageMimetype = true; } else { haveImageMimetype = getImageMimeTypes().contains(mimeType); } } return haveImageMimetype; } /** * Is given mimetype a compatible video mimetype? * @param mimeType * @return */ public static boolean isVideoMimetype(String mimeType, boolean withWildcard) { boolean haveVideoMimetype = false; if(!StringUtil.isNullOrEmpty(mimeType)) { if(withWildcard && MIME_TYPE_VIDEO_WILDCARD.contains(mimeType)) { haveVideoMimetype = true; } else { haveVideoMimetype = getVideoMimeTypes().contains(mimeType); } } return haveVideoMimetype; } /** * Is given mimetype a compatible rich content mimetype? * These are all we have our internal Glide/RLottie components for. * @param mimeType * @return */ public static boolean isRichContentMimetype(String mimeType) { if(StringUtil.isNullOrEmpty(mimeType)) { return false; } return getRichContentMimeTypes().contains(mimeType); } public static String getMimeTypeForUri(Context context, Uri contentUri) { String type = null; if (contentUri != null) { // First try this ContentResolver cR = context.getContentResolver(); type = cR.getType(contentUri); LogUtil.d(TAG, "getMimeTypeForUri: ContentResolver brought: " + type); if(MimeUtil.hasEmptyOrUnspecificMimeType(type)) { final String keepResult = type; // So we should try that type = getMimeTypeFromFilename(contentUri.getPath()); LogUtil.d(TAG, "getMimeTypeForUri: Pathname brought: " + type); // Step back if the latest result isn't even better ... if(type == null && keepResult != null) { type = keepResult; } } } return type; } public static String getExtensionForUri(Context context, final Uri uri) { String extension = null; String mimetype = getMimeTypeForUri(context, uri); if (!StringUtil.isNullOrEmpty(mimetype)) { MimeTypeMap mime = MimeTypeMap.getSingleton(); extension = mime.getExtensionFromMimeType(mimetype); } return extension; } public static int getIconForMimeType(String mimeType) { int resID = MIMETYPE_NOT_FOUND; switch (mimeType) { case MIME_TYPE_APP_PDF: resID = R.drawable.data_pdf; break; case MIME_TYPE_MSPOWERPOINT: case MIME_TYPE_MSPOWERPOINT2: case MIME_TYPE_MSPOWERPOINT_MACRO: case MIME_TYPE_OOPOWERPOINT: case MIME_TYPE_APPLE_KEYNOTE: resID = R.drawable.data_praesent; break; case MIME_TYPE_MSWORD: case MIME_TYPE_OOWORD: case MIME_TYPE_APPLE_PAGES: resID = R.drawable.data_doc; break; case MIME_TYPE_MSEXCEL: case MIME_TYPE_VND_MSEXCEL: case MIME_TYPE_OOEXCEL: case MIME_TYPE_CSV: case MIME_TYPE_CSV2: case MIME_TYPE_APPLE_NUMBERS: resID = R.drawable.data_xls; break; case MIME_TYPE_ZIP: case MIME_TYPE_GZIP: case MIME_TYPE_7ZIP: case MIME_TYPE_RAR: resID = R.drawable.data_zip; break; default: if (isImageMimetype(mimeType, false)) { resID = R.drawable.media_photo; } else if (isVideoMimetype(mimeType, false)) { resID = R.drawable.media_movie; } else if (isAudioMimetype(mimeType, false)) { resID = R.drawable.media_audio; } } return resID; } public static Boolean hasUnspecificBinaryMimeType(String mimeType) { return MimeUtil.MIME_TYPE_APP_OCTETSTREAM.equals(mimeType) || MimeUtil.MIME_TYPE_APP_OCTET_STREAM.equals(mimeType); } public static Boolean hasEmptyOrUnspecificMimeType(String mimeType) { return StringUtil.isNullOrEmpty(mimeType) || MimeUtil.MIME_TYPE_APP_GINLO_RICH_CONTENT.equals(mimeType) || MimeUtil.MIME_TYPE_TEXT_PLAIN.equals(mimeType) || hasUnspecificBinaryMimeType(mimeType); } public static String grabMimeType(String filename, DecryptedMessage decryptedMsg, String defaultMimeType) { // Use all we have to get a mime type. String mimeType = decryptedMsg.getContentType(); String tmpMimeType = null; LogUtil.d(TAG, "grabMimeType: Check mimetype in ContentType: " + mimeType); if(hasEmptyOrUnspecificMimeType(mimeType)) { tmpMimeType = mimeType; mimeType = decryptedMsg.getFileMimetype(); LogUtil.d(TAG, "grabMimeType: Check mimetype in FileMimetype: " + mimeType); if (hasEmptyOrUnspecificMimeType(mimeType)) { // Only alibi? Dig deeper, but keep what we have if (tmpMimeType == null) { tmpMimeType = mimeType; } mimeType = MimeUtil.getMimeTypeFromFilename(filename); LogUtil.d(TAG, "grabMimeType: Check mimetype in file pathname: " + mimeType); if (StringUtil.isNullOrEmpty(mimeType)) { // Ok, use what we have mimeType = tmpMimeType != null ? tmpMimeType : defaultMimeType; LogUtil.d(TAG, "grabMimeType: No more options - finally we have: " + mimeType); } } } LogUtil.d(TAG, "grabMimeType: Using " + mimeType); return mimeType; } public static String getMimeTypeFromFilename(String filename) { if (filename == null) { return null; } String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(filename.replace(" ", "")); if (StringUtil.isNullOrEmpty(extension)) { int dotIndex = filename.lastIndexOf('.'); if (dotIndex > -1) { extension = filename.substring(dotIndex + 1); } } if (extension != null) { // apple typen<SUF> // .key wird als pgp-datei erkannt... switch (extension.toLowerCase(Locale.US)) { case "keynote": case "key": return MIME_TYPE_APPLE_KEYNOTE; case "numbers": return MIME_TYPE_APPLE_NUMBERS; case "pages": return MIME_TYPE_APPLE_PAGES; case "odt": return MIME_TYPE_OOWORD; case "ods": return MIME_TYPE_OOEXCEL; case "odp": return MIME_TYPE_OOPOWERPOINT; case "json": case "tgs": // Stickers / lottie animations come as json-files return MimeUtil.MIME_TYPE_APP_JSON; case "heic": return MimeUtil.MIME_TYPE_IMAGE_HEIC; case "heif": return MimeUtil.MIME_TYPE_IMAGE_HEIF; default: break; } MimeTypeMap mime = MimeTypeMap.getSingleton(); type = mime.getMimeTypeFromExtension(extension.toLowerCase(Locale.US)); } return type; } }
200902_44
package rita; import java.util.Arrays; public class PlingStemmer { /* Words that are both singular and plural */ private static final String[] categorySP = { "acoustics", "aesthetics", "aquatics", "basics", "ceramics", "classics", "cosmetics", "dialectics", "deer", "dynamics", "ethics", "harmonics", "heroics", "mechanics", "metrics", "optics", "people", "physics", "polemics", "pyrotechnics", "quadratics", "quarters", "statistics", "tactics", "tropics" }; /* Words that end in "-se" in their plural forms (like "nurse" etc.) */ private static final String[] categorySE_SES = { "abuses", "apocalypses", "blouses", "bruises", "chaises", "cheeses", "chemises", "clauses", "corpses", "courses", "crazes", "creases", "cruises", "curses", "databases", "dazes", "defenses", "demises", "discourses", "diseases", "doses", "eclipses", "enterprises", "expenses", "friezes", "fuses", "glimpses", "guises", "hearses", "horses", "houses", "impasses", "impulses", "kamikazes", "mazes", "mousses", "noises", "nooses", "noses", "nurses", "obverses", "offenses", "oozes", "overdoses", "phrases", "posses", "premises", "pretenses", "proteases", "pulses", "purposes", "purses", "racehorses", "recluses", "recourses", "relapses", "responses", "roses", "ruses", "spouses", "stripteases", "subleases", "sunrises", "tortoises", "trapezes", "treatises", "toes", "universes", "uses", "vases", "verses", "vises", "wheelbases", "wheezes" }; /* Words that do not have a distinct plural form (like "atlas" etc.) */ private static final String[] category00 = { "alias", "asbestos", "atlas", "barracks", "bathos", "bias", "breeches", "britches", "canvas", "chaos", "clippers", "contretemps", "corps", "cosmos", "crossroads", "diabetes", "ethos", "gallows", "gas", "graffiti", "headquarters", "herpes", "high-jinks", "innings", "jackanapes", "lens", "means", "measles", "mews", "mumps", "news", "pathos", "pincers", "pliers", "proceedings", "rabies", "rhinoceros", "sassafras", "scissors", "series", "shears", "species", "tuna" }; /* Words that change from "-um" to "-a" (like "curriculum" etc.), listed in their plural forms */ private static final String[] categoryUM_A = { "addenda", "agenda", "aquaria", "bacteria", "candelabra", "compendia", "consortia", "crania", "curricula", "data", "desiderata", "dicta", "emporia", "enconia", "errata", "extrema", "gymnasia", "honoraria", "interregna", "lustra", "maxima", "media", "memoranda", "millenia", "minima", "momenta", "memorabilia", "millennia", "optima", "ova", "phyla", "quanta", "rostra", "spectra", "specula", "septa", "stadia", "strata", "symposia", "trapezia", "ultimata", "vacua", "vela" }; /* Words that change from "-on" to "-a" (like "phenomenon" etc.), listed in their plural forms */ private static final String[] categoryON_A = { "aphelia", "asyndeta", "automata", "criteria", "hyperbata", "noumena", "organa", "perihelia", "phenomena", "prolegomena", "referenda" }; /* Words that change from "-o" to "-i" (like "libretto" etc.), listed in their plural forms */ private static final String[] categoryO_I = { "alti", "bassi", "canti", "concerti", "contralti", "crescendi", "libretti", "soli", "soprani", "tempi", "virtuosi" }; /* Words that change from "-us" to "-i" (like "fungus" etc.), listed in their plural forms */ private static final String[] categoryUS_I = { "alumni", "bacilli", "cacti", "foci", "fungi", "genii", "hippopotami", "incubi", "nimbi", "nuclei", "nucleoli", "octopi", "radii", "stimuli", "styli", "succubi", "syllabi", "termini", "tori", "umbilici", "uteri" }; /* Words that change from "-ix" to "-ices" (like "appendix" etc.), listed in their plural forms */ private static final String[] categoryIX_ICES = { "appendices", "cervices", "indices", "matrices" }; /* Words that change from "-is" to "-es" (like "axis" etc.), listed in their plural forms, plus everybody ending in theses */ private static final String[] categoryIS_ES = { "analyses", "axes", "bases", "catharses", "crises", "diagnoses", "ellipses", "emphases", "neuroses", "oases", "paralyses", "prognoses", "synopses" }; /* Words that change from "-oe" to "-oes" (like "toe" etc.), listed in their plural forms*/ private static final String[] categoryOE_OES = { "aloes", "backhoes", "beroes", "canoes", "chigoes", "cohoes", "does", "felloes", "floes", "foes", "gumshoes", "hammertoes", "hoes", "hoopoes", "horseshoes", "leucothoes", "mahoes", "mistletoes", "oboes", "overshoes", "pahoehoes", "pekoes", "roes", "shoes", "sloes", "snowshoes", "throes", "tic-tac-toes", "tick-tack-toes", "ticktacktoes", "tiptoes", "tit-tat-toes", "toes", "toetoes", "tuckahoes", "woes" }; /* Words that change from "-ex" to "-ices" (like "index" etc.), listed in their plural forms*/ private static final String[] categoryEX_ICES = { "apices", "codices", "cortices", "indices", "latices", "murices", "pontifices", "silices", "simplices", "vertices", "vortices" }; /* Words that change from "-u" to "-us" (like "emu" etc.), listed in their plural forms*/ private static final String[] categoryU_US = { "menus", "gurus", "apercus", "barbus", "cornus", "ecrus", "emus", "fondus", "gnus", "iglus", "mus", "nandus", "napus", "poilus", "quipus", "snafus", "tabus", "tamandus", "tatus", "timucus", "tiramisus", "tofus", "tutus" }; /* Words that change from "-sse" to "-sses" (like "finesse" etc.), listed in their plural forms,plus those ending in mousse*/ private static final String[] categorySSE_SSES = { "bouillabaisses", "coulisses", "crevasses", "crosses", "cuisses", "demitasses", "ecrevisses", "fesses", "finesses", "fosses", "impasses", "lacrosses", "largesses", "masses", "noblesses", "palliasses", "pelisses", "politesses", "posses", "tasses", "wrasses" }; /* Words that change from "-che" to "-ches" (like "brioche" etc.), listed in their plural forms*/ private static final String[] categoryCHE_CHES = { "adrenarches", "attaches", "avalanches", "barouches", "brioches", "caches", "caleches", "caroches", "cartouches", "cliches", "cloches", "creches", "demarches", "douches", "gouaches", "guilloches", "headaches", "heartaches", "huaraches", "menarches", "microfiches", "moustaches", "mustaches", "niches", "panaches", "panoches", "pastiches", "penuches", "pinches", "postiches", "psyches", "quiches", "schottisches", "seiches", "soutaches", "synecdoches", "thelarches", "troches" }; /* Words that end with "-ics" and do not exist as nouns without the "s" (like "aerobics" etc.)*/ private static final String[] categoryICS = { "aerobatics", "aerobics", "aerodynamics", "aeromechanics", "aeronautics", "alphanumerics", "animatronics", "apologetics", "architectonics", "astrodynamics", "astronautics", "astrophysics", "athletics", "atmospherics", "autogenics", "avionics", "ballistics", "bibliotics", "bioethics", "biometrics", "bionics", "bionomics", "biophysics", "biosystematics", "cacogenics", "calisthenics", "callisthenics", "catoptrics", "civics", "cladistics", "cryogenics", "cryonics", "cryptanalytics", "cybernetics", "cytoarchitectonics", "cytogenetics", "diagnostics", "dietetics", "dramatics", "dysgenics", "econometrics", "economics", "electromagnetics", "electronics", "electrostatics", "endodontics", "enterics", "ergonomics", "eugenics", "eurhythmics", "eurythmics", "exodontics", "fibreoptics", "futuristics", "genetics", "genomics", "geographics", "geophysics", "geopolitics", "geriatrics", "glyptics", "graphics", "gymnastics", "hermeneutics", "histrionics", "homiletics", "hydraulics", "hydrodynamics", "hydrokinetics", "hydroponics", "hydrostatics", "hygienics", "informatics", "kinematics", "kinesthetics", "kinetics", "lexicostatistics", "linguistics", "lithoglyptics", "liturgics", "logistics", "macrobiotics", "macroeconomics", "magnetics", "magnetohydrodynamics", "mathematics", "metamathematics", "metaphysics", "microeconomics", "microelectronics", "mnemonics", "morphophonemics", "neuroethics", "neurolinguistics", "nucleonics", "numismatics", "obstetrics", "onomastics", "orthodontics", "orthopaedics", "orthopedics", "orthoptics", "paediatrics", "patristics", "patristics", "pedagogics", "pediatrics", "periodontics", "pharmaceutics", "pharmacogenetics", "pharmacokinetics", "phonemics", "phonetics", "phonics", "photomechanics", "physiatrics", "pneumatics", "poetics", "politics", "pragmatics", "prosthetics", "prosthodontics", "proteomics", "proxemics", "psycholinguistics", "psychometrics", "psychonomics", "psychophysics", "psychotherapeutics", "robotics", "semantics", "semiotics", "semitropics", "sociolinguistics", "stemmatics", "strategics", "subtropics", "systematics", "tectonics", "telerobotics", "therapeutics", "thermionics", "thermodynamics", "thermostatics" }; /* Words that change from "-ie" to "-ies" (like "auntie" etc.), listed in their plural forms*/ private static final String[] categoryIE_IES = { "aeries", "anomies", "aunties", "baddies", "beanies", "birdies", "bogies", "bonhomies", "boogies", "bookies", "booties", "bourgeoisies", "brasseries", "brassies", "brownies", "caddies", "calories", "camaraderies", "charcuteries", "collies", "commies", "cookies", "coolies", "coonties", "cooties", "coteries", "cowpies", "cowries", "cozies", "crappies", "crossties", "curies", "darkies", "dearies", "dickies", "dies", "dixies", "doggies", "dogies", "eyries", "faeries", "falsies", "floozies", "folies", "foodies", "freebies", "gendarmeries", "genies", "gillies", "goalies", "goonies", "grannies", "groupies", "hippies", "hoagies", "honkies", "indies", "junkies", "kelpies", "kilocalories", "laddies", "lassies", "lies", "lingeries", "magpies", "magpies", "mashies", "mealies", "meanies", "menageries", "mollies", "moxies", "neckties", "newbies", "nighties", "nookies", "oldies", "panties", "patisseries", "pies", "pinkies", "pixies", "porkpies", "potpies", "prairies", "preemies", "pyxies", "quickies", "reveries", "rookies", "rotisseries", "scrapies", "sharpies", "smoothies", "softies", "stoolies", "stymies", "swaggies", "sweeties", "talkies", "techies", "ties", "tooshies", "toughies", "townies", "veggies", "walkie-talkies", "wedgies", "weenies", "yuppies", "zombies" }; /* Maps irregular Germanic English plural nouns to their singular form */ private static final String[] categoryIRR = { "blondes", "blonde", "teeth", "tooth", "beefs", "beef", "brethren", "brother", "busses", "bus", "cattle", "cow", "children", "child", "corpora", "corpus", "femora", "femur", "genera", "genus", "genies", "genie", "genii", "genie", "lice", "louse", "mice", "mouse", "mongooses", "mongoose", "monies", "money", "octopodes", "octopus", "oxen", "ox", "people", "person", "schemata", "schema", "soliloquies", "soliloquy", "taxis", "taxi", "throes", "throes", "trilbys", "trilby", "innings", "inning", "alibis", "alibi", "skis", "ski", "safaris", "safari", "rabbis", "rabbi" }; private static String cut(String s, String suffix) { // Cuts a suffix from a string (that is the number of chars given by the return (s.substring(0, s.length() - suffix.length())); } private static Boolean greek(String s) { // Cuts a suffix from a string (that is the number of chars given by the return (s.indexOf("ph") > 0 || s.indexOf('y') > 0 && s.endsWith("nges")); } /* Returns true if a word is probably not Latin */ private static Boolean noLatin(String s) { return (s.indexOf('h') > 0 || s.indexOf('j') > 0 || s.indexOf('k') > 0 || s.indexOf('w') > 0 || s.indexOf('y') > 0 || s.indexOf('z') > 0 || s.indexOf("ou") > 0 || s.indexOf("sh") > 0 || s.indexOf("ch") > 0 || s.endsWith("aus")); } public static String stem(String s) { // Handle irregular ones if (Arrays.asList(categoryIRR).contains(s)) { int index = Arrays.asList(categoryIRR).indexOf(s); if (index % 2 == 0) { String irreg = categoryIRR[index + 1]; return (irreg); } } // -on to -a if (Arrays.asList(categoryON_A).contains(s)) return (cut(s, "a") + "on"); // -um to -a if (Arrays.asList(categoryUM_A).contains(s)) return (cut(s, "a") + "um"); // -x to -ices if (Arrays.asList(categoryIX_ICES).contains(s)) return (cut(s, "ices") + "ix"); // -o to -i if (Arrays.asList(categoryO_I).contains(s)) return (cut(s, "i") + "o"); // -se to ses if (Arrays.asList(categorySE_SES).contains(s)) return (cut(s, "s")); // -is to -es if (Arrays.asList(categoryIS_ES).contains(s) || s.endsWith("theses")) return (cut(s, "es") + "is"); // -us to -i if (Arrays.asList(categoryUS_I).contains(s)) return (cut(s, "i") + "us"); //Wrong plural if (s.endsWith("uses") && Arrays.asList(categoryUS_I).contains(cut(s, "uses") + "i") || s.equals("genuses") || s.equals("corpuses")) return (cut(s, "es")); // -ex to -ices if (Arrays.asList(categoryEX_ICES).contains(s)) return (cut(s, "ices") + "ex"); // Words that do not inflect in the plural if (s.endsWith("ois") || s.endsWith("itis") || Arrays.asList(category00).contains(s) || Arrays.asList(categoryICS).contains(s)) return (s); // -en to -ina // No other common words end in -ina if (s.endsWith("ina")) return (cut(s, "en")); // -a to -ae // No other common words end in -ae if (s.endsWith("ae")) // special case return (cut(s, "e")); // -a to -ata // No other common words end in -ata if (s.endsWith("ata")) return (cut(s, "ta")); // trix to -trices // No common word ends with -trice(s) if (s.endsWith("trices")) return (cut(s, "trices") + "trix"); // -us to -us //No other common word ends in -us, except for false plurals of French words //Catch words that are not latin or known to end in -u if (s.endsWith("us") && !s.endsWith("eaus") && !s.endsWith("ieus") && !noLatin(s) && !Arrays.asList(categoryU_US).contains(s)) return (s); // -tooth to -teeth // -goose to -geese // -foot to -feet // -zoon to -zoa //No other common words end with the indicated suffixes if (s.endsWith("teeth")) return (cut(s, "teeth") + "tooth"); if (s.endsWith("geese")) return (cut(s, "geese") + "goose"); if (s.endsWith("feet")) return (cut(s, "feet") + "foot"); if (s.endsWith("zoa")) return (cut(s, "zoa") + "zoon"); // -men to -man // -firemen to -fireman if (s.endsWith("men")) return (cut(s, "men") + "man"); // -martinis to -martini // -bikinis to -bikini if (s.endsWith("inis")) return (cut(s, "inis") + "ini"); // -children to -child // -schoolchildren to -schoolchild if (s.endsWith("children")) return (cut(s, "ren")); // -eau to -eaux //No other common words end in eaux if (s.endsWith("eaux")) return (cut(s, "x")); // -ieu to -ieux //No other common words end in ieux if (s.endsWith("ieux")) return (cut(s, "x")); // -nx to -nges // Pay attention not to kill words ending in -nge with plural -nges // Take only Greek words (works fine, only a handfull of exceptions) if (s.endsWith("nges") && greek(s)) return (cut(s, "nges") + "nx"); // -[sc]h to -[sc]hes //No other common word ends with "shes", "ches" or "she(s)" //Quite a lot end with "che(s)", filter them out if (s.endsWith("shes") || s.endsWith("ches") && !Arrays.asList(categoryCHE_CHES).contains(s)) return (cut(s, "es")); // -ss to -sses // No other common singular word ends with "sses" // Filter out those ending in "sse(s)" if (s.endsWith("sses") && !Arrays.asList(categorySSE_SSES).contains(s) && !s.endsWith("mousses")) return (cut(s, "es")); // -x to -xes // No other common word ends with "xe(s)" except for "axe" if (s.endsWith("xes") && !s.equals("axes")) return (cut(s, "es")); // -[nlw]ife to -[nlw]ives //No other common word ends with "[nlw]ive(s)" except for olive if (s.endsWith("nives") || s.endsWith("lives") && !s.endsWith("olives") || s.endsWith("wives")) return (cut(s, "ves") + "fe"); // -[aeo]lf to -ves exceptions: valve, solve // -[^d]eaf to -ves exceptions: heave, weave // -arf to -ves no exception if (s.endsWith("alves") && !s.endsWith("valves") || s.endsWith("olves") && !s.endsWith("solves") || s.endsWith("eaves") && !s.endsWith("heaves") && !s.endsWith("weaves") || s.endsWith("arves") || s.endsWith("shelves") || s.endsWith("selves")) return (cut(s, "ves") + "f"); // -y to -ies // -ies is very uncommon as a singular suffix // but -ie is quite common, filter them out if (s.endsWith("ies") && !Arrays.asList(categoryIE_IES).contains(s)) return (cut(s, "ies") + "y"); // -o to -oes // Some words end with -oe, so don't kill the "e" if (s.endsWith("oes") && !Arrays.asList(categoryOE_OES).contains(s)) return (cut(s, "es")); // -s to -ses // -z to -zes // no words end with "-ses" or "-zes" in singular if (s.endsWith("ses") || s.endsWith("zes")) return (cut(s, "es")); // - to -s if (s.endsWith("s") && !s.endsWith("ss") && !s.endsWith("is")) return (cut(s, "s")); return (s); } public static boolean _checkPluralNoLex(String s) { boolean res = false; if (Arrays.asList(categoryUM_A).contains(s) || Arrays.asList(categoryON_A).contains(s) || Arrays.asList(categoryO_I).contains(s) || Arrays.asList(categoryUS_I).contains(s) || Arrays.asList(categoryIX_ICES).contains(s)) { res = true; } res = res || (Arrays.asList(categoryIRR).indexOf(s) % 2 == 0); //if (res) System.out.println("checkPlural: "+s+" "+res); return res; } }
dhowe/rita4j
src/main/java/rita/PlingStemmer.java
6,015
// -zoon to -zoa
line_comment
nl
package rita; import java.util.Arrays; public class PlingStemmer { /* Words that are both singular and plural */ private static final String[] categorySP = { "acoustics", "aesthetics", "aquatics", "basics", "ceramics", "classics", "cosmetics", "dialectics", "deer", "dynamics", "ethics", "harmonics", "heroics", "mechanics", "metrics", "optics", "people", "physics", "polemics", "pyrotechnics", "quadratics", "quarters", "statistics", "tactics", "tropics" }; /* Words that end in "-se" in their plural forms (like "nurse" etc.) */ private static final String[] categorySE_SES = { "abuses", "apocalypses", "blouses", "bruises", "chaises", "cheeses", "chemises", "clauses", "corpses", "courses", "crazes", "creases", "cruises", "curses", "databases", "dazes", "defenses", "demises", "discourses", "diseases", "doses", "eclipses", "enterprises", "expenses", "friezes", "fuses", "glimpses", "guises", "hearses", "horses", "houses", "impasses", "impulses", "kamikazes", "mazes", "mousses", "noises", "nooses", "noses", "nurses", "obverses", "offenses", "oozes", "overdoses", "phrases", "posses", "premises", "pretenses", "proteases", "pulses", "purposes", "purses", "racehorses", "recluses", "recourses", "relapses", "responses", "roses", "ruses", "spouses", "stripteases", "subleases", "sunrises", "tortoises", "trapezes", "treatises", "toes", "universes", "uses", "vases", "verses", "vises", "wheelbases", "wheezes" }; /* Words that do not have a distinct plural form (like "atlas" etc.) */ private static final String[] category00 = { "alias", "asbestos", "atlas", "barracks", "bathos", "bias", "breeches", "britches", "canvas", "chaos", "clippers", "contretemps", "corps", "cosmos", "crossroads", "diabetes", "ethos", "gallows", "gas", "graffiti", "headquarters", "herpes", "high-jinks", "innings", "jackanapes", "lens", "means", "measles", "mews", "mumps", "news", "pathos", "pincers", "pliers", "proceedings", "rabies", "rhinoceros", "sassafras", "scissors", "series", "shears", "species", "tuna" }; /* Words that change from "-um" to "-a" (like "curriculum" etc.), listed in their plural forms */ private static final String[] categoryUM_A = { "addenda", "agenda", "aquaria", "bacteria", "candelabra", "compendia", "consortia", "crania", "curricula", "data", "desiderata", "dicta", "emporia", "enconia", "errata", "extrema", "gymnasia", "honoraria", "interregna", "lustra", "maxima", "media", "memoranda", "millenia", "minima", "momenta", "memorabilia", "millennia", "optima", "ova", "phyla", "quanta", "rostra", "spectra", "specula", "septa", "stadia", "strata", "symposia", "trapezia", "ultimata", "vacua", "vela" }; /* Words that change from "-on" to "-a" (like "phenomenon" etc.), listed in their plural forms */ private static final String[] categoryON_A = { "aphelia", "asyndeta", "automata", "criteria", "hyperbata", "noumena", "organa", "perihelia", "phenomena", "prolegomena", "referenda" }; /* Words that change from "-o" to "-i" (like "libretto" etc.), listed in their plural forms */ private static final String[] categoryO_I = { "alti", "bassi", "canti", "concerti", "contralti", "crescendi", "libretti", "soli", "soprani", "tempi", "virtuosi" }; /* Words that change from "-us" to "-i" (like "fungus" etc.), listed in their plural forms */ private static final String[] categoryUS_I = { "alumni", "bacilli", "cacti", "foci", "fungi", "genii", "hippopotami", "incubi", "nimbi", "nuclei", "nucleoli", "octopi", "radii", "stimuli", "styli", "succubi", "syllabi", "termini", "tori", "umbilici", "uteri" }; /* Words that change from "-ix" to "-ices" (like "appendix" etc.), listed in their plural forms */ private static final String[] categoryIX_ICES = { "appendices", "cervices", "indices", "matrices" }; /* Words that change from "-is" to "-es" (like "axis" etc.), listed in their plural forms, plus everybody ending in theses */ private static final String[] categoryIS_ES = { "analyses", "axes", "bases", "catharses", "crises", "diagnoses", "ellipses", "emphases", "neuroses", "oases", "paralyses", "prognoses", "synopses" }; /* Words that change from "-oe" to "-oes" (like "toe" etc.), listed in their plural forms*/ private static final String[] categoryOE_OES = { "aloes", "backhoes", "beroes", "canoes", "chigoes", "cohoes", "does", "felloes", "floes", "foes", "gumshoes", "hammertoes", "hoes", "hoopoes", "horseshoes", "leucothoes", "mahoes", "mistletoes", "oboes", "overshoes", "pahoehoes", "pekoes", "roes", "shoes", "sloes", "snowshoes", "throes", "tic-tac-toes", "tick-tack-toes", "ticktacktoes", "tiptoes", "tit-tat-toes", "toes", "toetoes", "tuckahoes", "woes" }; /* Words that change from "-ex" to "-ices" (like "index" etc.), listed in their plural forms*/ private static final String[] categoryEX_ICES = { "apices", "codices", "cortices", "indices", "latices", "murices", "pontifices", "silices", "simplices", "vertices", "vortices" }; /* Words that change from "-u" to "-us" (like "emu" etc.), listed in their plural forms*/ private static final String[] categoryU_US = { "menus", "gurus", "apercus", "barbus", "cornus", "ecrus", "emus", "fondus", "gnus", "iglus", "mus", "nandus", "napus", "poilus", "quipus", "snafus", "tabus", "tamandus", "tatus", "timucus", "tiramisus", "tofus", "tutus" }; /* Words that change from "-sse" to "-sses" (like "finesse" etc.), listed in their plural forms,plus those ending in mousse*/ private static final String[] categorySSE_SSES = { "bouillabaisses", "coulisses", "crevasses", "crosses", "cuisses", "demitasses", "ecrevisses", "fesses", "finesses", "fosses", "impasses", "lacrosses", "largesses", "masses", "noblesses", "palliasses", "pelisses", "politesses", "posses", "tasses", "wrasses" }; /* Words that change from "-che" to "-ches" (like "brioche" etc.), listed in their plural forms*/ private static final String[] categoryCHE_CHES = { "adrenarches", "attaches", "avalanches", "barouches", "brioches", "caches", "caleches", "caroches", "cartouches", "cliches", "cloches", "creches", "demarches", "douches", "gouaches", "guilloches", "headaches", "heartaches", "huaraches", "menarches", "microfiches", "moustaches", "mustaches", "niches", "panaches", "panoches", "pastiches", "penuches", "pinches", "postiches", "psyches", "quiches", "schottisches", "seiches", "soutaches", "synecdoches", "thelarches", "troches" }; /* Words that end with "-ics" and do not exist as nouns without the "s" (like "aerobics" etc.)*/ private static final String[] categoryICS = { "aerobatics", "aerobics", "aerodynamics", "aeromechanics", "aeronautics", "alphanumerics", "animatronics", "apologetics", "architectonics", "astrodynamics", "astronautics", "astrophysics", "athletics", "atmospherics", "autogenics", "avionics", "ballistics", "bibliotics", "bioethics", "biometrics", "bionics", "bionomics", "biophysics", "biosystematics", "cacogenics", "calisthenics", "callisthenics", "catoptrics", "civics", "cladistics", "cryogenics", "cryonics", "cryptanalytics", "cybernetics", "cytoarchitectonics", "cytogenetics", "diagnostics", "dietetics", "dramatics", "dysgenics", "econometrics", "economics", "electromagnetics", "electronics", "electrostatics", "endodontics", "enterics", "ergonomics", "eugenics", "eurhythmics", "eurythmics", "exodontics", "fibreoptics", "futuristics", "genetics", "genomics", "geographics", "geophysics", "geopolitics", "geriatrics", "glyptics", "graphics", "gymnastics", "hermeneutics", "histrionics", "homiletics", "hydraulics", "hydrodynamics", "hydrokinetics", "hydroponics", "hydrostatics", "hygienics", "informatics", "kinematics", "kinesthetics", "kinetics", "lexicostatistics", "linguistics", "lithoglyptics", "liturgics", "logistics", "macrobiotics", "macroeconomics", "magnetics", "magnetohydrodynamics", "mathematics", "metamathematics", "metaphysics", "microeconomics", "microelectronics", "mnemonics", "morphophonemics", "neuroethics", "neurolinguistics", "nucleonics", "numismatics", "obstetrics", "onomastics", "orthodontics", "orthopaedics", "orthopedics", "orthoptics", "paediatrics", "patristics", "patristics", "pedagogics", "pediatrics", "periodontics", "pharmaceutics", "pharmacogenetics", "pharmacokinetics", "phonemics", "phonetics", "phonics", "photomechanics", "physiatrics", "pneumatics", "poetics", "politics", "pragmatics", "prosthetics", "prosthodontics", "proteomics", "proxemics", "psycholinguistics", "psychometrics", "psychonomics", "psychophysics", "psychotherapeutics", "robotics", "semantics", "semiotics", "semitropics", "sociolinguistics", "stemmatics", "strategics", "subtropics", "systematics", "tectonics", "telerobotics", "therapeutics", "thermionics", "thermodynamics", "thermostatics" }; /* Words that change from "-ie" to "-ies" (like "auntie" etc.), listed in their plural forms*/ private static final String[] categoryIE_IES = { "aeries", "anomies", "aunties", "baddies", "beanies", "birdies", "bogies", "bonhomies", "boogies", "bookies", "booties", "bourgeoisies", "brasseries", "brassies", "brownies", "caddies", "calories", "camaraderies", "charcuteries", "collies", "commies", "cookies", "coolies", "coonties", "cooties", "coteries", "cowpies", "cowries", "cozies", "crappies", "crossties", "curies", "darkies", "dearies", "dickies", "dies", "dixies", "doggies", "dogies", "eyries", "faeries", "falsies", "floozies", "folies", "foodies", "freebies", "gendarmeries", "genies", "gillies", "goalies", "goonies", "grannies", "groupies", "hippies", "hoagies", "honkies", "indies", "junkies", "kelpies", "kilocalories", "laddies", "lassies", "lies", "lingeries", "magpies", "magpies", "mashies", "mealies", "meanies", "menageries", "mollies", "moxies", "neckties", "newbies", "nighties", "nookies", "oldies", "panties", "patisseries", "pies", "pinkies", "pixies", "porkpies", "potpies", "prairies", "preemies", "pyxies", "quickies", "reveries", "rookies", "rotisseries", "scrapies", "sharpies", "smoothies", "softies", "stoolies", "stymies", "swaggies", "sweeties", "talkies", "techies", "ties", "tooshies", "toughies", "townies", "veggies", "walkie-talkies", "wedgies", "weenies", "yuppies", "zombies" }; /* Maps irregular Germanic English plural nouns to their singular form */ private static final String[] categoryIRR = { "blondes", "blonde", "teeth", "tooth", "beefs", "beef", "brethren", "brother", "busses", "bus", "cattle", "cow", "children", "child", "corpora", "corpus", "femora", "femur", "genera", "genus", "genies", "genie", "genii", "genie", "lice", "louse", "mice", "mouse", "mongooses", "mongoose", "monies", "money", "octopodes", "octopus", "oxen", "ox", "people", "person", "schemata", "schema", "soliloquies", "soliloquy", "taxis", "taxi", "throes", "throes", "trilbys", "trilby", "innings", "inning", "alibis", "alibi", "skis", "ski", "safaris", "safari", "rabbis", "rabbi" }; private static String cut(String s, String suffix) { // Cuts a suffix from a string (that is the number of chars given by the return (s.substring(0, s.length() - suffix.length())); } private static Boolean greek(String s) { // Cuts a suffix from a string (that is the number of chars given by the return (s.indexOf("ph") > 0 || s.indexOf('y') > 0 && s.endsWith("nges")); } /* Returns true if a word is probably not Latin */ private static Boolean noLatin(String s) { return (s.indexOf('h') > 0 || s.indexOf('j') > 0 || s.indexOf('k') > 0 || s.indexOf('w') > 0 || s.indexOf('y') > 0 || s.indexOf('z') > 0 || s.indexOf("ou") > 0 || s.indexOf("sh") > 0 || s.indexOf("ch") > 0 || s.endsWith("aus")); } public static String stem(String s) { // Handle irregular ones if (Arrays.asList(categoryIRR).contains(s)) { int index = Arrays.asList(categoryIRR).indexOf(s); if (index % 2 == 0) { String irreg = categoryIRR[index + 1]; return (irreg); } } // -on to -a if (Arrays.asList(categoryON_A).contains(s)) return (cut(s, "a") + "on"); // -um to -a if (Arrays.asList(categoryUM_A).contains(s)) return (cut(s, "a") + "um"); // -x to -ices if (Arrays.asList(categoryIX_ICES).contains(s)) return (cut(s, "ices") + "ix"); // -o to -i if (Arrays.asList(categoryO_I).contains(s)) return (cut(s, "i") + "o"); // -se to ses if (Arrays.asList(categorySE_SES).contains(s)) return (cut(s, "s")); // -is to -es if (Arrays.asList(categoryIS_ES).contains(s) || s.endsWith("theses")) return (cut(s, "es") + "is"); // -us to -i if (Arrays.asList(categoryUS_I).contains(s)) return (cut(s, "i") + "us"); //Wrong plural if (s.endsWith("uses") && Arrays.asList(categoryUS_I).contains(cut(s, "uses") + "i") || s.equals("genuses") || s.equals("corpuses")) return (cut(s, "es")); // -ex to -ices if (Arrays.asList(categoryEX_ICES).contains(s)) return (cut(s, "ices") + "ex"); // Words that do not inflect in the plural if (s.endsWith("ois") || s.endsWith("itis") || Arrays.asList(category00).contains(s) || Arrays.asList(categoryICS).contains(s)) return (s); // -en to -ina // No other common words end in -ina if (s.endsWith("ina")) return (cut(s, "en")); // -a to -ae // No other common words end in -ae if (s.endsWith("ae")) // special case return (cut(s, "e")); // -a to -ata // No other common words end in -ata if (s.endsWith("ata")) return (cut(s, "ta")); // trix to -trices // No common word ends with -trice(s) if (s.endsWith("trices")) return (cut(s, "trices") + "trix"); // -us to -us //No other common word ends in -us, except for false plurals of French words //Catch words that are not latin or known to end in -u if (s.endsWith("us") && !s.endsWith("eaus") && !s.endsWith("ieus") && !noLatin(s) && !Arrays.asList(categoryU_US).contains(s)) return (s); // -tooth to -teeth // -goose to -geese // -foot to -feet // -zoon to<SUF> //No other common words end with the indicated suffixes if (s.endsWith("teeth")) return (cut(s, "teeth") + "tooth"); if (s.endsWith("geese")) return (cut(s, "geese") + "goose"); if (s.endsWith("feet")) return (cut(s, "feet") + "foot"); if (s.endsWith("zoa")) return (cut(s, "zoa") + "zoon"); // -men to -man // -firemen to -fireman if (s.endsWith("men")) return (cut(s, "men") + "man"); // -martinis to -martini // -bikinis to -bikini if (s.endsWith("inis")) return (cut(s, "inis") + "ini"); // -children to -child // -schoolchildren to -schoolchild if (s.endsWith("children")) return (cut(s, "ren")); // -eau to -eaux //No other common words end in eaux if (s.endsWith("eaux")) return (cut(s, "x")); // -ieu to -ieux //No other common words end in ieux if (s.endsWith("ieux")) return (cut(s, "x")); // -nx to -nges // Pay attention not to kill words ending in -nge with plural -nges // Take only Greek words (works fine, only a handfull of exceptions) if (s.endsWith("nges") && greek(s)) return (cut(s, "nges") + "nx"); // -[sc]h to -[sc]hes //No other common word ends with "shes", "ches" or "she(s)" //Quite a lot end with "che(s)", filter them out if (s.endsWith("shes") || s.endsWith("ches") && !Arrays.asList(categoryCHE_CHES).contains(s)) return (cut(s, "es")); // -ss to -sses // No other common singular word ends with "sses" // Filter out those ending in "sse(s)" if (s.endsWith("sses") && !Arrays.asList(categorySSE_SSES).contains(s) && !s.endsWith("mousses")) return (cut(s, "es")); // -x to -xes // No other common word ends with "xe(s)" except for "axe" if (s.endsWith("xes") && !s.equals("axes")) return (cut(s, "es")); // -[nlw]ife to -[nlw]ives //No other common word ends with "[nlw]ive(s)" except for olive if (s.endsWith("nives") || s.endsWith("lives") && !s.endsWith("olives") || s.endsWith("wives")) return (cut(s, "ves") + "fe"); // -[aeo]lf to -ves exceptions: valve, solve // -[^d]eaf to -ves exceptions: heave, weave // -arf to -ves no exception if (s.endsWith("alves") && !s.endsWith("valves") || s.endsWith("olves") && !s.endsWith("solves") || s.endsWith("eaves") && !s.endsWith("heaves") && !s.endsWith("weaves") || s.endsWith("arves") || s.endsWith("shelves") || s.endsWith("selves")) return (cut(s, "ves") + "f"); // -y to -ies // -ies is very uncommon as a singular suffix // but -ie is quite common, filter them out if (s.endsWith("ies") && !Arrays.asList(categoryIE_IES).contains(s)) return (cut(s, "ies") + "y"); // -o to -oes // Some words end with -oe, so don't kill the "e" if (s.endsWith("oes") && !Arrays.asList(categoryOE_OES).contains(s)) return (cut(s, "es")); // -s to -ses // -z to -zes // no words end with "-ses" or "-zes" in singular if (s.endsWith("ses") || s.endsWith("zes")) return (cut(s, "es")); // - to -s if (s.endsWith("s") && !s.endsWith("ss") && !s.endsWith("is")) return (cut(s, "s")); return (s); } public static boolean _checkPluralNoLex(String s) { boolean res = false; if (Arrays.asList(categoryUM_A).contains(s) || Arrays.asList(categoryON_A).contains(s) || Arrays.asList(categoryO_I).contains(s) || Arrays.asList(categoryUS_I).contains(s) || Arrays.asList(categoryIX_ICES).contains(s)) { res = true; } res = res || (Arrays.asList(categoryIRR).indexOf(s) % 2 == 0); //if (res) System.out.println("checkPlural: "+s+" "+res); return res; } }
200920_0
package validation; import model.Customer; import java.io.File; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.bind.util.ValidationEventCollector; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; /** * Voorbeeld: http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html * We maken gebruik van een XML schema: customer.xsd om het xml bestand input.txt te valideren. * Volgens het XML schema gelden volgende restricties: * - The customer's name cannot be longer than 5 characters. * - The customer cannot have more than 2 phone numbers. * <p> * Vandaar dat de ValidationEventHandler daarover informatie verzamelt en afdrukt. */ public class UnmarshalDemo { public static void main(String[] args) throws Exception { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File("customer.xsd")); JAXBContext context = JAXBContext.newInstance(Customer.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(schema); unmarshaller.setEventHandler(event -> { System.out.println("\nEVENT"); System.out.println("SEVERITY: " + event.getSeverity()); System.out.println("MESSAGE: " + event.getMessage()); System.out.println("LINKED EXCEPTION: " + event.getLinkedException()); System.out.println("LOCATOR"); System.out.println(" LINE NUMBER: " + event.getLocator().getLineNumber()); System.out.println(" COLUMN NUMBER: " + event.getLocator().getColumnNumber()); System.out.println(" OFFSET: " + event.getLocator().getOffset()); System.out.println(" OBJECT: " + event.getLocator().getObject()); System.out.println(" NODE: " + event.getLocator().getNode()); System.out.println(" URL: " + event.getLocator().getURL()); return true; }); Customer customer = (Customer) unmarshaller.unmarshal(new File("input.xml")); System.out.println("\n" + customer); } }
gvdhaege/KdG
Java Programming 2/Module 09 - XML & JSON/demo/Voorbeelden_09_XML_JSON/4_JAXB_with_XMLschema/src/validation/UnmarshalDemo.java
608
/** * Voorbeeld: http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html * We maken gebruik van een XML schema: customer.xsd om het xml bestand input.txt te valideren. * Volgens het XML schema gelden volgende restricties: * - The customer's name cannot be longer than 5 characters. * - The customer cannot have more than 2 phone numbers. * <p> * Vandaar dat de ValidationEventHandler daarover informatie verzamelt en afdrukt. */
block_comment
nl
package validation; import model.Customer; import java.io.File; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.bind.util.ValidationEventCollector; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; /** * Voorbeeld: http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html <SUF>*/ public class UnmarshalDemo { public static void main(String[] args) throws Exception { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File("customer.xsd")); JAXBContext context = JAXBContext.newInstance(Customer.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(schema); unmarshaller.setEventHandler(event -> { System.out.println("\nEVENT"); System.out.println("SEVERITY: " + event.getSeverity()); System.out.println("MESSAGE: " + event.getMessage()); System.out.println("LINKED EXCEPTION: " + event.getLinkedException()); System.out.println("LOCATOR"); System.out.println(" LINE NUMBER: " + event.getLocator().getLineNumber()); System.out.println(" COLUMN NUMBER: " + event.getLocator().getColumnNumber()); System.out.println(" OFFSET: " + event.getLocator().getOffset()); System.out.println(" OBJECT: " + event.getLocator().getObject()); System.out.println(" NODE: " + event.getLocator().getNode()); System.out.println(" URL: " + event.getLocator().getURL()); return true; }); Customer customer = (Customer) unmarshaller.unmarshal(new File("input.xml")); System.out.println("\n" + customer); } }
200921_0
package validation; import model.Customer; import model.PhoneNumber; import java.io.File; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; /** * Voorbeeld: http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html * We maken gebruik van een XML schema: customer.xsd om xml te genereren. * Volgens het XML schema gelden volgende restricties: * - The customer's name cannot be longer than 5 characters. * - The customer cannot have more than 2 phone numbers. * <p> * Vandaar dat de ValidationEventHandler daarover informatie verzamelt en afdrukt. */ public class MarshalDemo { public static void main(String[] args) throws Exception { Customer customer = new Customer(); customer.setName("Jane Doe"); customer.getPhoneNumbers().add("+32.36131313"); customer.getPhoneNumbers().add("+32.36131700"); customer.getPhoneNumbers().add("+32.32192672"); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File("customer.xsd")); JAXBContext context = JAXBContext.newInstance(Customer.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setSchema(schema); marshaller.setEventHandler(event -> { System.out.println("\nEVENT"); System.out.println("SEVERITY: " + event.getSeverity()); System.out.println("MESSAGE: " + event.getMessage()); System.out.println("LINKED EXCEPTION: " + event.getLinkedException()); System.out.println("LOCATOR"); System.out.println(" LINE NUMBER: " + event.getLocator().getLineNumber()); System.out.println(" COLUMN NUMBER: " + event.getLocator().getColumnNumber()); System.out.println(" OFFSET: " + event.getLocator().getOffset()); System.out.println(" OBJECT: " + event.getLocator().getObject()); System.out.println(" NODE: " + event.getLocator().getNode()); System.out.println(" URL: " + event.getLocator().getURL()); return true; }); System.out.println(); marshaller.marshal(customer, System.out); } }
gvdhaege/KdG
Java Programming 2/Module 09 - XML & JSON/demo/Voorbeelden_09_XML_JSON/4_JAXB_with_XMLschema/src/validation/MarshalDemo.java
652
/** * Voorbeeld: http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html * We maken gebruik van een XML schema: customer.xsd om xml te genereren. * Volgens het XML schema gelden volgende restricties: * - The customer's name cannot be longer than 5 characters. * - The customer cannot have more than 2 phone numbers. * <p> * Vandaar dat de ValidationEventHandler daarover informatie verzamelt en afdrukt. */
block_comment
nl
package validation; import model.Customer; import model.PhoneNumber; import java.io.File; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; /** * Voorbeeld: http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html <SUF>*/ public class MarshalDemo { public static void main(String[] args) throws Exception { Customer customer = new Customer(); customer.setName("Jane Doe"); customer.getPhoneNumbers().add("+32.36131313"); customer.getPhoneNumbers().add("+32.36131700"); customer.getPhoneNumbers().add("+32.32192672"); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(new File("customer.xsd")); JAXBContext context = JAXBContext.newInstance(Customer.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setSchema(schema); marshaller.setEventHandler(event -> { System.out.println("\nEVENT"); System.out.println("SEVERITY: " + event.getSeverity()); System.out.println("MESSAGE: " + event.getMessage()); System.out.println("LINKED EXCEPTION: " + event.getLinkedException()); System.out.println("LOCATOR"); System.out.println(" LINE NUMBER: " + event.getLocator().getLineNumber()); System.out.println(" COLUMN NUMBER: " + event.getLocator().getColumnNumber()); System.out.println(" OFFSET: " + event.getLocator().getOffset()); System.out.println(" OBJECT: " + event.getLocator().getObject()); System.out.println(" NODE: " + event.getLocator().getNode()); System.out.println(" URL: " + event.getLocator().getURL()); return true; }); System.out.println(); marshaller.marshal(customer, System.out); } }
200935_13
package de.golfgl.lightblocks.model; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.ByteArray; import com.badlogic.gdx.utils.IntArray; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.badlogic.gdx.utils.Queue; import de.golfgl.lightblocks.LightBlocksGame; import de.golfgl.lightblocks.backend.MatchEntity; import de.golfgl.lightblocks.backend.MatchTurnRequestInfo; import de.golfgl.lightblocks.screen.PlayScreen; import de.golfgl.lightblocks.state.InitGameParameters; import de.golfgl.lightblocks.state.Replay; /** * Turn based battle * <p> * Created by Benjamin Schulte on 17.12.2018. */ public class BackendBattleModel extends GameModel { public static final String MODEL_ID = "tbbattle"; public static final float PREPARE_TIME_SECONDS = 1.5f; protected MatchEntity matchEntity; MatchTurnRequestInfo infoForServer; private boolean firstTurnFirstPlayer = false; private boolean sendingGarbage = false; private int garbageReceived; private ByteArray garbagePos = new ByteArray(); private float prepareForGameDelay = PREPARE_TIME_SECONDS; private MatchEntity.MatchTurn lastTurnOnServer; private int lastTurnSequenceNum; private int firstPartOverTimeMs; private int everyThingsOverTimeMs; private Queue<WaitingGarbage> waitingGarbage = new Queue<>(); private IntArray completeDrawyer = new IntArray(); private String currentTurnString; private boolean beginPaused; @Override public InitGameParameters getInitParameters() { return null; } @Override public String getIdentifier() { return MODEL_ID; } @Override public String getGoalDescription() { return "goalModelTurnBattle"; } @Override public boolean beginPaused() { return beginPaused; } @Override public void setUserInterface(LightBlocksGame app, PlayScreen playScreen, IGameModelListener uiGameboard) { super.setUserInterface(app, playScreen, uiGameboard); if (!beginPaused) uiGameboard.showMotivation(IGameModelListener.MotivationTypes.prepare, null); else // Hack: es muss über 0 sein. siehe update() prepareForGameDelay = 0.02f; } @Override public boolean showTime() { return true; } @Override public int getShownTimeMs() { return everyThingsOverTimeMs - getScore().getTimeMs(); } @Override public Color getShownTimeColor() { return sendingGarbage ? app.theme.focussedColor : app.theme.getScoreColorOrWhite(); } @Override public String getShownTimeDescription() { return currentTurnString; } @Override public void startNewGame(InitGameParameters newGameParams) { matchEntity = newGameParams.getMatchEntity(); beginPaused = newGameParams.isStartPaused(); infoForServer = new MatchTurnRequestInfo(); infoForServer.matchId = matchEntity.uuid; infoForServer.turnKey = newGameParams.getPlayKey(); if (matchEntity.yourReplay != null) getReplay().fromString(matchEntity.yourReplay); if (matchEntity.turns.size() == 1 && matchEntity.opponentReplay == null && !matchEntity.turns.get(0).opponentPlayed) { // Sonderfall erster Zug des ersten Spielers firstTurnFirstPlayer = true; lastTurnSequenceNum = 0; // gleich mit Garbage senden beginnen sendingGarbage = true; } else { lastTurnSequenceNum = matchEntity.turns.size() - 1; lastTurnOnServer = matchEntity.turns.get(lastTurnSequenceNum); calcWaitingGarbage(); // garbageReceived initialisieren: aufsummieren, wieviel ich vorher schon bekommen habe for (int turnPos = 0; turnPos < lastTurnSequenceNum; turnPos++) { int linesSentInTurn = matchEntity.turns.get(turnPos).linesSent; // kleiner als 0 bedeutet, ich habe garbage bekommen if (linesSentInTurn < 0) garbageReceived = garbageReceived + linesSentInTurn * -1; } } //GarbageGapPos for (int i = 0; i < matchEntity.garbageGap.length(); i++) garbagePos.add((byte) (matchEntity.garbageGap.charAt(i) - 48)); // Spielendezeiten vorberechnen firstPartOverTimeMs = (matchEntity.turnBlockCount + getThisTurnsStartSeconds()) * 1000; everyThingsOverTimeMs = (matchEntity.turnBlockCount * (firstTurnFirstPlayer ? 1 : 2) + getThisTurnsStartSeconds()) * 1000; setCurrentTurnString(lastTurnSequenceNum + 1); super.startNewGame(newGameParams); } protected void setCurrentTurnString(int i) { currentTurnString = "#" + (i); } @Override protected void initializeActiveAndNextTetromino() { int blocksSoFar = 0; if (matchEntity.drawyer != null) { for (int i = 0; i < matchEntity.drawyer.length(); i++) { completeDrawyer.add(matchEntity.drawyer.charAt(i) - 48); } } // Drawyer blocksSoFar = getScore().getDrawnTetrominos(); if (completeDrawyer.size > blocksSoFar) { int[] queue = new int[completeDrawyer.size - blocksSoFar]; for (int i = 0; i < queue.length; i++) queue[i] = completeDrawyer.get(blocksSoFar + i); drawyer.queueNextTetrominos(queue); } super.initializeActiveAndNextTetromino(); } @Override protected void activeTetrominoDropped() { if (getScore().getDrawnTetrominos() > completeDrawyer.size) completeDrawyer.add(getActiveTetromino().getTetrominoType()); } public void calcWaitingGarbage() { // das andere Replay laden und am Ende des letzten Zuges positionieren Replay otherPlayersReplay = new Replay(); otherPlayersReplay.fromString(matchEntity.opponentReplay); otherPlayersReplay.seekToTimePos(1000 * getThisTurnsStartSeconds()); Replay.ReplayStep step = otherPlayersReplay.seekToPreviousStep(); int clearedLinesLastStep = otherPlayersReplay.getCurrentAdditionalInformation() != null ? otherPlayersReplay.getCurrentAdditionalInformation().clearedLines : 0; while (step != null && step.timeMs <= (getThisTurnsStartSeconds() + matchEntity.turnBlockCount) * 1000) { int garbageThisStep = 0; int clearedLinesThisStep = otherPlayersReplay.getCurrentAdditionalInformation().clearedLines - clearedLinesLastStep; clearedLinesLastStep = otherPlayersReplay.getCurrentAdditionalInformation().clearedLines; if (clearedLinesThisStep == 4) garbageThisStep = 4; else if (clearedLinesThisStep >= 2) garbageThisStep = clearedLinesThisStep - 1; if (garbageThisStep > 0) waitingGarbage.addLast(new WaitingGarbage(step.timeMs, garbageThisStep)); step = otherPlayersReplay.seekToNextStep(); } } public int getThisTurnsStartSeconds() { return (lastTurnSequenceNum) * matchEntity.turnBlockCount; } @Override protected void initGameScore(int beginningLevel) { super.initGameScore(beginningLevel); // Das Spielbrett aufbauen und den Score setzen initFromLastTurn(); } public void initFromLastTurn() { // Den vorherigen Spielzustand wieder herstellen if (matchEntity.yourReplay != null) { getReplay().seekToLastStep(); getGameboard().readFromReplay(getReplay().getCurrentGameboard()); // Score vom letzten Mals setzen Replay.AdditionalInformation replayAdditionalInfo = getReplay().getCurrentAdditionalInformation(); getScore().initFromReplay(getReplay().getCurrentScore(), replayAdditionalInfo.clearedLines, // der aktive Block wenn das Spiel unterbrochen wird ist in blocknum zweimal gezählt, daher // entsprechend oft abziehen replayAdditionalInfo.blockNum - ((lastTurnSequenceNum + 1) / 2), Math.max(getThisTurnsStartSeconds() * 1000, getReplay().getLastStep().timeMs)); } } @Override protected int[] drawGarbageLines(int removedLines) { if (waitingGarbage.size > 0 && waitingGarbage.first().timeMs <= getScore().getTimeMs()) { WaitingGarbage garbageToAdd = this.waitingGarbage.removeFirst(); int[] retVal = new int[garbageToAdd.lines]; for (int i = 0; i < retVal.length; i++) { int garbageSlotPos = garbageReceived / MultiplayerModel.GARBAGEGAP_CHANGECOUNT; if (garbagePos.size <= garbageSlotPos) garbagePos.add((byte) MathUtils.random(0, Gameboard.GAMEBOARD_COLUMNS - 1)); retVal[i] = garbagePos.get(garbageSlotPos); garbageReceived++; } return retVal; } return null; } @Override public void update(float delta) { if (prepareForGameDelay > 0) { prepareForGameDelay = prepareForGameDelay - delta; if (prepareForGameDelay > 0) return; uiGameboard.showMotivation(sendingGarbage ? IGameModelListener.MotivationTypes.turnGarbage : IGameModelListener.MotivationTypes.turnSurvive, matchEntity.opponentNick); } super.update(delta); if (isGameOver()) return; boolean firstPartOver = sendingGarbage || firstTurnFirstPlayer || getScore().getTimeMs() > firstPartOverTimeMs; boolean everythingsOver = isGameOver() || getScore().getTimeMs() > everyThingsOverTimeMs; if (firstPartOver && !sendingGarbage) { if (!lastTurnOnServer.opponentDroppedOut) { //TODO Stärker Anzeigen in Spielfeld sendingGarbage = true; uiGameboard.showMotivation(IGameModelListener.MotivationTypes.turnGarbage, matchEntity.opponentNick); setCurrentTurnString(lastTurnSequenceNum + 2); } else { // beenden, falls der Gegner bereits beendet hat setGameOverWon(IGameModelListener.MotivationTypes.playerOver); } } else if (everythingsOver) { setGameOverWon(IGameModelListener.MotivationTypes.turnOver); } } @Override protected void submitGameEnded(boolean success) { super.submitGameEnded(success); infoForServer.droppedOut = !success; if (!getScore().isFraudDetected()) infoForServer.replay = replay.toString(); infoForServer.platform = app.backendManager.getPlatformString(); infoForServer.inputType = ""; //TODO // Drawyer zusammenbauen int blocks = getScore().getDrawnTetrominos(); if (completeDrawyer.size < blocks) completeDrawyer.add(getActiveTetromino().getTetrominoType()); if (completeDrawyer.size < blocks + 1) completeDrawyer.add(getNextTetromino().getTetrominoType()); IntArray onDrawyer = this.drawyer.getDrawyerQueue(); for (int i = 0; i < onDrawyer.size; i++) if (completeDrawyer.size < blocks + 2 + i) completeDrawyer.add(onDrawyer.get(i)); StringBuilder drawyerString = new StringBuilder(); for (int i = 0; i < completeDrawyer.size; i++) drawyerString.append(String.valueOf(completeDrawyer.get(i))); infoForServer.drawyer = drawyerString.toString(); StringBuilder garbagePosString = new StringBuilder(); for (int i = 0; i < garbagePos.size; i++) garbagePosString.append(String.valueOf(garbagePos.get(i))); infoForServer.garbagePos = garbagePosString.toString(); app.backendManager.queueAndUploadPlayedTurn(infoForServer); } @Override public boolean isHoldMoveAllowedByModel() { // Problem 1: das Hold Piece müsste für die Unterbrechnung gespeichert werden // Problem 2 (größer): Hold verändert den Block Count im Replay, der zum Finden des Aufsatzpunkts benötigt wird return false; } @Override public void read(Json json, JsonValue jsonData) { throw new UnsupportedOperationException("Not allowed in battle mode"); } @Override public void write(Json json) { throw new UnsupportedOperationException("Not allowed in battle mode"); } @Override public String saveGameModel() { return null; } @Override public String getExitWarningMessage() { return "exitWarningTurnBattle"; } private static class WaitingGarbage { int timeMs; int lines; public WaitingGarbage(int timeMs, int lines) { this.timeMs = timeMs; this.lines = lines; } } }
MrStahlfelge/lightblocks
core/src/de/golfgl/lightblocks/model/BackendBattleModel.java
3,296
// beenden, falls der Gegner bereits beendet hat
line_comment
nl
package de.golfgl.lightblocks.model; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.ByteArray; import com.badlogic.gdx.utils.IntArray; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; import com.badlogic.gdx.utils.Queue; import de.golfgl.lightblocks.LightBlocksGame; import de.golfgl.lightblocks.backend.MatchEntity; import de.golfgl.lightblocks.backend.MatchTurnRequestInfo; import de.golfgl.lightblocks.screen.PlayScreen; import de.golfgl.lightblocks.state.InitGameParameters; import de.golfgl.lightblocks.state.Replay; /** * Turn based battle * <p> * Created by Benjamin Schulte on 17.12.2018. */ public class BackendBattleModel extends GameModel { public static final String MODEL_ID = "tbbattle"; public static final float PREPARE_TIME_SECONDS = 1.5f; protected MatchEntity matchEntity; MatchTurnRequestInfo infoForServer; private boolean firstTurnFirstPlayer = false; private boolean sendingGarbage = false; private int garbageReceived; private ByteArray garbagePos = new ByteArray(); private float prepareForGameDelay = PREPARE_TIME_SECONDS; private MatchEntity.MatchTurn lastTurnOnServer; private int lastTurnSequenceNum; private int firstPartOverTimeMs; private int everyThingsOverTimeMs; private Queue<WaitingGarbage> waitingGarbage = new Queue<>(); private IntArray completeDrawyer = new IntArray(); private String currentTurnString; private boolean beginPaused; @Override public InitGameParameters getInitParameters() { return null; } @Override public String getIdentifier() { return MODEL_ID; } @Override public String getGoalDescription() { return "goalModelTurnBattle"; } @Override public boolean beginPaused() { return beginPaused; } @Override public void setUserInterface(LightBlocksGame app, PlayScreen playScreen, IGameModelListener uiGameboard) { super.setUserInterface(app, playScreen, uiGameboard); if (!beginPaused) uiGameboard.showMotivation(IGameModelListener.MotivationTypes.prepare, null); else // Hack: es muss über 0 sein. siehe update() prepareForGameDelay = 0.02f; } @Override public boolean showTime() { return true; } @Override public int getShownTimeMs() { return everyThingsOverTimeMs - getScore().getTimeMs(); } @Override public Color getShownTimeColor() { return sendingGarbage ? app.theme.focussedColor : app.theme.getScoreColorOrWhite(); } @Override public String getShownTimeDescription() { return currentTurnString; } @Override public void startNewGame(InitGameParameters newGameParams) { matchEntity = newGameParams.getMatchEntity(); beginPaused = newGameParams.isStartPaused(); infoForServer = new MatchTurnRequestInfo(); infoForServer.matchId = matchEntity.uuid; infoForServer.turnKey = newGameParams.getPlayKey(); if (matchEntity.yourReplay != null) getReplay().fromString(matchEntity.yourReplay); if (matchEntity.turns.size() == 1 && matchEntity.opponentReplay == null && !matchEntity.turns.get(0).opponentPlayed) { // Sonderfall erster Zug des ersten Spielers firstTurnFirstPlayer = true; lastTurnSequenceNum = 0; // gleich mit Garbage senden beginnen sendingGarbage = true; } else { lastTurnSequenceNum = matchEntity.turns.size() - 1; lastTurnOnServer = matchEntity.turns.get(lastTurnSequenceNum); calcWaitingGarbage(); // garbageReceived initialisieren: aufsummieren, wieviel ich vorher schon bekommen habe for (int turnPos = 0; turnPos < lastTurnSequenceNum; turnPos++) { int linesSentInTurn = matchEntity.turns.get(turnPos).linesSent; // kleiner als 0 bedeutet, ich habe garbage bekommen if (linesSentInTurn < 0) garbageReceived = garbageReceived + linesSentInTurn * -1; } } //GarbageGapPos for (int i = 0; i < matchEntity.garbageGap.length(); i++) garbagePos.add((byte) (matchEntity.garbageGap.charAt(i) - 48)); // Spielendezeiten vorberechnen firstPartOverTimeMs = (matchEntity.turnBlockCount + getThisTurnsStartSeconds()) * 1000; everyThingsOverTimeMs = (matchEntity.turnBlockCount * (firstTurnFirstPlayer ? 1 : 2) + getThisTurnsStartSeconds()) * 1000; setCurrentTurnString(lastTurnSequenceNum + 1); super.startNewGame(newGameParams); } protected void setCurrentTurnString(int i) { currentTurnString = "#" + (i); } @Override protected void initializeActiveAndNextTetromino() { int blocksSoFar = 0; if (matchEntity.drawyer != null) { for (int i = 0; i < matchEntity.drawyer.length(); i++) { completeDrawyer.add(matchEntity.drawyer.charAt(i) - 48); } } // Drawyer blocksSoFar = getScore().getDrawnTetrominos(); if (completeDrawyer.size > blocksSoFar) { int[] queue = new int[completeDrawyer.size - blocksSoFar]; for (int i = 0; i < queue.length; i++) queue[i] = completeDrawyer.get(blocksSoFar + i); drawyer.queueNextTetrominos(queue); } super.initializeActiveAndNextTetromino(); } @Override protected void activeTetrominoDropped() { if (getScore().getDrawnTetrominos() > completeDrawyer.size) completeDrawyer.add(getActiveTetromino().getTetrominoType()); } public void calcWaitingGarbage() { // das andere Replay laden und am Ende des letzten Zuges positionieren Replay otherPlayersReplay = new Replay(); otherPlayersReplay.fromString(matchEntity.opponentReplay); otherPlayersReplay.seekToTimePos(1000 * getThisTurnsStartSeconds()); Replay.ReplayStep step = otherPlayersReplay.seekToPreviousStep(); int clearedLinesLastStep = otherPlayersReplay.getCurrentAdditionalInformation() != null ? otherPlayersReplay.getCurrentAdditionalInformation().clearedLines : 0; while (step != null && step.timeMs <= (getThisTurnsStartSeconds() + matchEntity.turnBlockCount) * 1000) { int garbageThisStep = 0; int clearedLinesThisStep = otherPlayersReplay.getCurrentAdditionalInformation().clearedLines - clearedLinesLastStep; clearedLinesLastStep = otherPlayersReplay.getCurrentAdditionalInformation().clearedLines; if (clearedLinesThisStep == 4) garbageThisStep = 4; else if (clearedLinesThisStep >= 2) garbageThisStep = clearedLinesThisStep - 1; if (garbageThisStep > 0) waitingGarbage.addLast(new WaitingGarbage(step.timeMs, garbageThisStep)); step = otherPlayersReplay.seekToNextStep(); } } public int getThisTurnsStartSeconds() { return (lastTurnSequenceNum) * matchEntity.turnBlockCount; } @Override protected void initGameScore(int beginningLevel) { super.initGameScore(beginningLevel); // Das Spielbrett aufbauen und den Score setzen initFromLastTurn(); } public void initFromLastTurn() { // Den vorherigen Spielzustand wieder herstellen if (matchEntity.yourReplay != null) { getReplay().seekToLastStep(); getGameboard().readFromReplay(getReplay().getCurrentGameboard()); // Score vom letzten Mals setzen Replay.AdditionalInformation replayAdditionalInfo = getReplay().getCurrentAdditionalInformation(); getScore().initFromReplay(getReplay().getCurrentScore(), replayAdditionalInfo.clearedLines, // der aktive Block wenn das Spiel unterbrochen wird ist in blocknum zweimal gezählt, daher // entsprechend oft abziehen replayAdditionalInfo.blockNum - ((lastTurnSequenceNum + 1) / 2), Math.max(getThisTurnsStartSeconds() * 1000, getReplay().getLastStep().timeMs)); } } @Override protected int[] drawGarbageLines(int removedLines) { if (waitingGarbage.size > 0 && waitingGarbage.first().timeMs <= getScore().getTimeMs()) { WaitingGarbage garbageToAdd = this.waitingGarbage.removeFirst(); int[] retVal = new int[garbageToAdd.lines]; for (int i = 0; i < retVal.length; i++) { int garbageSlotPos = garbageReceived / MultiplayerModel.GARBAGEGAP_CHANGECOUNT; if (garbagePos.size <= garbageSlotPos) garbagePos.add((byte) MathUtils.random(0, Gameboard.GAMEBOARD_COLUMNS - 1)); retVal[i] = garbagePos.get(garbageSlotPos); garbageReceived++; } return retVal; } return null; } @Override public void update(float delta) { if (prepareForGameDelay > 0) { prepareForGameDelay = prepareForGameDelay - delta; if (prepareForGameDelay > 0) return; uiGameboard.showMotivation(sendingGarbage ? IGameModelListener.MotivationTypes.turnGarbage : IGameModelListener.MotivationTypes.turnSurvive, matchEntity.opponentNick); } super.update(delta); if (isGameOver()) return; boolean firstPartOver = sendingGarbage || firstTurnFirstPlayer || getScore().getTimeMs() > firstPartOverTimeMs; boolean everythingsOver = isGameOver() || getScore().getTimeMs() > everyThingsOverTimeMs; if (firstPartOver && !sendingGarbage) { if (!lastTurnOnServer.opponentDroppedOut) { //TODO Stärker Anzeigen in Spielfeld sendingGarbage = true; uiGameboard.showMotivation(IGameModelListener.MotivationTypes.turnGarbage, matchEntity.opponentNick); setCurrentTurnString(lastTurnSequenceNum + 2); } else { // beenden, falls<SUF> setGameOverWon(IGameModelListener.MotivationTypes.playerOver); } } else if (everythingsOver) { setGameOverWon(IGameModelListener.MotivationTypes.turnOver); } } @Override protected void submitGameEnded(boolean success) { super.submitGameEnded(success); infoForServer.droppedOut = !success; if (!getScore().isFraudDetected()) infoForServer.replay = replay.toString(); infoForServer.platform = app.backendManager.getPlatformString(); infoForServer.inputType = ""; //TODO // Drawyer zusammenbauen int blocks = getScore().getDrawnTetrominos(); if (completeDrawyer.size < blocks) completeDrawyer.add(getActiveTetromino().getTetrominoType()); if (completeDrawyer.size < blocks + 1) completeDrawyer.add(getNextTetromino().getTetrominoType()); IntArray onDrawyer = this.drawyer.getDrawyerQueue(); for (int i = 0; i < onDrawyer.size; i++) if (completeDrawyer.size < blocks + 2 + i) completeDrawyer.add(onDrawyer.get(i)); StringBuilder drawyerString = new StringBuilder(); for (int i = 0; i < completeDrawyer.size; i++) drawyerString.append(String.valueOf(completeDrawyer.get(i))); infoForServer.drawyer = drawyerString.toString(); StringBuilder garbagePosString = new StringBuilder(); for (int i = 0; i < garbagePos.size; i++) garbagePosString.append(String.valueOf(garbagePos.get(i))); infoForServer.garbagePos = garbagePosString.toString(); app.backendManager.queueAndUploadPlayedTurn(infoForServer); } @Override public boolean isHoldMoveAllowedByModel() { // Problem 1: das Hold Piece müsste für die Unterbrechnung gespeichert werden // Problem 2 (größer): Hold verändert den Block Count im Replay, der zum Finden des Aufsatzpunkts benötigt wird return false; } @Override public void read(Json json, JsonValue jsonData) { throw new UnsupportedOperationException("Not allowed in battle mode"); } @Override public void write(Json json) { throw new UnsupportedOperationException("Not allowed in battle mode"); } @Override public String saveGameModel() { return null; } @Override public String getExitWarningMessage() { return "exitWarningTurnBattle"; } private static class WaitingGarbage { int timeMs; int lines; public WaitingGarbage(int timeMs, int lines) { this.timeMs = timeMs; this.lines = lines; } } }
200936_15
package bankprojekt.verwaltung; import bankprojekt.verarbeitung.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Klasse zum Verwalten der Konten * * @author Tom Dittrich [email protected] * @version 0.8 * @date 05.05.2017 */ public class Bank { long bankleitzahl; long groesteKtn = 1000000000; Map<Long, Konto> Kontenliste = new HashMap<>(); /** * Default Konstruktor * Erzeugt eine Test BLZ 123456789 */ public Bank() { this(123456789); } /** * Konstruktor * * @param bankleitzahl BLZ */ public Bank(long bankleitzahl) { this.bankleitzahl = bankleitzahl; } /** * Getter Bankleitzahl * * @return BLZ */ public long getBankleitzahl() { return bankleitzahl; } /** * @param nummer * @return */ public double getKontostand(long nummer) { // ! Exception bauen Konto tempKonto = Kontenliste.get(nummer); return tempKonto.getKontostand(); } /** * Erstellt Girkonto * * @param inhaber Kunde * @return die erstellte Kontonummer */ public long girokontoErstellen(Kunde inhaber) { // Generiert KTN, in 64er Abstaenden // zufaellige KTN moeglich, dann Abfrage mit containsKey ob vorhanden long ktn = groesteKtn + 64; this.groesteKtn = ktn; Konto neuGiro = new Girokonto(inhaber, ktn, 500); Kontenliste.put(ktn, neuGiro); return ktn; } /** * Erstellt Sparbuch * * @param inhaber Kunde * @return die erstellte Kontonummer */ public long sparbuchErstellen(Kunde inhaber) { // Generiert KTN, in 64er Abstaenden // zufaellige KTN moeglich, dann Abfrage mit containsKey ob vorhanden long ktn = groesteKtn + 64; this.groesteKtn = ktn; Konto neuSpar = new Sparbuch(inhaber, ktn); Kontenliste.put(ktn, neuSpar); return ktn; } /** * Gibt alle Kontonummern und den dazugehörigen Kontostand aus * * @return KTNs + Betrag */ public String getAlleKonten() { String ausgabe = ""; for (Long nr : Kontenliste.keySet()) { ausgabe += "Kontonummer: " + nr + " Kontostand: " + getKontostand(nr) + System.getProperty("line.separator"); } return ausgabe; } /** * Gibt alle Kontonummern und den dazugehörigen Kontostand aus * * @return KTNs + Betrag */ @Override public String toString() { return getAlleKonten(); } /** * Gibt alle Kontonummern zurück * * @return Kontonummern als ArrayListe */ public List<Long> getAlleKontonummern() { List<Long> liste = new ArrayList<>(); for (Long nr : Kontenliste.keySet()) { liste.add(nr); } return liste; } /** * Hebt Geld vom angegebenen Konto ab * * @param von welches Konto * @param betrag Betrag * @return hat es geklappt? * @throws GesperrtException falls gesperrt */ public boolean geldAbheben(long von, double betrag) throws GesperrtException { return (Kontenliste.get(von)).abheben(betrag); } /** * Zahlt Geld auf das angegebene Konto ein * * @param auf welches Konto * @param betrag Betrag */ public void geldEinzahlen(long auf, double betrag) { (Kontenliste.get(auf)).einzahlen(betrag); } /** * Loescht ein Konto VOLLSTAENDIG * * @param nummer welches Konto * @return hat es geklappt? */ public boolean kontoLoeschen(long nummer) { Kontenliste.remove(nummer); return !Kontenliste.containsKey(nummer); } /** * Ueberweist Geld von einem Girokonto zu anderen Girokonto * Bankintern (gleiche BLZ) * * @param vonKontonr von welchem Konto * @param nachKontonr zu welchem Konto * @param betrag Betrag * @param verwendungszweck Verwendungszweck * @return hat es geklappt? * @throws GesperrtException falls ein Konto gesperrt */ public boolean geldUeberweisen(long vonKontonr, long nachKontonr, double betrag, String verwendungszweck) throws GesperrtException { // ! noch Exceptions bauen (KTN nicht vorhanden, falsche InstanceOf usw) // "uberweisungAbsenden" und "ueberweisungEmpfangen" koennte man auch nutzen, umstaendlicher boolean ergebnis = false; // Konten vorhanden? Prueft damit gleichzeitig ob beide Konten die // selbe BLZ haben (bzw. in gleicher Map sind) if (Kontenliste.containsKey(vonKontonr) && Kontenliste.containsKey(nachKontonr)) { // Beides Girokonten? if (Kontenliste.get(vonKontonr) instanceof Girokonto && Kontenliste.get(nachKontonr) instanceof Girokonto) { // klappt das Abheben? (Dispo?, Kontobetrag, Gesperrt) if (geldAbheben(vonKontonr, betrag)) { geldEinzahlen(nachKontonr, betrag); ergebnis = true; } } else { System.out.println("Ueberweisung nur zwischen Girokonten moeglich."); } } else { System.out.println("Mind. eine Kontonummer ist falsch"); } return ergebnis; } }
tomdittrich/htw_java_03
04_collections/main/java/bankprojekt/verwaltung/Bank.java
1,744
/** * Hebt Geld vom angegebenen Konto ab * * @param von welches Konto * @param betrag Betrag * @return hat es geklappt? * @throws GesperrtException falls gesperrt */
block_comment
nl
package bankprojekt.verwaltung; import bankprojekt.verarbeitung.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Klasse zum Verwalten der Konten * * @author Tom Dittrich [email protected] * @version 0.8 * @date 05.05.2017 */ public class Bank { long bankleitzahl; long groesteKtn = 1000000000; Map<Long, Konto> Kontenliste = new HashMap<>(); /** * Default Konstruktor * Erzeugt eine Test BLZ 123456789 */ public Bank() { this(123456789); } /** * Konstruktor * * @param bankleitzahl BLZ */ public Bank(long bankleitzahl) { this.bankleitzahl = bankleitzahl; } /** * Getter Bankleitzahl * * @return BLZ */ public long getBankleitzahl() { return bankleitzahl; } /** * @param nummer * @return */ public double getKontostand(long nummer) { // ! Exception bauen Konto tempKonto = Kontenliste.get(nummer); return tempKonto.getKontostand(); } /** * Erstellt Girkonto * * @param inhaber Kunde * @return die erstellte Kontonummer */ public long girokontoErstellen(Kunde inhaber) { // Generiert KTN, in 64er Abstaenden // zufaellige KTN moeglich, dann Abfrage mit containsKey ob vorhanden long ktn = groesteKtn + 64; this.groesteKtn = ktn; Konto neuGiro = new Girokonto(inhaber, ktn, 500); Kontenliste.put(ktn, neuGiro); return ktn; } /** * Erstellt Sparbuch * * @param inhaber Kunde * @return die erstellte Kontonummer */ public long sparbuchErstellen(Kunde inhaber) { // Generiert KTN, in 64er Abstaenden // zufaellige KTN moeglich, dann Abfrage mit containsKey ob vorhanden long ktn = groesteKtn + 64; this.groesteKtn = ktn; Konto neuSpar = new Sparbuch(inhaber, ktn); Kontenliste.put(ktn, neuSpar); return ktn; } /** * Gibt alle Kontonummern und den dazugehörigen Kontostand aus * * @return KTNs + Betrag */ public String getAlleKonten() { String ausgabe = ""; for (Long nr : Kontenliste.keySet()) { ausgabe += "Kontonummer: " + nr + " Kontostand: " + getKontostand(nr) + System.getProperty("line.separator"); } return ausgabe; } /** * Gibt alle Kontonummern und den dazugehörigen Kontostand aus * * @return KTNs + Betrag */ @Override public String toString() { return getAlleKonten(); } /** * Gibt alle Kontonummern zurück * * @return Kontonummern als ArrayListe */ public List<Long> getAlleKontonummern() { List<Long> liste = new ArrayList<>(); for (Long nr : Kontenliste.keySet()) { liste.add(nr); } return liste; } /** * Hebt Geld vom<SUF>*/ public boolean geldAbheben(long von, double betrag) throws GesperrtException { return (Kontenliste.get(von)).abheben(betrag); } /** * Zahlt Geld auf das angegebene Konto ein * * @param auf welches Konto * @param betrag Betrag */ public void geldEinzahlen(long auf, double betrag) { (Kontenliste.get(auf)).einzahlen(betrag); } /** * Loescht ein Konto VOLLSTAENDIG * * @param nummer welches Konto * @return hat es geklappt? */ public boolean kontoLoeschen(long nummer) { Kontenliste.remove(nummer); return !Kontenliste.containsKey(nummer); } /** * Ueberweist Geld von einem Girokonto zu anderen Girokonto * Bankintern (gleiche BLZ) * * @param vonKontonr von welchem Konto * @param nachKontonr zu welchem Konto * @param betrag Betrag * @param verwendungszweck Verwendungszweck * @return hat es geklappt? * @throws GesperrtException falls ein Konto gesperrt */ public boolean geldUeberweisen(long vonKontonr, long nachKontonr, double betrag, String verwendungszweck) throws GesperrtException { // ! noch Exceptions bauen (KTN nicht vorhanden, falsche InstanceOf usw) // "uberweisungAbsenden" und "ueberweisungEmpfangen" koennte man auch nutzen, umstaendlicher boolean ergebnis = false; // Konten vorhanden? Prueft damit gleichzeitig ob beide Konten die // selbe BLZ haben (bzw. in gleicher Map sind) if (Kontenliste.containsKey(vonKontonr) && Kontenliste.containsKey(nachKontonr)) { // Beides Girokonten? if (Kontenliste.get(vonKontonr) instanceof Girokonto && Kontenliste.get(nachKontonr) instanceof Girokonto) { // klappt das Abheben? (Dispo?, Kontobetrag, Gesperrt) if (geldAbheben(vonKontonr, betrag)) { geldEinzahlen(nachKontonr, betrag); ergebnis = true; } } else { System.out.println("Ueberweisung nur zwischen Girokonten moeglich."); } } else { System.out.println("Mind. eine Kontonummer ist falsch"); } return ergebnis; } }
200968_10
/* Dandelion, a Lisp plugin for Eclipse. Copyright (C) 2007 Michael Bohn 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 de.defmacro.dandelion.internal.core.connection; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; import de.defmacro.dandelion.internal.LispPluginActivator; /** * Abstrakte Basisklasse fuer Jobs die Aktionen * an einer Lisp-Umgebung durchfuehren. * @author Michael Bohn */ public abstract class AbstractJob extends Job { /** * Konstaten fuer die Darstellung einer Jobart. * @author Michael Bohn */ public enum JobType { START_JOB(0), INIT_JOB(2), EVAL_JOB(3); private final int fPriority; JobType(final int priority) { this.fPriority = priority; } /** * Liefert die Prioritaet dieses Jobtyps. * Eine kleinere Zahl bedeutet eine hoehere Prioritaet. * @return */ public int getPriority() { return fPriority; } } private IEnvironment fServer; private boolean fDidConnect; /** * Initialisiert einen neuen Umgebungsjob. * @param jobName - Name des Jobs * @param server - {@link IEnvironment}-Objekt an dem die Aktion durchgefuehrt wird. */ public AbstractJob(final String jobName, final IEnvironment server) { super(jobName); setSystem(false); this.fServer = server; //null-check in EvalServer Rule setRule(new EnvironmentRule(server, getType())); } /** * @see Job */ @Override protected abstract IStatus run(IProgressMonitor monitor); /** * Liefert den Typ des Jobs. * @return {@link JobType} der Typ des Jobs */ public abstract JobType getType(); /** * Liefert <code>true</code> wenn dieser Job die Verbindung hergestellt hat * vor der Verwendung. * @return */ public boolean hasConnected() { return fDidConnect; } /** * Liefert die Lisp-Umgebung des Jobs. * @return */ public IEnvironment getEvalServer() { return fServer; } /** * @see Job#belongsTo(Object) */ @Override public boolean belongsTo(final Object family) { if( !(family instanceof IEnvironment) ) { return false; } //invariante != null return ((IEnvironment)family).equals(fServer); } /** * Stellt eine hergestellt Verbindung zur Lisp-Umgebung sicher. * Alle abgeleiteten Klassen sollten diese Methode zur Verbindungsherstellung verwenden. * @param connection - Das Verbindungsobjekt * @throws ConnectionException - wenn ein herstellen der Verbindung nicht moeglich ist */ protected void ensureConnected(final IConnection connection) throws ConnectionException { if(!connection.isConnected()) { connection.connect(); fDidConnect = true; } } /** * Erzeugt ein {@link IStatus}-Objekt fuer einen aufgetretenen Fehler. * @param message - Die Fehlerbeschreibung * @param e - Das Fehlerobjekt * @return Ein {@link IStatus}-Objekt */ protected IStatus error(final String message, final Exception e) { return new Status(IStatus.ERROR, LispPluginActivator.ID, 0, message, e); } }
Ragnaroek/dandelion
Dandelion/src/de/defmacro/dandelion/internal/core/connection/AbstractJob.java
1,127
/** * @see Job#belongsTo(Object) */
block_comment
nl
/* Dandelion, a Lisp plugin for Eclipse. Copyright (C) 2007 Michael Bohn 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 de.defmacro.dandelion.internal.core.connection; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.jobs.Job; import de.defmacro.dandelion.internal.LispPluginActivator; /** * Abstrakte Basisklasse fuer Jobs die Aktionen * an einer Lisp-Umgebung durchfuehren. * @author Michael Bohn */ public abstract class AbstractJob extends Job { /** * Konstaten fuer die Darstellung einer Jobart. * @author Michael Bohn */ public enum JobType { START_JOB(0), INIT_JOB(2), EVAL_JOB(3); private final int fPriority; JobType(final int priority) { this.fPriority = priority; } /** * Liefert die Prioritaet dieses Jobtyps. * Eine kleinere Zahl bedeutet eine hoehere Prioritaet. * @return */ public int getPriority() { return fPriority; } } private IEnvironment fServer; private boolean fDidConnect; /** * Initialisiert einen neuen Umgebungsjob. * @param jobName - Name des Jobs * @param server - {@link IEnvironment}-Objekt an dem die Aktion durchgefuehrt wird. */ public AbstractJob(final String jobName, final IEnvironment server) { super(jobName); setSystem(false); this.fServer = server; //null-check in EvalServer Rule setRule(new EnvironmentRule(server, getType())); } /** * @see Job */ @Override protected abstract IStatus run(IProgressMonitor monitor); /** * Liefert den Typ des Jobs. * @return {@link JobType} der Typ des Jobs */ public abstract JobType getType(); /** * Liefert <code>true</code> wenn dieser Job die Verbindung hergestellt hat * vor der Verwendung. * @return */ public boolean hasConnected() { return fDidConnect; } /** * Liefert die Lisp-Umgebung des Jobs. * @return */ public IEnvironment getEvalServer() { return fServer; } /** * @see Job#belongsTo(Object) <SUF>*/ @Override public boolean belongsTo(final Object family) { if( !(family instanceof IEnvironment) ) { return false; } //invariante != null return ((IEnvironment)family).equals(fServer); } /** * Stellt eine hergestellt Verbindung zur Lisp-Umgebung sicher. * Alle abgeleiteten Klassen sollten diese Methode zur Verbindungsherstellung verwenden. * @param connection - Das Verbindungsobjekt * @throws ConnectionException - wenn ein herstellen der Verbindung nicht moeglich ist */ protected void ensureConnected(final IConnection connection) throws ConnectionException { if(!connection.isConnected()) { connection.connect(); fDidConnect = true; } } /** * Erzeugt ein {@link IStatus}-Objekt fuer einen aufgetretenen Fehler. * @param message - Die Fehlerbeschreibung * @param e - Das Fehlerobjekt * @return Ein {@link IStatus}-Objekt */ protected IStatus error(final String message, final Exception e) { return new Status(IStatus.ERROR, LispPluginActivator.ID, 0, message, e); } }
200999_4
/* @author Nick @version 0607 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; public class Datenbank { int zug = 0; Connection connection = null; public void datenbankErstellen() { try { // Pfad zur SQLite-Datenbankdatei angeben String dbFile = "datenbank.db"; // Verbindung zur Datenbank herstellen connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile); } catch (SQLException e) { e.printStackTrace(); } } Statement statement = null; ResultSet resultSet = null; public void tabelleErstellen(){ try { statement = connection.createStatement(); // Tabelle erstellen String createTableQuery = "CREATE TABLE IF NOT EXISTS zuege (Zugnummer INT, Zug TEXT)"; statement.executeUpdate(createTableQuery); } catch (SQLException e) { e.printStackTrace(); } } public void insertDataIntoTable(Connection connection, String text) throws SQLException { // SQL-Abfrage zum Einfügen von Daten String insertQuery = "INSERT INTO zuege (Zugnummer, Zug) VALUES (?, ?)"; // Prepared Statement vorbereiten PreparedStatement statement = connection.prepareStatement(insertQuery); // Werte für die Parameter festlegen statement.setInt(1, zug); statement.setString(2, text); // Einfügen der Daten ausführen statement.executeUpdate(); // Prepared Statement schließen statement.close(); } public static void clearTable(Connection connection) throws SQLException { //leert die komplette Tabelle String deleteQuery = "DELETE FROM zuege"; Statement statement = connection.createStatement(); statement.executeUpdate(deleteQuery); statement.close(); } }
wulusub/Schach
Schach-main/Datenbank.java
509
// Prepared Statement vorbereiten
line_comment
nl
/* @author Nick @version 0607 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; public class Datenbank { int zug = 0; Connection connection = null; public void datenbankErstellen() { try { // Pfad zur SQLite-Datenbankdatei angeben String dbFile = "datenbank.db"; // Verbindung zur Datenbank herstellen connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile); } catch (SQLException e) { e.printStackTrace(); } } Statement statement = null; ResultSet resultSet = null; public void tabelleErstellen(){ try { statement = connection.createStatement(); // Tabelle erstellen String createTableQuery = "CREATE TABLE IF NOT EXISTS zuege (Zugnummer INT, Zug TEXT)"; statement.executeUpdate(createTableQuery); } catch (SQLException e) { e.printStackTrace(); } } public void insertDataIntoTable(Connection connection, String text) throws SQLException { // SQL-Abfrage zum Einfügen von Daten String insertQuery = "INSERT INTO zuege (Zugnummer, Zug) VALUES (?, ?)"; // Prepared Statement<SUF> PreparedStatement statement = connection.prepareStatement(insertQuery); // Werte für die Parameter festlegen statement.setInt(1, zug); statement.setString(2, text); // Einfügen der Daten ausführen statement.executeUpdate(); // Prepared Statement schließen statement.close(); } public static void clearTable(Connection connection) throws SQLException { //leert die komplette Tabelle String deleteQuery = "DELETE FROM zuege"; Statement statement = connection.createStatement(); statement.executeUpdate(deleteQuery); statement.close(); } }
201015_6
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
at-Sven/SMT
src/datenbank/Datenbank.java
1,393
// temp feld, falls andere noch benoetigt werden sollten
line_comment
nl
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld,<SUF> "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
201015_7
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
at-Sven/SMT
src/datenbank/Datenbank.java
1,393
// temp feld, falls andere noch benoetigt werden sollten
line_comment
nl
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld,<SUF> "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
201015_8
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
at-Sven/SMT
src/datenbank/Datenbank.java
1,393
// temp feld, falls andere noch benoetigt werden sollten
line_comment
nl
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld,<SUF> "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
201015_9
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
at-Sven/SMT
src/datenbank/Datenbank.java
1,393
// temp feld, falls andere noch benoetigt werden sollten
line_comment
nl
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld,<SUF> "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
201015_10
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
at-Sven/SMT
src/datenbank/Datenbank.java
1,393
// temp feld, falls andere noch benoetigt werden sollten
line_comment
nl
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld,<SUF> "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
201015_11
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
at-Sven/SMT
src/datenbank/Datenbank.java
1,393
// temp feld, falls andere noch benoetigt werden sollten
line_comment
nl
package datenbank; import datenbank.connection.SQLiteDatenbankverbindung; import java.sql.SQLException; /** * Klasse zur Steuerung der Datenbankvorgänge. Definiert als Singelton: * https://de.wikibooks.org/wiki/Muster:_Java:_Singleton */ public class Datenbank extends SQLiteDatenbankverbindung { private static Datenbank db; private final static String DBFILE = "smt_db.sqlite"; /** * private Konstruktor */ private Datenbank() { super(DBFILE); } /** * Klassenmethode, die die Instanz der Datenbankklasse zurückgibt (Fabrikmethode genannt) * * @return Instanz der Datenbank-Klasse */ public static Datenbank getInstance() { if (db == null) { // Neue Instanz von Datenbank erzeugen db = new Datenbank(); db.init(); } return db; } /** * Diese Methode soll die erforderliche Datenstruktur der Datenbank herstellen */ private void init() { try { execute("CREATE TABLE IF NOT EXISTS \"Users\" (" + "uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "Email VARCHAR(100) NOT NULL, " + "Passwort VARCHAR(100) NOT NULL" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaAccounts\" (" + "sid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER UNIQUE NOT NULL, " + "twConsumerKey VARCHAR(200), " + "twConsumerSecret VARCHAR(200), " + "twAccessToken VARCHAR(200), " + "twAccessTokenSecret VARCHAR(200)," + "fbAppID VARCHAR(500), " + // facebook AppID "fbAppSecret VARCHAR(500), " + // facebook AppSecret "fbUserAccessToken VARCHAR(500), " + // facebook fbUserAccessToken "fbPageAccessToken VARCHAR(500), " + // facebook fbPageAccessToken "fbAccessTokenExpireDate INTEGER, " + // temp feld, falls andere noch benoetigt werden sollten "soc1 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc2 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc3 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc4 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc5 VARCHAR(300), " + // temp feld, falls andere noch benoetigt werden sollten "soc6 VARCHAR(300), " + // temp feld,<SUF> "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"SocialmediaPosts\" (" + "pid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + // uid from Users "sid INTEGER NOT NULL, " + // sid from SocialMediaAccounts "platform INTEGER NOT NULL, " + // 1 = twitter, 2 = facebook (where to post helper var) "fbsite VARCHAR(300) DEFAULT NULL, " + // z.B.: me/feed, me/photos, pageId/feed, groupId/feed... "posttext VARCHAR(2000), " + // posttag+hashtags "mediafile VARCHAR(500), " + // image or video file "posttime DATETIME NOT NULL, " + // datetime when post will be send "poststatus INTEGER DEFAULT 0, " + // 0 noch nicht versendet, 1 versendet, 2 fehler etc. "FOREIGN KEY (uid) REFERENCES Users(uid), " + "FOREIGN KEY (sid) REFERENCES SocialmediaAccounts(sid) " + ");"); execute("CREATE TABLE IF NOT EXISTS \"Hashtags\" (" + "hid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "theme VARCHAR(100) NOT NULL, " + "hashtags VARCHAR(500) NOT NULL, " + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); /* // TwitterAccounts und FacebookAccounts in einem Table SocialmediaAccounts verfügbar // hier als Kommentar, falls es doch extra benötigt werden sollte: execute("CREATE TABLE IF NOT EXISTS \"TwitterAccounts\" (" + "tid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "consumerKey VARCHAR(200) NOT NULL," + "consumerSecret VARCHAR(200) NOT NULL," + "accessToken VARCHAR(200) NOT NULL," + "accessTokenSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); execute("CREATE TABLE IF NOT EXISTS \"FacebookAccounts\" (" + "fid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + "uid INTEGER NOT NULL, " + "username VARCHAR(200) NOT NULL," + "passwort VARCHAR(200) NOT NULL," + "appID VARCHAR(200) NOT NULL," + "appSecret VARCHAR(200) NOT NULL," + "FOREIGN KEY (uid) REFERENCES Users(uid)" + ");"); */ this.commit(); } catch (SQLException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Diese Methode pr&uuml;ft, ob eine Datenbankverbindung da ist * * @return Status der Datenbank */ public static Boolean isConnected() { if (db != null) { return true; } return false; } }
201017_6
package game.model; import java.util.Collections; import java.util.Vector; /** * short description of Deck * * @author Brenden Jose * @version 1.0 * @since 27.06.2020 */ public class Deck { private Vector<Karte> deck; private int kartenImDeck; private int oberste; /** * Instantiates a new Deck. */ public Deck() { deck = new Vector<>(); deckherstellen(); } //Methoden /** * Deckherstellen. */ public void deckherstellen() { Karte.Symbol[] symbols = Karte.Symbol.values(); kartenImDeck = 0; for (int k = 0; k < 2; k++) { for (int i = 0; i < symbols.length; i++) { Karte.Symbol symbol = symbols[i]; for (int j = 0; j < 9; j++) { Karte karte = new Karte(symbol, Karte.Nummer.getNummer(j)); deck.add(karte); kartenImDeck++; } } } oberste = deck.size() - 1; assert deck.get(oberste) != null; } /** * Mischen. */ public void mischen() { Collections.shuffle(deck); } /** * Ziehen karte. * * @return the karte */ public Karte ziehen() { Karte gezogeneKarte = deck.get(oberste); deck.remove(gezogeneKarte); oberste--; kartenImDeck--; return gezogeneKarte; } /** * Add karte. * * @param karte the karte */ public void addKarte(Karte karte) { deck.add(karte); } /** * Deck leeren. */ public void deckLeeren() { deck.removeAll(deck); } /** * Gets karten im deck. * * @return the karten im deck */ public int getKartenImDeck() { return kartenImDeck; } public void setOberste(int oberste) { this.oberste = oberste; } }
Brenden7788/TschauSepp
src/game/model/Deck.java
581
/** * Deck leeren. */
block_comment
nl
package game.model; import java.util.Collections; import java.util.Vector; /** * short description of Deck * * @author Brenden Jose * @version 1.0 * @since 27.06.2020 */ public class Deck { private Vector<Karte> deck; private int kartenImDeck; private int oberste; /** * Instantiates a new Deck. */ public Deck() { deck = new Vector<>(); deckherstellen(); } //Methoden /** * Deckherstellen. */ public void deckherstellen() { Karte.Symbol[] symbols = Karte.Symbol.values(); kartenImDeck = 0; for (int k = 0; k < 2; k++) { for (int i = 0; i < symbols.length; i++) { Karte.Symbol symbol = symbols[i]; for (int j = 0; j < 9; j++) { Karte karte = new Karte(symbol, Karte.Nummer.getNummer(j)); deck.add(karte); kartenImDeck++; } } } oberste = deck.size() - 1; assert deck.get(oberste) != null; } /** * Mischen. */ public void mischen() { Collections.shuffle(deck); } /** * Ziehen karte. * * @return the karte */ public Karte ziehen() { Karte gezogeneKarte = deck.get(oberste); deck.remove(gezogeneKarte); oberste--; kartenImDeck--; return gezogeneKarte; } /** * Add karte. * * @param karte the karte */ public void addKarte(Karte karte) { deck.add(karte); } /** * Deck leeren. <SUF>*/ public void deckLeeren() { deck.removeAll(deck); } /** * Gets karten im deck. * * @return the karten im deck */ public int getKartenImDeck() { return kartenImDeck; } public void setOberste(int oberste) { this.oberste = oberste; } }
201039_3
package com.francelabs.datafari.servlets.admin.cluster; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.francelabs.datafari.utils.AuthenticatedUserName; import com.francelabs.datafari.utils.ClusterActionsConfiguration; import com.francelabs.datafari.utils.Environment; import com.francelabs.datafari.audit.AuditLogUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * Servlet implementation class getAllUsersAndRoles */ @WebServlet("/admin/cluster/reinitializemcf") public class ClusterReinit extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = LogManager.getLogger(ClusterReinit.class); // Threshold to compare dates, if dates are closer than the threshold, they are // considered equal. This is in seconds. private static final long THRESHOLD = 10; private static final String DATAFARI_HOME = Environment.getEnvironmentVariable("DATAFARI_HOME") != null ? Environment.getEnvironmentVariable("DATAFARI_HOME") : "/opt/datafari"; private static final String SCRIPT_WORKING_DIR = DATAFARI_HOME + "/bin"; private static final String REPORT_BASE_DIR = DATAFARI_HOME + "/logs"; /** * @see HttpServlet#HttpServlet() */ public ClusterReinit() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String action = request.getParameter("action"); if (action != null && action.equals("getReport")) { ClusterActionsUtils.outputReport(request, response, ClusterAction.REINIT); } else { ClusterActionsUtils.outputStatus(request, response, ClusterAction.REINIT); } } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { ClusterActionsUtils.setUnmanagedDoPost(req, resp); } @Override protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { DateTimeFormatter dateFormatter = ClusterActionsConfiguration.dateFormatter; ClusterActionsConfiguration config = ClusterActionsConfiguration.getInstance(); final JSONObject jsonResponse = new JSONObject(); req.setCharacterEncoding("utf8"); resp.setContentType("application/json"); req.getParameter("annotatorActivation"); try { BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); final JSONParser parser = new JSONParser(); JSONObject requestBody = (JSONObject) parser.parse(br); String lastReinitString = config.getProperty(ClusterActionsConfiguration.LAST_REINIT_DATE); Instant putDate = Instant.parse((String) requestBody.get("date")); Instant now = Instant.now(); Instant lastReinit = Instant.MIN; if (lastReinitString != null && !lastReinitString.equals("")) { Instant.parse(lastReinitString); } long nowToPutDate = Math.abs(now.until(putDate, ChronoUnit.SECONDS)); long lastReinitToPutDate = Math.abs(lastReinit.until(putDate, ChronoUnit.SECONDS)); if (lastReinitToPutDate > THRESHOLD && nowToPutDate < THRESHOLD) { // If the put date is far enough from the last restart // and close enough to the current time => we can restart // But we need first to check that the install is standard (mandatory) // and that we are either in unmanaged mode, or no other action is in progress String unmanagedString = config.getProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE); boolean unmanagedMode = unmanagedString != null && unmanagedString.contentEquals("true"); boolean noActionInProgress = true; for (ClusterAction action : ClusterAction.values()) { try { noActionInProgress = noActionInProgress && !ClusterActionsUtils.isActionInProgress(action); } catch (FileNotFoundException e) { logger.info("Last report file for " + action + " not found, actions are not blocked."); } } if (ClusterActionsUtils.isStandardInstall() && (unmanagedMode || noActionInProgress)) { // retrieve AuthenticatedUserName if user authenticated (it should be as we are // in the admin...) String authenticatedUserName = AuthenticatedUserName.getName(req); // Log for audit purposes who did the request String unmanagedModeNotice = unmanagedMode ? " with UNMANAGED UI state" : ""; AuditLogUtil.log("Reinitialization", authenticatedUserName, req.getRemoteAddr(), "Datafari full reinitialization request received from user " + authenticatedUserName + " from ip " + req.getRemoteAddr() + unmanagedModeNotice + " through the admin UI, answering YES to both questions: Do you confirm " + "that you successfully backed up the connectors beforehand (it " + "is part of the backup process) ? and Do you confirm that " + "you have understood that you will need to reindex you data ?"); String reportName = "cluster-reinitialization-" + dateFormatter.format(putDate) + ".log"; // Set the property file containing the last reinitialization date config.setProperty(ClusterActionsConfiguration.LAST_REINIT_DATE, dateFormatter.format(putDate)); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_IP, req.getRemoteAddr()); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_USER, authenticatedUserName); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_REPORT, reportName); config.setProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE, "false"); config.saveProperties(); // Wire up the call to the bash script final String workingDirectory = SCRIPT_WORKING_DIR; final String filePath = REPORT_BASE_DIR + File.separator + reportName; final String[] command = { "/bin/bash", "./reinitUtils/global_reinit_restore_mcf.sh" }; final ProcessBuilder p = new ProcessBuilder(command); p.redirectErrorStream(true); p.redirectOutput(new File(filePath)); p.directory(new File(workingDirectory)); // Not storing the Process in any manner, tomcat will be restarted anyway so any // variable would be lost, this would be useless. Could store a process ID but // it is not necessary as the report file will provide us information about the // status. p.start(); jsonResponse.put("success", "true"); jsonResponse.put("message", "Datafari reinitializing"); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); for (ClusterAction action : ClusterAction.values()) { try { if (ClusterActionsUtils.isActionInProgress(action)) { // Only the last action in progress will be added to the result // object, but there should be only one active at a time anyway. jsonResponse.put("message", "A " + action + " is in progress."); }; } catch (FileNotFoundException e) { // Nothing to do here, but the file being missing is not a problem, so // catch it to ensure it does not escalate. } } if(jsonResponse.get("message") == null) { jsonResponse.put("message", "An unidentified error prevented the action completion."); } } } else { // Send an error message. if (nowToPutDate >= THRESHOLD) { logger.warn("Trying to perform a cluster reinitialization with a date that is not now. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); jsonResponse.put("message", "Can't reinitialize with a date different than now, now and provided date differ by " + lastReinitToPutDate + "seconds"); } else if (lastReinitToPutDate <= THRESHOLD) { logger.warn( "Trying to perform a cluster reinitialization with a date that is too close to the last reinitialization. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); jsonResponse.put("success", "false"); jsonResponse.put("message", "Server already reinitialized at this date"); } } } catch (Exception e) { logger.error("Couldn't perform the cluster reinitialization.", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); jsonResponse.clear(); jsonResponse.put("success", "false"); jsonResponse.put("message", "Unexpected server error while processing the reinitialization query"); } final PrintWriter out = resp.getWriter(); out.print(jsonResponse); } }
francelabs/datafari
datafari-webapp/src/main/java/com/francelabs/datafari/servlets/admin/cluster/ClusterReinit.java
2,389
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
package com.francelabs.datafari.servlets.admin.cluster; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.francelabs.datafari.utils.AuthenticatedUserName; import com.francelabs.datafari.utils.ClusterActionsConfiguration; import com.francelabs.datafari.utils.Environment; import com.francelabs.datafari.audit.AuditLogUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * Servlet implementation class getAllUsersAndRoles */ @WebServlet("/admin/cluster/reinitializemcf") public class ClusterReinit extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = LogManager.getLogger(ClusterReinit.class); // Threshold to compare dates, if dates are closer than the threshold, they are // considered equal. This is in seconds. private static final long THRESHOLD = 10; private static final String DATAFARI_HOME = Environment.getEnvironmentVariable("DATAFARI_HOME") != null ? Environment.getEnvironmentVariable("DATAFARI_HOME") : "/opt/datafari"; private static final String SCRIPT_WORKING_DIR = DATAFARI_HOME + "/bin"; private static final String REPORT_BASE_DIR = DATAFARI_HOME + "/logs"; /** * @see HttpServlet#HttpServlet() <SUF>*/ public ClusterReinit() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String action = request.getParameter("action"); if (action != null && action.equals("getReport")) { ClusterActionsUtils.outputReport(request, response, ClusterAction.REINIT); } else { ClusterActionsUtils.outputStatus(request, response, ClusterAction.REINIT); } } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { ClusterActionsUtils.setUnmanagedDoPost(req, resp); } @Override protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { DateTimeFormatter dateFormatter = ClusterActionsConfiguration.dateFormatter; ClusterActionsConfiguration config = ClusterActionsConfiguration.getInstance(); final JSONObject jsonResponse = new JSONObject(); req.setCharacterEncoding("utf8"); resp.setContentType("application/json"); req.getParameter("annotatorActivation"); try { BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); final JSONParser parser = new JSONParser(); JSONObject requestBody = (JSONObject) parser.parse(br); String lastReinitString = config.getProperty(ClusterActionsConfiguration.LAST_REINIT_DATE); Instant putDate = Instant.parse((String) requestBody.get("date")); Instant now = Instant.now(); Instant lastReinit = Instant.MIN; if (lastReinitString != null && !lastReinitString.equals("")) { Instant.parse(lastReinitString); } long nowToPutDate = Math.abs(now.until(putDate, ChronoUnit.SECONDS)); long lastReinitToPutDate = Math.abs(lastReinit.until(putDate, ChronoUnit.SECONDS)); if (lastReinitToPutDate > THRESHOLD && nowToPutDate < THRESHOLD) { // If the put date is far enough from the last restart // and close enough to the current time => we can restart // But we need first to check that the install is standard (mandatory) // and that we are either in unmanaged mode, or no other action is in progress String unmanagedString = config.getProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE); boolean unmanagedMode = unmanagedString != null && unmanagedString.contentEquals("true"); boolean noActionInProgress = true; for (ClusterAction action : ClusterAction.values()) { try { noActionInProgress = noActionInProgress && !ClusterActionsUtils.isActionInProgress(action); } catch (FileNotFoundException e) { logger.info("Last report file for " + action + " not found, actions are not blocked."); } } if (ClusterActionsUtils.isStandardInstall() && (unmanagedMode || noActionInProgress)) { // retrieve AuthenticatedUserName if user authenticated (it should be as we are // in the admin...) String authenticatedUserName = AuthenticatedUserName.getName(req); // Log for audit purposes who did the request String unmanagedModeNotice = unmanagedMode ? " with UNMANAGED UI state" : ""; AuditLogUtil.log("Reinitialization", authenticatedUserName, req.getRemoteAddr(), "Datafari full reinitialization request received from user " + authenticatedUserName + " from ip " + req.getRemoteAddr() + unmanagedModeNotice + " through the admin UI, answering YES to both questions: Do you confirm " + "that you successfully backed up the connectors beforehand (it " + "is part of the backup process) ? and Do you confirm that " + "you have understood that you will need to reindex you data ?"); String reportName = "cluster-reinitialization-" + dateFormatter.format(putDate) + ".log"; // Set the property file containing the last reinitialization date config.setProperty(ClusterActionsConfiguration.LAST_REINIT_DATE, dateFormatter.format(putDate)); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_IP, req.getRemoteAddr()); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_USER, authenticatedUserName); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_REPORT, reportName); config.setProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE, "false"); config.saveProperties(); // Wire up the call to the bash script final String workingDirectory = SCRIPT_WORKING_DIR; final String filePath = REPORT_BASE_DIR + File.separator + reportName; final String[] command = { "/bin/bash", "./reinitUtils/global_reinit_restore_mcf.sh" }; final ProcessBuilder p = new ProcessBuilder(command); p.redirectErrorStream(true); p.redirectOutput(new File(filePath)); p.directory(new File(workingDirectory)); // Not storing the Process in any manner, tomcat will be restarted anyway so any // variable would be lost, this would be useless. Could store a process ID but // it is not necessary as the report file will provide us information about the // status. p.start(); jsonResponse.put("success", "true"); jsonResponse.put("message", "Datafari reinitializing"); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); for (ClusterAction action : ClusterAction.values()) { try { if (ClusterActionsUtils.isActionInProgress(action)) { // Only the last action in progress will be added to the result // object, but there should be only one active at a time anyway. jsonResponse.put("message", "A " + action + " is in progress."); }; } catch (FileNotFoundException e) { // Nothing to do here, but the file being missing is not a problem, so // catch it to ensure it does not escalate. } } if(jsonResponse.get("message") == null) { jsonResponse.put("message", "An unidentified error prevented the action completion."); } } } else { // Send an error message. if (nowToPutDate >= THRESHOLD) { logger.warn("Trying to perform a cluster reinitialization with a date that is not now. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); jsonResponse.put("message", "Can't reinitialize with a date different than now, now and provided date differ by " + lastReinitToPutDate + "seconds"); } else if (lastReinitToPutDate <= THRESHOLD) { logger.warn( "Trying to perform a cluster reinitialization with a date that is too close to the last reinitialization. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); jsonResponse.put("success", "false"); jsonResponse.put("message", "Server already reinitialized at this date"); } } } catch (Exception e) { logger.error("Couldn't perform the cluster reinitialization.", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); jsonResponse.clear(); jsonResponse.put("success", "false"); jsonResponse.put("message", "Unexpected server error while processing the reinitialization query"); } final PrintWriter out = resp.getWriter(); out.print(jsonResponse); } }
201092_24
package at.favre.lib.armadillo; import android.content.SharedPreferences; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.security.SecureRandom; import java.util.HashSet; import java.util.Random; import java.util.Set; import at.favre.lib.bytes.Bytes; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assume.assumeFalse; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @SuppressWarnings("deprecation") public abstract class ASecureSharedPreferencesTest { private static final String DEFAULT_PREF_NAME = "test-prefs"; SharedPreferences preferences; @Before public void setup() { try { preferences = create(DEFAULT_PREF_NAME, null).build(); } catch (Exception e) { e.printStackTrace(); throw e; } } @After public void tearDown() { preferences.edit().clear().commit(); } protected abstract Armadillo.Builder create(String name, char[] pw); protected abstract boolean isKitKatOrBelow(); @Test public void simpleMultipleStringGet() { SharedPreferences preferences = create("manytest", null).build(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 100; j++) { String content = "testäI/_²~" + Bytes.random(64 + j).encodeHex(); preferences.edit().putString("k" + j, content).commit(); assertEquals(content, preferences.getString("k" + j, null)); } } } @Test public void simpleGetString() { putAndTestString(preferences, "string1", 1); putAndTestString(preferences, "string2", 16); putAndTestString(preferences, "string3", 200); } @Test public void simpleGetStringApply() { String content = Bytes.random(16).encodeBase64(); preferences.edit().putString("d", content).apply(); assertEquals(content, preferences.getString("d", null)); } private String putAndTestString(SharedPreferences preferences, String key, int length) { String content = Bytes.random(length).encodeBase64(); preferences.edit().putString(key, content).commit(); assertTrue(preferences.contains(key)); assertEquals(content, preferences.getString(key, null)); return content; } @Test public void simpleGetInt() { int content = 3782633; preferences.edit().putInt("int", content).commit(); assertTrue(preferences.contains("int")); assertEquals(content, preferences.getInt("int", 0)); } @Test public void simpleGetLong() { long content = 3782633654323456L; preferences.edit().putLong("long", content).commit(); assertTrue(preferences.contains("long")); assertEquals(content, preferences.getLong("long", 0)); } @Test public void simpleGetFloat() { float content = 728.1891f; preferences.edit().putFloat("float", content).commit(); assertTrue(preferences.contains("float")); assertEquals(content, preferences.getFloat("float", 0), 0.001); } @Test public void simpleGetBoolean() { preferences.edit().putBoolean("boolean", true).commit(); assertTrue(preferences.contains("boolean")); assertTrue(preferences.getBoolean("boolean", false)); preferences.edit().putBoolean("boolean2", false).commit(); assertFalse(preferences.getBoolean("boolean2", true)); } @Test public void simpleGetStringSet() { addStringSet(preferences, 1); addStringSet(preferences, 7); addStringSet(preferences, 128); } private void addStringSet(SharedPreferences preferences, int count) { Set<String> set = new HashSet<>(count); for (int i = 0; i < count; i++) { set.add(Bytes.random(32).encodeBase36() + "input" + i); } preferences.edit().putStringSet("stringSet" + count, set).commit(); assertTrue(preferences.contains("stringSet" + count)); assertEquals(set, preferences.getStringSet("stringSet" + count, null)); } @Test public void testGetDefaults() { assertNull(preferences.getString("s", null)); assertNull(preferences.getStringSet("s", null)); assertFalse(preferences.getBoolean("s", false)); assertEquals(2, preferences.getInt("s", 2)); assertEquals(2, preferences.getLong("s", 2)); assertEquals(2f, preferences.getFloat("s", 2f), 0.0001); } @Test public void testRemove() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertTrue(preferences.getAll().size() >= count); for (int i = 0; i < count; i++) { preferences.edit().remove("string" + i).commit(); assertNull(preferences.getString("string" + i, null)); } } @Test public void testPutNullString() { String id = "testPutNullString"; putAndTestString(preferences, id, new Random().nextInt(32) + 1); preferences.edit().putString(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testPutNullStringSet() { String id = "testPutNullStringSet"; addStringSet(preferences, 8); preferences.edit().putStringSet(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testClear() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertFalse(preferences.getAll().isEmpty()); preferences.edit().clear().commit(); assertTrue(preferences.getAll().isEmpty()); String newContent = putAndTestString(preferences, "new", new Random().nextInt(32) + 1); assertFalse(preferences.getAll().isEmpty()); preferences = create(DEFAULT_PREF_NAME, null).build(); assertEquals(newContent, preferences.getString("new", null)); } @Test public void testInitializeTwice() { SharedPreferences sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s2", 24); } @Test public void testContainsAfterReinitialization() { SharedPreferences sharedPreferences = create("twice", null).build(); String t = putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("twice", null).build(); assertEquals(t, sharedPreferences.getString("s", null)); putAndTestString(sharedPreferences, "s2", 24); } @Test public void simpleStringGetWithPkdf2Password() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new PBKDF2KeyStretcher(1000, null)).build()); } @Test public void simpleStringGetWithBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(7)).build()); } @Test public void simpleStringGetWithBrokenBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(6)).build()); } @Test public void simpleStringGetWithUnicodePw() { preferenceSmokeTest(create("withPw", "ö案äü_ß²áèµÿA2ijʥ".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void simpleStringGetWithFastKDF() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void testWithCompression() { preferenceSmokeTest(create("compressed", null).compress().build()); } @Test public void testWithDifferentFingerprint() { preferenceSmokeTest(create("fingerprint", null) .encryptionFingerprint(Bytes.random(16).array()).build()); preferenceSmokeTest(create("fingerprint2", null) .encryptionFingerprint(new TestEncryptionFingerprint(new byte[16])).build()); } @Test public void testWithDifferentContentDigest() { preferenceSmokeTest(create("contentDigest1", null) .contentKeyDigest(8).build()); preferenceSmokeTest(create("contentDigest2", null) .contentKeyDigest(Bytes.random(16).array()).build()); preferenceSmokeTest(create("contentDigest3", null) .contentKeyDigest((providedMessage, usageName) -> Bytes.from(providedMessage).append(usageName).encodeUtf8()).build()); } @Test public void testWithSecureRandom() { preferenceSmokeTest(create("secureRandom", null) .secureRandom(new SecureRandom()).build()); } @Test public void testEncryptionStrength() { preferenceSmokeTest(create("secureRandom", null) .encryptionKeyStrength(AuthenticatedEncryption.STRENGTH_HIGH).build()); } @Test public void testProvider() { preferenceSmokeTest(create("provider", null) .securityProvider(null).build()); } @Test public void testWithNoObfuscation() { preferenceSmokeTest(create("obfuscate", null) .dataObfuscatorFactory(new NoObfuscator.Factory()).build()); } @Test public void testSetEncryption() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); preferenceSmokeTest(create("enc", null) .symmetricEncryption(new AesGcmEncryption()).build()); } @Test public void testRecoveryPolicy() { preferenceSmokeTest(create("recovery", null) .recoveryPolicy(true, true).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy(new SimpleRecoveryPolicy.Default(true, true)).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy((e, keyHash, base64Encrypted, pwUsed, sharedPreferences) -> System.out.println(e + " " + keyHash + " " + base64Encrypted + " " + pwUsed)).build()); } @Test public void testCustomProtocolVersion() { preferenceSmokeTest(create("protocol", null) .cryptoProtocolVersion(14221).build()); } void preferenceSmokeTest(SharedPreferences preferences) { putAndTestString(preferences, "string", new Random().nextInt(500) + 1); assertNull(preferences.getString("string2", null)); long contentLong = new Random().nextLong(); preferences.edit().putLong("long", contentLong).commit(); assertEquals(contentLong, preferences.getLong("long", 0)); float contentFloat = new Random().nextFloat(); preferences.edit().putFloat("float", contentFloat).commit(); assertEquals(contentFloat, preferences.getFloat("float", 0), 0.001); boolean contentBoolean = new Random().nextBoolean(); preferences.edit().putBoolean("boolean", contentBoolean).commit(); assertEquals(contentBoolean, preferences.getBoolean("boolean", !contentBoolean)); addStringSet(preferences, new Random().nextInt(31) + 1); preferences.edit().remove("string").commit(); assertNull(preferences.getString("string", null)); preferences.edit().remove("float").commit(); assertEquals(-1, preferences.getFloat("float", -1), 0.00001); } @Test public void testChangePassword() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordWithEnabledDerivedPwCache() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), true); } @Test public void testChangePasswordFromNullPassword() { testChangePassword("testChangePasswordFromNullPassword", null, "pw2".toCharArray(), false); } @Test public void testChangePasswordToNullPassword() { testChangePassword("testChangePasswordToNullPassword", "pw1".toCharArray(), null, false); } @Test public void testChangePasswordFromEmptyPassword() { testChangePassword("testChangePasswordFromEmptyPassword", "".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordToEmptyPassword() { testChangePassword("testChangePasswordToEmptyPassword", "pw1".toCharArray(), "".toCharArray(), false); } private void testChangePassword(String name, char[] currentPassword, char[] newPassword, boolean enableCache) { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and change to new one, all the values should be accessible pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.changePassword(clonePassword(newPassword)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw, should be accessible pref = create(name, clonePassword(newPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw, should throw exception, since cannot decrypt pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } private char[] clonePassword(char[] password) { return password == null ? null : password.clone(); } @Test public void testChangePasswordAndKeyStretchingFunction() { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and old ksFn; change to new one, all the values should be accessible pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.changePassword("pw2".toCharArray(), new ArmadilloBcryptKeyStretcher(8)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and new ksFn, should be accessible pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } // open with old pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testInvalidPasswordShouldNotBeAccessible() { // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with invalid pw, should throw exception, since cannot decrypt pref = create("testInvalidPassword", "pw2".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getInt("k2", 0); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getBoolean("k3", false); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testUpgradeToNewerProtocolVersion() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); // open new preference with old encryption config ArmadilloSharedPreferences pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // add some data pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again with encryption config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); // overwrite old data pref.edit().putInt("k2", 2).commit(); // add some data pref.edit().putString("j1", "string2").putInt("j2", 3).putBoolean("j3", false).commit(); pref.close(); // open again with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals("string2", pref.getString("j1", null)); assertEquals(3, pref.getInt("j2", 0)); assertFalse(pref.getBoolean("j3", true)); pref.close(); // open again with new config WITHOUT old config as support config (removing in the builder) pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .clearAdditionalDecryptionProtocolConfigs() // test remove support protocols in builder .build(); // check overwritten data assertEquals(2, pref.getInt("k2", 0)); try { pref.getString("k1", null); fail("should throw exception, since should not be able to decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testSameKeyDifferentTypeShouldOverwrite() { //this is a similar behavior to normal shared preferences SharedPreferences pref = create("testSameKeyDifferentTypeShouldOverwrite", null).build(); pref.edit().putInt("id", 1).commit(); pref.edit().putString("id", "testNotInt").commit(); TestCase.assertEquals("testNotInt", pref.getString("id", null)); try { pref.getInt("id", -1); TestCase.fail("string should be overwritten with int"); } catch (Exception ignored) { } } }
patrickfav/armadillo
armadillo/src/sharedTest/java/at/favre/lib/armadillo/ASecureSharedPreferencesTest.java
6,160
// check overwritten data
line_comment
nl
package at.favre.lib.armadillo; import android.content.SharedPreferences; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.security.SecureRandom; import java.util.HashSet; import java.util.Random; import java.util.Set; import at.favre.lib.bytes.Bytes; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assume.assumeFalse; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @SuppressWarnings("deprecation") public abstract class ASecureSharedPreferencesTest { private static final String DEFAULT_PREF_NAME = "test-prefs"; SharedPreferences preferences; @Before public void setup() { try { preferences = create(DEFAULT_PREF_NAME, null).build(); } catch (Exception e) { e.printStackTrace(); throw e; } } @After public void tearDown() { preferences.edit().clear().commit(); } protected abstract Armadillo.Builder create(String name, char[] pw); protected abstract boolean isKitKatOrBelow(); @Test public void simpleMultipleStringGet() { SharedPreferences preferences = create("manytest", null).build(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 100; j++) { String content = "testäI/_²~" + Bytes.random(64 + j).encodeHex(); preferences.edit().putString("k" + j, content).commit(); assertEquals(content, preferences.getString("k" + j, null)); } } } @Test public void simpleGetString() { putAndTestString(preferences, "string1", 1); putAndTestString(preferences, "string2", 16); putAndTestString(preferences, "string3", 200); } @Test public void simpleGetStringApply() { String content = Bytes.random(16).encodeBase64(); preferences.edit().putString("d", content).apply(); assertEquals(content, preferences.getString("d", null)); } private String putAndTestString(SharedPreferences preferences, String key, int length) { String content = Bytes.random(length).encodeBase64(); preferences.edit().putString(key, content).commit(); assertTrue(preferences.contains(key)); assertEquals(content, preferences.getString(key, null)); return content; } @Test public void simpleGetInt() { int content = 3782633; preferences.edit().putInt("int", content).commit(); assertTrue(preferences.contains("int")); assertEquals(content, preferences.getInt("int", 0)); } @Test public void simpleGetLong() { long content = 3782633654323456L; preferences.edit().putLong("long", content).commit(); assertTrue(preferences.contains("long")); assertEquals(content, preferences.getLong("long", 0)); } @Test public void simpleGetFloat() { float content = 728.1891f; preferences.edit().putFloat("float", content).commit(); assertTrue(preferences.contains("float")); assertEquals(content, preferences.getFloat("float", 0), 0.001); } @Test public void simpleGetBoolean() { preferences.edit().putBoolean("boolean", true).commit(); assertTrue(preferences.contains("boolean")); assertTrue(preferences.getBoolean("boolean", false)); preferences.edit().putBoolean("boolean2", false).commit(); assertFalse(preferences.getBoolean("boolean2", true)); } @Test public void simpleGetStringSet() { addStringSet(preferences, 1); addStringSet(preferences, 7); addStringSet(preferences, 128); } private void addStringSet(SharedPreferences preferences, int count) { Set<String> set = new HashSet<>(count); for (int i = 0; i < count; i++) { set.add(Bytes.random(32).encodeBase36() + "input" + i); } preferences.edit().putStringSet("stringSet" + count, set).commit(); assertTrue(preferences.contains("stringSet" + count)); assertEquals(set, preferences.getStringSet("stringSet" + count, null)); } @Test public void testGetDefaults() { assertNull(preferences.getString("s", null)); assertNull(preferences.getStringSet("s", null)); assertFalse(preferences.getBoolean("s", false)); assertEquals(2, preferences.getInt("s", 2)); assertEquals(2, preferences.getLong("s", 2)); assertEquals(2f, preferences.getFloat("s", 2f), 0.0001); } @Test public void testRemove() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertTrue(preferences.getAll().size() >= count); for (int i = 0; i < count; i++) { preferences.edit().remove("string" + i).commit(); assertNull(preferences.getString("string" + i, null)); } } @Test public void testPutNullString() { String id = "testPutNullString"; putAndTestString(preferences, id, new Random().nextInt(32) + 1); preferences.edit().putString(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testPutNullStringSet() { String id = "testPutNullStringSet"; addStringSet(preferences, 8); preferences.edit().putStringSet(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testClear() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertFalse(preferences.getAll().isEmpty()); preferences.edit().clear().commit(); assertTrue(preferences.getAll().isEmpty()); String newContent = putAndTestString(preferences, "new", new Random().nextInt(32) + 1); assertFalse(preferences.getAll().isEmpty()); preferences = create(DEFAULT_PREF_NAME, null).build(); assertEquals(newContent, preferences.getString("new", null)); } @Test public void testInitializeTwice() { SharedPreferences sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s2", 24); } @Test public void testContainsAfterReinitialization() { SharedPreferences sharedPreferences = create("twice", null).build(); String t = putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("twice", null).build(); assertEquals(t, sharedPreferences.getString("s", null)); putAndTestString(sharedPreferences, "s2", 24); } @Test public void simpleStringGetWithPkdf2Password() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new PBKDF2KeyStretcher(1000, null)).build()); } @Test public void simpleStringGetWithBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(7)).build()); } @Test public void simpleStringGetWithBrokenBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(6)).build()); } @Test public void simpleStringGetWithUnicodePw() { preferenceSmokeTest(create("withPw", "ö案äü_ß²áèµÿA2ijʥ".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void simpleStringGetWithFastKDF() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void testWithCompression() { preferenceSmokeTest(create("compressed", null).compress().build()); } @Test public void testWithDifferentFingerprint() { preferenceSmokeTest(create("fingerprint", null) .encryptionFingerprint(Bytes.random(16).array()).build()); preferenceSmokeTest(create("fingerprint2", null) .encryptionFingerprint(new TestEncryptionFingerprint(new byte[16])).build()); } @Test public void testWithDifferentContentDigest() { preferenceSmokeTest(create("contentDigest1", null) .contentKeyDigest(8).build()); preferenceSmokeTest(create("contentDigest2", null) .contentKeyDigest(Bytes.random(16).array()).build()); preferenceSmokeTest(create("contentDigest3", null) .contentKeyDigest((providedMessage, usageName) -> Bytes.from(providedMessage).append(usageName).encodeUtf8()).build()); } @Test public void testWithSecureRandom() { preferenceSmokeTest(create("secureRandom", null) .secureRandom(new SecureRandom()).build()); } @Test public void testEncryptionStrength() { preferenceSmokeTest(create("secureRandom", null) .encryptionKeyStrength(AuthenticatedEncryption.STRENGTH_HIGH).build()); } @Test public void testProvider() { preferenceSmokeTest(create("provider", null) .securityProvider(null).build()); } @Test public void testWithNoObfuscation() { preferenceSmokeTest(create("obfuscate", null) .dataObfuscatorFactory(new NoObfuscator.Factory()).build()); } @Test public void testSetEncryption() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); preferenceSmokeTest(create("enc", null) .symmetricEncryption(new AesGcmEncryption()).build()); } @Test public void testRecoveryPolicy() { preferenceSmokeTest(create("recovery", null) .recoveryPolicy(true, true).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy(new SimpleRecoveryPolicy.Default(true, true)).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy((e, keyHash, base64Encrypted, pwUsed, sharedPreferences) -> System.out.println(e + " " + keyHash + " " + base64Encrypted + " " + pwUsed)).build()); } @Test public void testCustomProtocolVersion() { preferenceSmokeTest(create("protocol", null) .cryptoProtocolVersion(14221).build()); } void preferenceSmokeTest(SharedPreferences preferences) { putAndTestString(preferences, "string", new Random().nextInt(500) + 1); assertNull(preferences.getString("string2", null)); long contentLong = new Random().nextLong(); preferences.edit().putLong("long", contentLong).commit(); assertEquals(contentLong, preferences.getLong("long", 0)); float contentFloat = new Random().nextFloat(); preferences.edit().putFloat("float", contentFloat).commit(); assertEquals(contentFloat, preferences.getFloat("float", 0), 0.001); boolean contentBoolean = new Random().nextBoolean(); preferences.edit().putBoolean("boolean", contentBoolean).commit(); assertEquals(contentBoolean, preferences.getBoolean("boolean", !contentBoolean)); addStringSet(preferences, new Random().nextInt(31) + 1); preferences.edit().remove("string").commit(); assertNull(preferences.getString("string", null)); preferences.edit().remove("float").commit(); assertEquals(-1, preferences.getFloat("float", -1), 0.00001); } @Test public void testChangePassword() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordWithEnabledDerivedPwCache() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), true); } @Test public void testChangePasswordFromNullPassword() { testChangePassword("testChangePasswordFromNullPassword", null, "pw2".toCharArray(), false); } @Test public void testChangePasswordToNullPassword() { testChangePassword("testChangePasswordToNullPassword", "pw1".toCharArray(), null, false); } @Test public void testChangePasswordFromEmptyPassword() { testChangePassword("testChangePasswordFromEmptyPassword", "".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordToEmptyPassword() { testChangePassword("testChangePasswordToEmptyPassword", "pw1".toCharArray(), "".toCharArray(), false); } private void testChangePassword(String name, char[] currentPassword, char[] newPassword, boolean enableCache) { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and change to new one, all the values should be accessible pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.changePassword(clonePassword(newPassword)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw, should be accessible pref = create(name, clonePassword(newPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw, should throw exception, since cannot decrypt pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } private char[] clonePassword(char[] password) { return password == null ? null : password.clone(); } @Test public void testChangePasswordAndKeyStretchingFunction() { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and old ksFn; change to new one, all the values should be accessible pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.changePassword("pw2".toCharArray(), new ArmadilloBcryptKeyStretcher(8)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and new ksFn, should be accessible pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } // open with old pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testInvalidPasswordShouldNotBeAccessible() { // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with invalid pw, should throw exception, since cannot decrypt pref = create("testInvalidPassword", "pw2".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getInt("k2", 0); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getBoolean("k3", false); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testUpgradeToNewerProtocolVersion() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); // open new preference with old encryption config ArmadilloSharedPreferences pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // add some data pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again with encryption config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); // overwrite old data pref.edit().putInt("k2", 2).commit(); // add some data pref.edit().putString("j1", "string2").putInt("j2", 3).putBoolean("j3", false).commit(); pref.close(); // open again with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals("string2", pref.getString("j1", null)); assertEquals(3, pref.getInt("j2", 0)); assertFalse(pref.getBoolean("j3", true)); pref.close(); // open again with new config WITHOUT old config as support config (removing in the builder) pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .clearAdditionalDecryptionProtocolConfigs() // test remove support protocols in builder .build(); // check overwritten<SUF> assertEquals(2, pref.getInt("k2", 0)); try { pref.getString("k1", null); fail("should throw exception, since should not be able to decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testSameKeyDifferentTypeShouldOverwrite() { //this is a similar behavior to normal shared preferences SharedPreferences pref = create("testSameKeyDifferentTypeShouldOverwrite", null).build(); pref.edit().putInt("id", 1).commit(); pref.edit().putString("id", "testNotInt").commit(); TestCase.assertEquals("testNotInt", pref.getString("id", null)); try { pref.getInt("id", -1); TestCase.fail("string should be overwritten with int"); } catch (Exception ignored) { } } }
201186_20
// 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.doris.nereids.trees.plans.algebra; import org.apache.doris.nereids.exceptions.AnalysisException; import org.apache.doris.nereids.trees.expressions.Alias; import org.apache.doris.nereids.trees.expressions.Expression; import org.apache.doris.nereids.trees.expressions.NamedExpression; import org.apache.doris.nereids.trees.expressions.VirtualSlotReference; import org.apache.doris.nereids.trees.expressions.functions.scalar.GroupingScalarFunction; import org.apache.doris.nereids.trees.plans.Plan; import org.apache.doris.nereids.types.BigIntType; import org.apache.doris.nereids.util.BitUtils; import org.apache.doris.nereids.util.ExpressionUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * Common interface for logical/physical Repeat. */ public interface Repeat<CHILD_PLAN extends Plan> extends Aggregate<CHILD_PLAN> { String COL_GROUPING_ID = "GROUPING_ID"; String GROUPING_PREFIX = "GROUPING_PREFIX_"; List<List<Expression>> getGroupingSets(); List<NamedExpression> getOutputExpressions(); @Override default List<Expression> getGroupByExpressions() { return ExpressionUtils.flatExpressions(getGroupingSets()); } static VirtualSlotReference generateVirtualGroupingIdSlot() { return new VirtualSlotReference(COL_GROUPING_ID, BigIntType.INSTANCE, Optional.empty(), GroupingSetShapes::computeVirtualGroupingIdValue); } static VirtualSlotReference generateVirtualSlotByFunction(GroupingScalarFunction function) { return new VirtualSlotReference( generateVirtualSlotName(function), function.getDataType(), Optional.of(function), function::computeVirtualSlotValue); } /** * get common grouping set expressions. * e.g. grouping sets((a, b, c), (b, c), (c)) * the common expressions is [c] */ default Set<Expression> getCommonGroupingSetExpressions() { List<List<Expression>> groupingSets = getGroupingSets(); Iterator<List<Expression>> iterator = groupingSets.iterator(); Set<Expression> commonGroupingExpressions = Sets.newLinkedHashSet(iterator.next()); while (iterator.hasNext()) { commonGroupingExpressions = Sets.intersection(commonGroupingExpressions, Sets.newLinkedHashSet(iterator.next())); if (commonGroupingExpressions.isEmpty()) { break; } } return commonGroupingExpressions; } /** * getSortedVirtualSlots: order by virtual GROUPING_ID slot first. */ default Set<VirtualSlotReference> getSortedVirtualSlots() { Set<VirtualSlotReference> virtualSlots = ExpressionUtils.collect(getOutputExpressions(), VirtualSlotReference.class::isInstance); VirtualSlotReference virtualGroupingSetIdSlot = virtualSlots.stream() .filter(slot -> slot.getName().equals(COL_GROUPING_ID)) .findFirst() .get(); return ImmutableSet.<VirtualSlotReference>builder() .add(virtualGroupingSetIdSlot) .addAll(Sets.difference(virtualSlots, ImmutableSet.of(virtualGroupingSetIdSlot))) .build(); } /** * computeVirtualSlotValues. backend will fill this long value to the VirtualSlotRef */ default List<List<Long>> computeVirtualSlotValues(Set<VirtualSlotReference> sortedVirtualSlots) { GroupingSetShapes shapes = toShapes(); return sortedVirtualSlots.stream() .map(virtualSlot -> virtualSlot.getComputeLongValueMethod().apply(shapes)) .collect(ImmutableList.toImmutableList()); } /** * flatten the grouping sets and build to a GroupingSetShapes. */ default GroupingSetShapes toShapes() { Set<Expression> flattenGroupingSet = ImmutableSet.copyOf(ExpressionUtils.flatExpressions(getGroupingSets())); List<GroupingSetShape> shapes = Lists.newArrayList(); for (List<Expression> groupingSet : getGroupingSets()) { List<Boolean> shouldBeErasedToNull = Lists.newArrayListWithCapacity(flattenGroupingSet.size()); for (Expression groupingSetExpression : flattenGroupingSet) { shouldBeErasedToNull.add(!groupingSet.contains(groupingSetExpression)); } shapes.add(new GroupingSetShape(shouldBeErasedToNull)); } return new GroupingSetShapes(flattenGroupingSet, shapes); } /** * Generate repeat slot id list corresponding to SlotId according to the original grouping sets * and the actual SlotId. * * eg: groupingSets=((b, a), (a)), output=[a, b] * slotId in the outputTuple: [3, 4] * * return: [(4, 3), (3)] */ default List<Set<Integer>> computeRepeatSlotIdList(List<Integer> slotIdList) { List<Set<Integer>> groupingSetsIndexesInOutput = getGroupingSetsIndexesInOutput(); List<Set<Integer>> repeatSlotIdList = Lists.newArrayList(); for (Set<Integer> groupingSetIndex : groupingSetsIndexesInOutput) { // keep order Set<Integer> repeatSlotId = Sets.newLinkedHashSet(); for (Integer exprInOutputIndex : groupingSetIndex) { repeatSlotId.add(slotIdList.get(exprInOutputIndex)); } repeatSlotIdList.add(repeatSlotId); } return repeatSlotIdList; } /** * getGroupingSetsIndexesInOutput: find the location where the grouping output exists * * e.g. groupingSets=((b, a), (a)), output=[a, b] * return ((1, 0), (1)) */ default List<Set<Integer>> getGroupingSetsIndexesInOutput() { Map<Expression, Integer> indexMap = indexesOfOutput(); List<Set<Integer>> groupingSetsIndex = Lists.newArrayList(); List<List<Expression>> groupingSets = getGroupingSets(); for (List<Expression> groupingSet : groupingSets) { // keep the index order Set<Integer> groupingSetIndex = Sets.newLinkedHashSet(); for (Expression expression : groupingSet) { Integer index = indexMap.get(expression); if (index == null) { throw new AnalysisException("Can not find grouping set expression in output: " + expression); } groupingSetIndex.add(index); } groupingSetsIndex.add(groupingSetIndex); } return groupingSetsIndex; } /** * indexesOfOutput: get the indexes which mapping from the expression to the index in the output. * * e.g. output=[a + 1, b + 2, c] * * return the map( * `a + 1`: 0, * `b + 2`: 1, * `c`: 2 * ) */ default Map<Expression, Integer> indexesOfOutput() { Map<Expression, Integer> indexes = Maps.newLinkedHashMap(); List<NamedExpression> outputs = getOutputExpressions(); for (int i = 0; i < outputs.size(); i++) { NamedExpression output = outputs.get(i); indexes.put(output, i); if (output instanceof Alias) { indexes.put(((Alias) output).child(), i); } } return indexes; } static String generateVirtualSlotName(GroupingScalarFunction function) { String colName = function.getArguments() .stream() .map(Expression::toSql) .collect(Collectors.joining("_")); return GROUPING_PREFIX + colName; } /** GroupingSetShapes */ class GroupingSetShapes { public final List<Expression> flattenGroupingSetExpression; public final List<GroupingSetShape> shapes; public GroupingSetShapes(Set<Expression> flattenGroupingSetExpression, List<GroupingSetShape> shapes) { this.flattenGroupingSetExpression = ImmutableList.copyOf(flattenGroupingSetExpression); this.shapes = ImmutableList.copyOf(shapes); } /**compute a long value that backend need to fill to the GROUPING_ID slot*/ public List<Long> computeVirtualGroupingIdValue() { Set<Long> res = Sets.newLinkedHashSet(); long k = (long) Math.pow(2, flattenGroupingSetExpression.size()); for (GroupingSetShape shape : shapes) { Long val = shape.computeLongValue(); while (res.contains(val)) { val += k; } res.add(val); } return ImmutableList.copyOf(res); } public int indexOf(Expression expression) { return flattenGroupingSetExpression.indexOf(expression); } @Override public String toString() { String exprs = StringUtils.join(flattenGroupingSetExpression, ", "); return "GroupingSetShapes(flattenGroupingSetExpression=" + exprs + ", shapes=" + shapes + ")"; } } /** * GroupingSetShape is used to compute which group column should be erased to null, * and as the computation source of grouping() / grouping_id() function. * * for example: this grouping sets will create 3 group sets * <pre> * select b, a * from tbl * group by * grouping sets * ( * (a, b) -- GroupingSetShape(shouldBeErasedToNull=[false, false]) * ( b) -- GroupingSetShape(shouldBeErasedToNull=[true, false]) * ( ) -- GroupingSetShape(shouldBeErasedToNull=[true, true]) * ) * </pre> */ class GroupingSetShape { List<Boolean> shouldBeErasedToNull; public GroupingSetShape(List<Boolean> shouldBeErasedToNull) { this.shouldBeErasedToNull = shouldBeErasedToNull; } public boolean shouldBeErasedToNull(int index) { return shouldBeErasedToNull.get(index); } /** * convert shouldBeErasedToNull to bits, combine the bits to long, * backend will set the column to null if the bit is 1. * * The compute method, e.g. * shouldBeErasedToNull = [false, true, true, true] means [0, 1, 1, 1], * we combine the bits of big endian to long value 7. * * The example in class comment: * grouping sets * ( * (a, b) -- [0, 0], to long value is 0 * ( b) -- [1, 0], to long value is 2 * ( ) -- [1, 1], to long value is 3 * ) */ public Long computeLongValue() { return BitUtils.bigEndianBitsToLong(shouldBeErasedToNull); } @Override public String toString() { String shouldBeErasedToNull = StringUtils.join(this.shouldBeErasedToNull, ", "); return "GroupingSetShape(shouldBeErasedToNull=" + shouldBeErasedToNull + ")"; } } }
apache/doris
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/algebra/Repeat.java
3,038
// keep the index order
line_comment
nl
// 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.doris.nereids.trees.plans.algebra; import org.apache.doris.nereids.exceptions.AnalysisException; import org.apache.doris.nereids.trees.expressions.Alias; import org.apache.doris.nereids.trees.expressions.Expression; import org.apache.doris.nereids.trees.expressions.NamedExpression; import org.apache.doris.nereids.trees.expressions.VirtualSlotReference; import org.apache.doris.nereids.trees.expressions.functions.scalar.GroupingScalarFunction; import org.apache.doris.nereids.trees.plans.Plan; import org.apache.doris.nereids.types.BigIntType; import org.apache.doris.nereids.util.BitUtils; import org.apache.doris.nereids.util.ExpressionUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.lang3.StringUtils; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * Common interface for logical/physical Repeat. */ public interface Repeat<CHILD_PLAN extends Plan> extends Aggregate<CHILD_PLAN> { String COL_GROUPING_ID = "GROUPING_ID"; String GROUPING_PREFIX = "GROUPING_PREFIX_"; List<List<Expression>> getGroupingSets(); List<NamedExpression> getOutputExpressions(); @Override default List<Expression> getGroupByExpressions() { return ExpressionUtils.flatExpressions(getGroupingSets()); } static VirtualSlotReference generateVirtualGroupingIdSlot() { return new VirtualSlotReference(COL_GROUPING_ID, BigIntType.INSTANCE, Optional.empty(), GroupingSetShapes::computeVirtualGroupingIdValue); } static VirtualSlotReference generateVirtualSlotByFunction(GroupingScalarFunction function) { return new VirtualSlotReference( generateVirtualSlotName(function), function.getDataType(), Optional.of(function), function::computeVirtualSlotValue); } /** * get common grouping set expressions. * e.g. grouping sets((a, b, c), (b, c), (c)) * the common expressions is [c] */ default Set<Expression> getCommonGroupingSetExpressions() { List<List<Expression>> groupingSets = getGroupingSets(); Iterator<List<Expression>> iterator = groupingSets.iterator(); Set<Expression> commonGroupingExpressions = Sets.newLinkedHashSet(iterator.next()); while (iterator.hasNext()) { commonGroupingExpressions = Sets.intersection(commonGroupingExpressions, Sets.newLinkedHashSet(iterator.next())); if (commonGroupingExpressions.isEmpty()) { break; } } return commonGroupingExpressions; } /** * getSortedVirtualSlots: order by virtual GROUPING_ID slot first. */ default Set<VirtualSlotReference> getSortedVirtualSlots() { Set<VirtualSlotReference> virtualSlots = ExpressionUtils.collect(getOutputExpressions(), VirtualSlotReference.class::isInstance); VirtualSlotReference virtualGroupingSetIdSlot = virtualSlots.stream() .filter(slot -> slot.getName().equals(COL_GROUPING_ID)) .findFirst() .get(); return ImmutableSet.<VirtualSlotReference>builder() .add(virtualGroupingSetIdSlot) .addAll(Sets.difference(virtualSlots, ImmutableSet.of(virtualGroupingSetIdSlot))) .build(); } /** * computeVirtualSlotValues. backend will fill this long value to the VirtualSlotRef */ default List<List<Long>> computeVirtualSlotValues(Set<VirtualSlotReference> sortedVirtualSlots) { GroupingSetShapes shapes = toShapes(); return sortedVirtualSlots.stream() .map(virtualSlot -> virtualSlot.getComputeLongValueMethod().apply(shapes)) .collect(ImmutableList.toImmutableList()); } /** * flatten the grouping sets and build to a GroupingSetShapes. */ default GroupingSetShapes toShapes() { Set<Expression> flattenGroupingSet = ImmutableSet.copyOf(ExpressionUtils.flatExpressions(getGroupingSets())); List<GroupingSetShape> shapes = Lists.newArrayList(); for (List<Expression> groupingSet : getGroupingSets()) { List<Boolean> shouldBeErasedToNull = Lists.newArrayListWithCapacity(flattenGroupingSet.size()); for (Expression groupingSetExpression : flattenGroupingSet) { shouldBeErasedToNull.add(!groupingSet.contains(groupingSetExpression)); } shapes.add(new GroupingSetShape(shouldBeErasedToNull)); } return new GroupingSetShapes(flattenGroupingSet, shapes); } /** * Generate repeat slot id list corresponding to SlotId according to the original grouping sets * and the actual SlotId. * * eg: groupingSets=((b, a), (a)), output=[a, b] * slotId in the outputTuple: [3, 4] * * return: [(4, 3), (3)] */ default List<Set<Integer>> computeRepeatSlotIdList(List<Integer> slotIdList) { List<Set<Integer>> groupingSetsIndexesInOutput = getGroupingSetsIndexesInOutput(); List<Set<Integer>> repeatSlotIdList = Lists.newArrayList(); for (Set<Integer> groupingSetIndex : groupingSetsIndexesInOutput) { // keep order Set<Integer> repeatSlotId = Sets.newLinkedHashSet(); for (Integer exprInOutputIndex : groupingSetIndex) { repeatSlotId.add(slotIdList.get(exprInOutputIndex)); } repeatSlotIdList.add(repeatSlotId); } return repeatSlotIdList; } /** * getGroupingSetsIndexesInOutput: find the location where the grouping output exists * * e.g. groupingSets=((b, a), (a)), output=[a, b] * return ((1, 0), (1)) */ default List<Set<Integer>> getGroupingSetsIndexesInOutput() { Map<Expression, Integer> indexMap = indexesOfOutput(); List<Set<Integer>> groupingSetsIndex = Lists.newArrayList(); List<List<Expression>> groupingSets = getGroupingSets(); for (List<Expression> groupingSet : groupingSets) { // keep the<SUF> Set<Integer> groupingSetIndex = Sets.newLinkedHashSet(); for (Expression expression : groupingSet) { Integer index = indexMap.get(expression); if (index == null) { throw new AnalysisException("Can not find grouping set expression in output: " + expression); } groupingSetIndex.add(index); } groupingSetsIndex.add(groupingSetIndex); } return groupingSetsIndex; } /** * indexesOfOutput: get the indexes which mapping from the expression to the index in the output. * * e.g. output=[a + 1, b + 2, c] * * return the map( * `a + 1`: 0, * `b + 2`: 1, * `c`: 2 * ) */ default Map<Expression, Integer> indexesOfOutput() { Map<Expression, Integer> indexes = Maps.newLinkedHashMap(); List<NamedExpression> outputs = getOutputExpressions(); for (int i = 0; i < outputs.size(); i++) { NamedExpression output = outputs.get(i); indexes.put(output, i); if (output instanceof Alias) { indexes.put(((Alias) output).child(), i); } } return indexes; } static String generateVirtualSlotName(GroupingScalarFunction function) { String colName = function.getArguments() .stream() .map(Expression::toSql) .collect(Collectors.joining("_")); return GROUPING_PREFIX + colName; } /** GroupingSetShapes */ class GroupingSetShapes { public final List<Expression> flattenGroupingSetExpression; public final List<GroupingSetShape> shapes; public GroupingSetShapes(Set<Expression> flattenGroupingSetExpression, List<GroupingSetShape> shapes) { this.flattenGroupingSetExpression = ImmutableList.copyOf(flattenGroupingSetExpression); this.shapes = ImmutableList.copyOf(shapes); } /**compute a long value that backend need to fill to the GROUPING_ID slot*/ public List<Long> computeVirtualGroupingIdValue() { Set<Long> res = Sets.newLinkedHashSet(); long k = (long) Math.pow(2, flattenGroupingSetExpression.size()); for (GroupingSetShape shape : shapes) { Long val = shape.computeLongValue(); while (res.contains(val)) { val += k; } res.add(val); } return ImmutableList.copyOf(res); } public int indexOf(Expression expression) { return flattenGroupingSetExpression.indexOf(expression); } @Override public String toString() { String exprs = StringUtils.join(flattenGroupingSetExpression, ", "); return "GroupingSetShapes(flattenGroupingSetExpression=" + exprs + ", shapes=" + shapes + ")"; } } /** * GroupingSetShape is used to compute which group column should be erased to null, * and as the computation source of grouping() / grouping_id() function. * * for example: this grouping sets will create 3 group sets * <pre> * select b, a * from tbl * group by * grouping sets * ( * (a, b) -- GroupingSetShape(shouldBeErasedToNull=[false, false]) * ( b) -- GroupingSetShape(shouldBeErasedToNull=[true, false]) * ( ) -- GroupingSetShape(shouldBeErasedToNull=[true, true]) * ) * </pre> */ class GroupingSetShape { List<Boolean> shouldBeErasedToNull; public GroupingSetShape(List<Boolean> shouldBeErasedToNull) { this.shouldBeErasedToNull = shouldBeErasedToNull; } public boolean shouldBeErasedToNull(int index) { return shouldBeErasedToNull.get(index); } /** * convert shouldBeErasedToNull to bits, combine the bits to long, * backend will set the column to null if the bit is 1. * * The compute method, e.g. * shouldBeErasedToNull = [false, true, true, true] means [0, 1, 1, 1], * we combine the bits of big endian to long value 7. * * The example in class comment: * grouping sets * ( * (a, b) -- [0, 0], to long value is 0 * ( b) -- [1, 0], to long value is 2 * ( ) -- [1, 1], to long value is 3 * ) */ public Long computeLongValue() { return BitUtils.bigEndianBitsToLong(shouldBeErasedToNull); } @Override public String toString() { String shouldBeErasedToNull = StringUtils.join(this.shouldBeErasedToNull, ", "); return "GroupingSetShape(shouldBeErasedToNull=" + shouldBeErasedToNull + ")"; } } }
201219_19
package com.etiennelawlor.quickreturn.activities; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.ServiceConnection; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import com.android.vending.billing.IInAppBillingService; import com.etiennelawlor.quickreturn.R; import com.etiennelawlor.quickreturn.library.utils.QuickReturnUtils; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import de.keyboardsurfer.android.widget.crouton.Configuration; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class QuickReturnBaseActivity extends AppCompatActivity { // region Constants // Server Response Codes (http://developer.android.com/google/play/billing/billing_reference.html) private static final int BILLING_RESPONSE_RESULT_OK = 0; private static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1; private static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3; private static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4; private static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5; private static final int BILLING_RESPONSE_RESULT_ERROR = 6; private static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7; private static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8; private static final int BUY_REQUEST_CODE = 4; private static final String ITEM_TYPE_INAPP = "inapp"; private static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; private static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE"; private static final String RESPONSE_CODE = "RESPONSE_CODE"; private static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST"; private static final String RESPONSE_BUY_INTENT = "BUY_INTENT"; private static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST"; private static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST"; private static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST"; private static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST"; private static final String RESPONSE_INAPP_PURCHASE_SIGNATURE_LIST = "INAPP_PURCHASE_SIGNATURE_LIST"; private static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN"; // endregion // region Member Variables private IInAppBillingService mService; private ServiceConnection mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IInAppBillingService.Stub.asInterface(service); } }; // endregion // region Lifecycle Methods @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); intent.setPackage("com.android.vending"); bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); if (mService != null) { unbindService(mServiceConn); } Crouton.cancelAllCroutons(); } // endregion @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BUY_REQUEST_CODE) { int responseCode; switch (resultCode) { case RESULT_OK: Log.d(getClass().getSimpleName(), "onActivityResult() : RESULT_OK"); responseCode = data.getIntExtra(RESPONSE_CODE, -5); switch (responseCode) { case BILLING_RESPONSE_RESULT_OK: String signature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE); String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA); JSONObject object; try { object = new JSONObject(purchaseData); // sample data // "purchaseToken" -> "inapp:com.etiennelawlor.quickreturn:android.test.purchased" // "developerPayload" -> "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzK" // "packageName" -> "com.etiennelawlor.quickreturn" // "purchaseState" -> "0" // "orderId" -> "transactionId.android.test.purchased" // "purchaseTime" -> "0" // "productId" -> "android.test.purchased" // String sku = object.getString("productId"); if (!TextUtils.isEmpty(sku)) { if (sku.equals(getString(R.string.buy_one_beer))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 1, 1)); } else if (sku.equals(getString(R.string.buy_two_beers))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 2, 2)); } else if (sku.equals(getString(R.string.buy_four_beers))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 4, 4)); } else if (sku.equals("android.test.purchased")) { showCrouton(android.R.color.holo_green_light, "Test Purchase completed"); } } } catch (JSONException e) { e.printStackTrace(); } // handle purchase here (for a permanent item like a premium upgrade, // this means dispensing the benefits of the upgrade; for a consumable // item like "X gold coins", typically the application would initiate // consumption of the purchase here) break; case BILLING_RESPONSE_RESULT_USER_CANCELED: Log.d(getClass().getSimpleName(), "donate() : User pressed back or canceled a dialog"); break; case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Billing API version is not supported for the type requested"); break; case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Requested product is not available for purchase"); break; case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR: Log.d(getClass().getSimpleName(), "donate() : Invalid arguments provided to the API. This error can also " + "indicate that the application was not correctly signed or properly set up for In-app Billing in " + "Google Play, or does not have the necessary permissions in its manifest"); break; case BILLING_RESPONSE_RESULT_ERROR: Log.d(getClass().getSimpleName(), "donate() : Fatal error during the API action"); break; case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to purchase since item is already owned"); showCrouton(android.R.color.holo_red_light, R.string.item_already_owned); break; case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to consume since item is not owned"); break; default: break; } break; case RESULT_CANCELED: Log.d(getClass().getSimpleName(), "onActivityResult() : RESULT_CANCELED"); // responseCode = data.getIntExtra(RESPONSE_CODE, -5); showCrouton(android.R.color.holo_red_light, R.string.beer_order_canceled); break; default: break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.quick_return, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case R.id.action_github: openWebPage("https://github.com/lawloretienne/QuickReturn"); return true; case R.id.buy_one_beer: donate(getString(R.string.buy_one_beer)); return true; case R.id.buy_two_beers: donate(getString(R.string.buy_two_beers)); return true; case R.id.buy_four_beers: donate(getString(R.string.buy_four_beers)); return true; default: break; } return super.onOptionsItemSelected(item); } // region Helper Methods private void openWebPage(String url) { Uri webpage = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, webpage); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } private void donate(String productSku) { try { // getAllSkus(); // getAllPurchases(); // consumePurchase(); String developerPayload = "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzK"; if (mService != null) { Bundle bundle = mService.getBuyIntent(3, getPackageName(), productSku, ITEM_TYPE_INAPP, developerPayload); // Test Item // Bundle bundle = mService.getBuyIntent(3, getPackageName(), // "android.test.purchased", ITEM_TYPE_INAPP, developerPayload); PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT); int responseCode = bundle.getInt(RESPONSE_CODE); switch (responseCode) { case BILLING_RESPONSE_RESULT_OK: startIntentSenderForResult(pendingIntent.getIntentSender(), BUY_REQUEST_CODE, new Intent(), 0, 0, 0); break; case BILLING_RESPONSE_RESULT_USER_CANCELED: Log.d(getClass().getSimpleName(), "donate() : User pressed back or canceled a dialog"); break; case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Billing API version is not supported for the type requested"); break; case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Requested product is not available for purchase"); break; case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR: Log.d(getClass().getSimpleName(), "donate() : Invalid arguments provided to the API. This error can also " + "indicate that the application was not correctly signed or properly set up for In-app Billing in " + "Google Play, or does not have the necessary permissions in its manifest"); break; case BILLING_RESPONSE_RESULT_ERROR: Log.d(getClass().getSimpleName(), "donate() : Fatal error during the API action"); break; case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to purchase since item is already owned"); showCrouton(android.R.color.holo_red_light, R.string.item_already_owned); break; case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to consume since item is not owned"); break; default: break; } } } catch (RemoteException e) { e.printStackTrace(); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); } } private void consumePurchase() { // "purchaseToken": "inapp:com.etiennelawlor.quickreturn:android.test.purchased" String token = "inapp:com.etiennelawlor.quickreturn:android.test.purchased"; try { int response = mService.consumePurchase(3, getPackageName(), token); Log.d(getClass().getSimpleName(), "consumePurchase() : response - " + response); } catch (RemoteException e) { e.printStackTrace(); } } private void getAllSkus() { ArrayList<String> skuList = new ArrayList<>(); skuList.add("buy_one_beer"); skuList.add("buy_two_beers"); skuList.add("buy_four_beers"); Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList); try { Bundle skuDetails = mService.getSkuDetails(3, getPackageName(), ITEM_TYPE_INAPP, querySkus); int response = skuDetails.getInt(RESPONSE_CODE); if (response == BILLING_RESPONSE_RESULT_OK) { ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { JSONObject object; try { object = new JSONObject(thisResponse); String sku = object.getString("productId"); String price = object.getString("price"); if (sku.equals(getString(R.string.buy_one_beer))) { Log.d(getClass().getSimpleName(), "price - " + price); // mPremiumUpgradePrice = price; } else if (sku.equals(getString(R.string.buy_two_beers))) { Log.d(getClass().getSimpleName(), "price - " + price); // mGasPrice = price; } else if (sku.equals(getString(R.string.buy_four_beers))) { Log.d(getClass().getSimpleName(), "price - " + price); // mGasPrice = price; } } catch (JSONException e) { e.printStackTrace(); } } } } catch (RemoteException e) { e.printStackTrace(); } } private void getAllPurchases() { try { Bundle purchases = mService.getPurchases(3, getPackageName(), ITEM_TYPE_INAPP, INAPP_CONTINUATION_TOKEN); if (purchases.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) { ArrayList mySkus, myPurchases, mySignatures; mySkus = purchases.getStringArrayList(RESPONSE_INAPP_ITEM_LIST); myPurchases = purchases.getStringArrayList(RESPONSE_INAPP_PURCHASE_DATA_LIST); mySignatures = purchases.getStringArrayList(RESPONSE_INAPP_PURCHASE_SIGNATURE_LIST); Log.d(getClass().getSimpleName(), "getAllPurchases() : purchases"); // handle items here } } catch (RemoteException e) { e.printStackTrace(); } } private void showCrouton(int colorRes, int messageRes) { Style croutonStyle = new Style.Builder() .setHeight(QuickReturnUtils.dp2px(this, 50)) // .setTextColor(getResources().getColor(R.color.white)) .setGravity(Gravity.CENTER) .setBackgroundColor(colorRes) .build(); Crouton.makeText(this, messageRes, croutonStyle) .setConfiguration(new Configuration.Builder() .setDuration(Configuration.DURATION_SHORT) .setInAnimation(R.anim.crouton_in_delayed) .setOutAnimation(R.anim.crouton_out) .build()) .show(); } private void showCrouton(int colorRes, String message) { Style croutonStyle = new Style.Builder() .setHeight(QuickReturnUtils.dp2px(this, 50)) // .setTextColor(getResources().getColor(R.color.white)) .setGravity(Gravity.CENTER) .setBackgroundColor(colorRes) .build(); Crouton.makeText(this, message, croutonStyle) .setConfiguration(new Configuration.Builder() .setDuration(Configuration.DURATION_SHORT) .setInAnimation(R.anim.crouton_in_delayed) .setOutAnimation(R.anim.crouton_out) .build()) .show(); } // endregion }
lawloretienne/QuickReturn
sample/src/main/java/com/etiennelawlor/quickreturn/activities/QuickReturnBaseActivity.java
4,306
// region Helper Methods
line_comment
nl
package com.etiennelawlor.quickreturn.activities; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.ServiceConnection; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import com.android.vending.billing.IInAppBillingService; import com.etiennelawlor.quickreturn.R; import com.etiennelawlor.quickreturn.library.utils.QuickReturnUtils; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import de.keyboardsurfer.android.widget.crouton.Configuration; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; public class QuickReturnBaseActivity extends AppCompatActivity { // region Constants // Server Response Codes (http://developer.android.com/google/play/billing/billing_reference.html) private static final int BILLING_RESPONSE_RESULT_OK = 0; private static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1; private static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3; private static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4; private static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5; private static final int BILLING_RESPONSE_RESULT_ERROR = 6; private static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7; private static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8; private static final int BUY_REQUEST_CODE = 4; private static final String ITEM_TYPE_INAPP = "inapp"; private static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; private static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE"; private static final String RESPONSE_CODE = "RESPONSE_CODE"; private static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST"; private static final String RESPONSE_BUY_INTENT = "BUY_INTENT"; private static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST"; private static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST"; private static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST"; private static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST"; private static final String RESPONSE_INAPP_PURCHASE_SIGNATURE_LIST = "INAPP_PURCHASE_SIGNATURE_LIST"; private static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN"; // endregion // region Member Variables private IInAppBillingService mService; private ServiceConnection mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IInAppBillingService.Stub.asInterface(service); } }; // endregion // region Lifecycle Methods @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); intent.setPackage("com.android.vending"); bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); if (mService != null) { unbindService(mServiceConn); } Crouton.cancelAllCroutons(); } // endregion @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BUY_REQUEST_CODE) { int responseCode; switch (resultCode) { case RESULT_OK: Log.d(getClass().getSimpleName(), "onActivityResult() : RESULT_OK"); responseCode = data.getIntExtra(RESPONSE_CODE, -5); switch (responseCode) { case BILLING_RESPONSE_RESULT_OK: String signature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE); String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA); JSONObject object; try { object = new JSONObject(purchaseData); // sample data // "purchaseToken" -> "inapp:com.etiennelawlor.quickreturn:android.test.purchased" // "developerPayload" -> "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzK" // "packageName" -> "com.etiennelawlor.quickreturn" // "purchaseState" -> "0" // "orderId" -> "transactionId.android.test.purchased" // "purchaseTime" -> "0" // "productId" -> "android.test.purchased" // String sku = object.getString("productId"); if (!TextUtils.isEmpty(sku)) { if (sku.equals(getString(R.string.buy_one_beer))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 1, 1)); } else if (sku.equals(getString(R.string.buy_two_beers))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 2, 2)); } else if (sku.equals(getString(R.string.buy_four_beers))) { showCrouton(android.R.color.holo_green_light, getResources().getQuantityString(R.plurals.beer_cheers, 4, 4)); } else if (sku.equals("android.test.purchased")) { showCrouton(android.R.color.holo_green_light, "Test Purchase completed"); } } } catch (JSONException e) { e.printStackTrace(); } // handle purchase here (for a permanent item like a premium upgrade, // this means dispensing the benefits of the upgrade; for a consumable // item like "X gold coins", typically the application would initiate // consumption of the purchase here) break; case BILLING_RESPONSE_RESULT_USER_CANCELED: Log.d(getClass().getSimpleName(), "donate() : User pressed back or canceled a dialog"); break; case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Billing API version is not supported for the type requested"); break; case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Requested product is not available for purchase"); break; case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR: Log.d(getClass().getSimpleName(), "donate() : Invalid arguments provided to the API. This error can also " + "indicate that the application was not correctly signed or properly set up for In-app Billing in " + "Google Play, or does not have the necessary permissions in its manifest"); break; case BILLING_RESPONSE_RESULT_ERROR: Log.d(getClass().getSimpleName(), "donate() : Fatal error during the API action"); break; case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to purchase since item is already owned"); showCrouton(android.R.color.holo_red_light, R.string.item_already_owned); break; case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to consume since item is not owned"); break; default: break; } break; case RESULT_CANCELED: Log.d(getClass().getSimpleName(), "onActivityResult() : RESULT_CANCELED"); // responseCode = data.getIntExtra(RESPONSE_CODE, -5); showCrouton(android.R.color.holo_red_light, R.string.beer_order_canceled); break; default: break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.quick_return, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch (id) { case R.id.action_github: openWebPage("https://github.com/lawloretienne/QuickReturn"); return true; case R.id.buy_one_beer: donate(getString(R.string.buy_one_beer)); return true; case R.id.buy_two_beers: donate(getString(R.string.buy_two_beers)); return true; case R.id.buy_four_beers: donate(getString(R.string.buy_four_beers)); return true; default: break; } return super.onOptionsItemSelected(item); } // region Helper<SUF> private void openWebPage(String url) { Uri webpage = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, webpage); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } private void donate(String productSku) { try { // getAllSkus(); // getAllPurchases(); // consumePurchase(); String developerPayload = "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzK"; if (mService != null) { Bundle bundle = mService.getBuyIntent(3, getPackageName(), productSku, ITEM_TYPE_INAPP, developerPayload); // Test Item // Bundle bundle = mService.getBuyIntent(3, getPackageName(), // "android.test.purchased", ITEM_TYPE_INAPP, developerPayload); PendingIntent pendingIntent = bundle.getParcelable(RESPONSE_BUY_INTENT); int responseCode = bundle.getInt(RESPONSE_CODE); switch (responseCode) { case BILLING_RESPONSE_RESULT_OK: startIntentSenderForResult(pendingIntent.getIntentSender(), BUY_REQUEST_CODE, new Intent(), 0, 0, 0); break; case BILLING_RESPONSE_RESULT_USER_CANCELED: Log.d(getClass().getSimpleName(), "donate() : User pressed back or canceled a dialog"); break; case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Billing API version is not supported for the type requested"); break; case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE: Log.d(getClass().getSimpleName(), "donate() : Requested product is not available for purchase"); break; case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR: Log.d(getClass().getSimpleName(), "donate() : Invalid arguments provided to the API. This error can also " + "indicate that the application was not correctly signed or properly set up for In-app Billing in " + "Google Play, or does not have the necessary permissions in its manifest"); break; case BILLING_RESPONSE_RESULT_ERROR: Log.d(getClass().getSimpleName(), "donate() : Fatal error during the API action"); break; case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to purchase since item is already owned"); showCrouton(android.R.color.holo_red_light, R.string.item_already_owned); break; case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED: Log.d(getClass().getSimpleName(), "donate() : Failure to consume since item is not owned"); break; default: break; } } } catch (RemoteException e) { e.printStackTrace(); } catch (IntentSender.SendIntentException e) { e.printStackTrace(); } } private void consumePurchase() { // "purchaseToken": "inapp:com.etiennelawlor.quickreturn:android.test.purchased" String token = "inapp:com.etiennelawlor.quickreturn:android.test.purchased"; try { int response = mService.consumePurchase(3, getPackageName(), token); Log.d(getClass().getSimpleName(), "consumePurchase() : response - " + response); } catch (RemoteException e) { e.printStackTrace(); } } private void getAllSkus() { ArrayList<String> skuList = new ArrayList<>(); skuList.add("buy_one_beer"); skuList.add("buy_two_beers"); skuList.add("buy_four_beers"); Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList); try { Bundle skuDetails = mService.getSkuDetails(3, getPackageName(), ITEM_TYPE_INAPP, querySkus); int response = skuDetails.getInt(RESPONSE_CODE); if (response == BILLING_RESPONSE_RESULT_OK) { ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { JSONObject object; try { object = new JSONObject(thisResponse); String sku = object.getString("productId"); String price = object.getString("price"); if (sku.equals(getString(R.string.buy_one_beer))) { Log.d(getClass().getSimpleName(), "price - " + price); // mPremiumUpgradePrice = price; } else if (sku.equals(getString(R.string.buy_two_beers))) { Log.d(getClass().getSimpleName(), "price - " + price); // mGasPrice = price; } else if (sku.equals(getString(R.string.buy_four_beers))) { Log.d(getClass().getSimpleName(), "price - " + price); // mGasPrice = price; } } catch (JSONException e) { e.printStackTrace(); } } } } catch (RemoteException e) { e.printStackTrace(); } } private void getAllPurchases() { try { Bundle purchases = mService.getPurchases(3, getPackageName(), ITEM_TYPE_INAPP, INAPP_CONTINUATION_TOKEN); if (purchases.getInt(RESPONSE_CODE) == BILLING_RESPONSE_RESULT_OK) { ArrayList mySkus, myPurchases, mySignatures; mySkus = purchases.getStringArrayList(RESPONSE_INAPP_ITEM_LIST); myPurchases = purchases.getStringArrayList(RESPONSE_INAPP_PURCHASE_DATA_LIST); mySignatures = purchases.getStringArrayList(RESPONSE_INAPP_PURCHASE_SIGNATURE_LIST); Log.d(getClass().getSimpleName(), "getAllPurchases() : purchases"); // handle items here } } catch (RemoteException e) { e.printStackTrace(); } } private void showCrouton(int colorRes, int messageRes) { Style croutonStyle = new Style.Builder() .setHeight(QuickReturnUtils.dp2px(this, 50)) // .setTextColor(getResources().getColor(R.color.white)) .setGravity(Gravity.CENTER) .setBackgroundColor(colorRes) .build(); Crouton.makeText(this, messageRes, croutonStyle) .setConfiguration(new Configuration.Builder() .setDuration(Configuration.DURATION_SHORT) .setInAnimation(R.anim.crouton_in_delayed) .setOutAnimation(R.anim.crouton_out) .build()) .show(); } private void showCrouton(int colorRes, String message) { Style croutonStyle = new Style.Builder() .setHeight(QuickReturnUtils.dp2px(this, 50)) // .setTextColor(getResources().getColor(R.color.white)) .setGravity(Gravity.CENTER) .setBackgroundColor(colorRes) .build(); Crouton.makeText(this, message, croutonStyle) .setConfiguration(new Configuration.Builder() .setDuration(Configuration.DURATION_SHORT) .setInAnimation(R.anim.crouton_in_delayed) .setOutAnimation(R.anim.crouton_out) .build()) .show(); } // endregion }
201234_0
package observer.model; import java.util.Observable; // Deze klasse wordt geobserveerd! public class Croque extends Observable { private static final int BASIS_PRIJS = 200; private static final int KAAS_PRIJS = 50; private static final int HAM_PRIJS = 60; private static final int ANANAS_PRIJS = 30; private boolean metKaas = false; private boolean metHam = false; private boolean metAnanas = false; private String betaalWijze = "Contant"; public String getBetaalWijze() { return betaalWijze; } public void setBetaalWijze(String wijze) { betaalWijze = wijze; setChanged(); notifyObservers(); } public void setMetKaas(boolean kaas) { metKaas = kaas; setChanged(); notifyObservers(); } public void setMetHam(boolean ham) { metHam = ham; setChanged(); notifyObservers(); } public void setMetAnanas(boolean ananas) { metAnanas = ananas; setChanged(); notifyObservers(); } public String teBetalen() { int teBetalen = BASIS_PRIJS; if (metKaas) { teBetalen += KAAS_PRIJS; } if (metHam) { teBetalen += HAM_PRIJS; } if (metAnanas) { teBetalen += ANANAS_PRIJS; } return Double.toString((double) teBetalen / 100); } }
AdriVanHoudt/School
KdG12-13/Java/Oef/Week3.MVC_Observer_Opdracht/src/observer/model/Croque.java
407
// Deze klasse wordt geobserveerd!
line_comment
nl
package observer.model; import java.util.Observable; // Deze klasse<SUF> public class Croque extends Observable { private static final int BASIS_PRIJS = 200; private static final int KAAS_PRIJS = 50; private static final int HAM_PRIJS = 60; private static final int ANANAS_PRIJS = 30; private boolean metKaas = false; private boolean metHam = false; private boolean metAnanas = false; private String betaalWijze = "Contant"; public String getBetaalWijze() { return betaalWijze; } public void setBetaalWijze(String wijze) { betaalWijze = wijze; setChanged(); notifyObservers(); } public void setMetKaas(boolean kaas) { metKaas = kaas; setChanged(); notifyObservers(); } public void setMetHam(boolean ham) { metHam = ham; setChanged(); notifyObservers(); } public void setMetAnanas(boolean ananas) { metAnanas = ananas; setChanged(); notifyObservers(); } public String teBetalen() { int teBetalen = BASIS_PRIJS; if (metKaas) { teBetalen += KAAS_PRIJS; } if (metHam) { teBetalen += HAM_PRIJS; } if (metAnanas) { teBetalen += ANANAS_PRIJS; } return Double.toString((double) teBetalen / 100); } }
201241_1
package yolo; public abstract class Betaalwijze { protected double saldo; /** * Methode om krediet te initialiseren * @param saldo */ public void setSaldo(double saldo) { this.saldo = saldo; } /** * Methode om betaling af te handelen * * @param tebetalen * @return Boolean om te kijken of er voldoende saldo is */ public abstract void betaal(double tebetalen) throws TeWeinigGeldException; }
reneoun/KantineUnit
src/main/java/yolo/Betaalwijze.java
126
/** * Methode om betaling af te handelen * * @param tebetalen * @return Boolean om te kijken of er voldoende saldo is */
block_comment
nl
package yolo; public abstract class Betaalwijze { protected double saldo; /** * Methode om krediet te initialiseren * @param saldo */ public void setSaldo(double saldo) { this.saldo = saldo; } /** * Methode om betaling<SUF>*/ public abstract void betaal(double tebetalen) throws TeWeinigGeldException; }
201246_0
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.openapitools.client.model.Waardelijst; /** * Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze) */ @ApiModel(description = "Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze)") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class LocatieKadastraalObject { public static final String SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE = "nummeraanduidingIdentificatie"; @SerializedName(SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE) private String nummeraanduidingIdentificatie; public static final String SERIALIZED_NAME_KOPPELINGSWIJZE = "koppelingswijze"; @SerializedName(SERIALIZED_NAME_KOPPELINGSWIJZE) private Waardelijst koppelingswijze; public LocatieKadastraalObject nummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; return this; } /** * Get nummeraanduidingIdentificatie * @return nummeraanduidingIdentificatie **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getNummeraanduidingIdentificatie() { return nummeraanduidingIdentificatie; } public void setNummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; } public LocatieKadastraalObject koppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; return this; } /** * Get koppelingswijze * @return koppelingswijze **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Waardelijst getKoppelingswijze() { return koppelingswijze; } public void setKoppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocatieKadastraalObject locatieKadastraalObject = (LocatieKadastraalObject) o; return Objects.equals(this.nummeraanduidingIdentificatie, locatieKadastraalObject.nummeraanduidingIdentificatie) && Objects.equals(this.koppelingswijze, locatieKadastraalObject.koppelingswijze); } @Override public int hashCode() { return Objects.hash(nummeraanduidingIdentificatie, koppelingswijze); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LocatieKadastraalObject {\n"); sb.append(" nummeraanduidingIdentificatie: ").append(toIndentedString(nummeraanduidingIdentificatie)).append("\n"); sb.append(" koppelingswijze: ").append(toIndentedString(koppelingswijze)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
kad-henger/Haal-Centraal-BRK-bevragen
code/java/src/main/java/org/openapitools/client/model/LocatieKadastraalObject.java
1,222
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */
block_comment
nl
/* * Kadaster - BRK-Bevragen<SUF>*/ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.openapitools.client.model.Waardelijst; /** * Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze) */ @ApiModel(description = "Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze)") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class LocatieKadastraalObject { public static final String SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE = "nummeraanduidingIdentificatie"; @SerializedName(SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE) private String nummeraanduidingIdentificatie; public static final String SERIALIZED_NAME_KOPPELINGSWIJZE = "koppelingswijze"; @SerializedName(SERIALIZED_NAME_KOPPELINGSWIJZE) private Waardelijst koppelingswijze; public LocatieKadastraalObject nummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; return this; } /** * Get nummeraanduidingIdentificatie * @return nummeraanduidingIdentificatie **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getNummeraanduidingIdentificatie() { return nummeraanduidingIdentificatie; } public void setNummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; } public LocatieKadastraalObject koppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; return this; } /** * Get koppelingswijze * @return koppelingswijze **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Waardelijst getKoppelingswijze() { return koppelingswijze; } public void setKoppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocatieKadastraalObject locatieKadastraalObject = (LocatieKadastraalObject) o; return Objects.equals(this.nummeraanduidingIdentificatie, locatieKadastraalObject.nummeraanduidingIdentificatie) && Objects.equals(this.koppelingswijze, locatieKadastraalObject.koppelingswijze); } @Override public int hashCode() { return Objects.hash(nummeraanduidingIdentificatie, koppelingswijze); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LocatieKadastraalObject {\n"); sb.append(" nummeraanduidingIdentificatie: ").append(toIndentedString(nummeraanduidingIdentificatie)).append("\n"); sb.append(" koppelingswijze: ").append(toIndentedString(koppelingswijze)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
201246_1
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.openapitools.client.model.Waardelijst; /** * Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze) */ @ApiModel(description = "Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze)") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class LocatieKadastraalObject { public static final String SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE = "nummeraanduidingIdentificatie"; @SerializedName(SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE) private String nummeraanduidingIdentificatie; public static final String SERIALIZED_NAME_KOPPELINGSWIJZE = "koppelingswijze"; @SerializedName(SERIALIZED_NAME_KOPPELINGSWIJZE) private Waardelijst koppelingswijze; public LocatieKadastraalObject nummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; return this; } /** * Get nummeraanduidingIdentificatie * @return nummeraanduidingIdentificatie **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getNummeraanduidingIdentificatie() { return nummeraanduidingIdentificatie; } public void setNummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; } public LocatieKadastraalObject koppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; return this; } /** * Get koppelingswijze * @return koppelingswijze **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Waardelijst getKoppelingswijze() { return koppelingswijze; } public void setKoppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocatieKadastraalObject locatieKadastraalObject = (LocatieKadastraalObject) o; return Objects.equals(this.nummeraanduidingIdentificatie, locatieKadastraalObject.nummeraanduidingIdentificatie) && Objects.equals(this.koppelingswijze, locatieKadastraalObject.koppelingswijze); } @Override public int hashCode() { return Objects.hash(nummeraanduidingIdentificatie, koppelingswijze); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LocatieKadastraalObject {\n"); sb.append(" nummeraanduidingIdentificatie: ").append(toIndentedString(nummeraanduidingIdentificatie)).append("\n"); sb.append(" koppelingswijze: ").append(toIndentedString(koppelingswijze)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
kad-henger/Haal-Centraal-BRK-bevragen
code/java/src/main/java/org/openapitools/client/model/LocatieKadastraalObject.java
1,222
/** * Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze) */
block_comment
nl
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.openapitools.client.model.Waardelijst; /** * Waardelijst in deze<SUF>*/ @ApiModel(description = "Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze)") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class LocatieKadastraalObject { public static final String SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE = "nummeraanduidingIdentificatie"; @SerializedName(SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE) private String nummeraanduidingIdentificatie; public static final String SERIALIZED_NAME_KOPPELINGSWIJZE = "koppelingswijze"; @SerializedName(SERIALIZED_NAME_KOPPELINGSWIJZE) private Waardelijst koppelingswijze; public LocatieKadastraalObject nummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; return this; } /** * Get nummeraanduidingIdentificatie * @return nummeraanduidingIdentificatie **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getNummeraanduidingIdentificatie() { return nummeraanduidingIdentificatie; } public void setNummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; } public LocatieKadastraalObject koppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; return this; } /** * Get koppelingswijze * @return koppelingswijze **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Waardelijst getKoppelingswijze() { return koppelingswijze; } public void setKoppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocatieKadastraalObject locatieKadastraalObject = (LocatieKadastraalObject) o; return Objects.equals(this.nummeraanduidingIdentificatie, locatieKadastraalObject.nummeraanduidingIdentificatie) && Objects.equals(this.koppelingswijze, locatieKadastraalObject.koppelingswijze); } @Override public int hashCode() { return Objects.hash(nummeraanduidingIdentificatie, koppelingswijze); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LocatieKadastraalObject {\n"); sb.append(" nummeraanduidingIdentificatie: ").append(toIndentedString(nummeraanduidingIdentificatie)).append("\n"); sb.append(" koppelingswijze: ").append(toIndentedString(koppelingswijze)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
201246_2
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.openapitools.client.model.Waardelijst; /** * Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze) */ @ApiModel(description = "Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze)") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class LocatieKadastraalObject { public static final String SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE = "nummeraanduidingIdentificatie"; @SerializedName(SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE) private String nummeraanduidingIdentificatie; public static final String SERIALIZED_NAME_KOPPELINGSWIJZE = "koppelingswijze"; @SerializedName(SERIALIZED_NAME_KOPPELINGSWIJZE) private Waardelijst koppelingswijze; public LocatieKadastraalObject nummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; return this; } /** * Get nummeraanduidingIdentificatie * @return nummeraanduidingIdentificatie **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getNummeraanduidingIdentificatie() { return nummeraanduidingIdentificatie; } public void setNummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; } public LocatieKadastraalObject koppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; return this; } /** * Get koppelingswijze * @return koppelingswijze **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Waardelijst getKoppelingswijze() { return koppelingswijze; } public void setKoppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocatieKadastraalObject locatieKadastraalObject = (LocatieKadastraalObject) o; return Objects.equals(this.nummeraanduidingIdentificatie, locatieKadastraalObject.nummeraanduidingIdentificatie) && Objects.equals(this.koppelingswijze, locatieKadastraalObject.koppelingswijze); } @Override public int hashCode() { return Objects.hash(nummeraanduidingIdentificatie, koppelingswijze); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LocatieKadastraalObject {\n"); sb.append(" nummeraanduidingIdentificatie: ").append(toIndentedString(nummeraanduidingIdentificatie)).append("\n"); sb.append(" koppelingswijze: ").append(toIndentedString(koppelingswijze)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
kad-henger/Haal-Centraal-BRK-bevragen
code/java/src/main/java/org/openapitools/client/model/LocatieKadastraalObject.java
1,222
/** * Get nummeraanduidingIdentificatie * @return nummeraanduidingIdentificatie **/
block_comment
nl
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.openapitools.client.model.Waardelijst; /** * Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze) */ @ApiModel(description = "Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze)") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class LocatieKadastraalObject { public static final String SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE = "nummeraanduidingIdentificatie"; @SerializedName(SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE) private String nummeraanduidingIdentificatie; public static final String SERIALIZED_NAME_KOPPELINGSWIJZE = "koppelingswijze"; @SerializedName(SERIALIZED_NAME_KOPPELINGSWIJZE) private Waardelijst koppelingswijze; public LocatieKadastraalObject nummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; return this; } /** * Get nummeraanduidingIdentificatie <SUF>*/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getNummeraanduidingIdentificatie() { return nummeraanduidingIdentificatie; } public void setNummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; } public LocatieKadastraalObject koppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; return this; } /** * Get koppelingswijze * @return koppelingswijze **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Waardelijst getKoppelingswijze() { return koppelingswijze; } public void setKoppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocatieKadastraalObject locatieKadastraalObject = (LocatieKadastraalObject) o; return Objects.equals(this.nummeraanduidingIdentificatie, locatieKadastraalObject.nummeraanduidingIdentificatie) && Objects.equals(this.koppelingswijze, locatieKadastraalObject.koppelingswijze); } @Override public int hashCode() { return Objects.hash(nummeraanduidingIdentificatie, koppelingswijze); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LocatieKadastraalObject {\n"); sb.append(" nummeraanduidingIdentificatie: ").append(toIndentedString(nummeraanduidingIdentificatie)).append("\n"); sb.append(" koppelingswijze: ").append(toIndentedString(koppelingswijze)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
201246_3
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.openapitools.client.model.Waardelijst; /** * Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze) */ @ApiModel(description = "Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze)") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class LocatieKadastraalObject { public static final String SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE = "nummeraanduidingIdentificatie"; @SerializedName(SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE) private String nummeraanduidingIdentificatie; public static final String SERIALIZED_NAME_KOPPELINGSWIJZE = "koppelingswijze"; @SerializedName(SERIALIZED_NAME_KOPPELINGSWIJZE) private Waardelijst koppelingswijze; public LocatieKadastraalObject nummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; return this; } /** * Get nummeraanduidingIdentificatie * @return nummeraanduidingIdentificatie **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getNummeraanduidingIdentificatie() { return nummeraanduidingIdentificatie; } public void setNummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; } public LocatieKadastraalObject koppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; return this; } /** * Get koppelingswijze * @return koppelingswijze **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Waardelijst getKoppelingswijze() { return koppelingswijze; } public void setKoppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocatieKadastraalObject locatieKadastraalObject = (LocatieKadastraalObject) o; return Objects.equals(this.nummeraanduidingIdentificatie, locatieKadastraalObject.nummeraanduidingIdentificatie) && Objects.equals(this.koppelingswijze, locatieKadastraalObject.koppelingswijze); } @Override public int hashCode() { return Objects.hash(nummeraanduidingIdentificatie, koppelingswijze); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LocatieKadastraalObject {\n"); sb.append(" nummeraanduidingIdentificatie: ").append(toIndentedString(nummeraanduidingIdentificatie)).append("\n"); sb.append(" koppelingswijze: ").append(toIndentedString(koppelingswijze)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
kad-henger/Haal-Centraal-BRK-bevragen
code/java/src/main/java/org/openapitools/client/model/LocatieKadastraalObject.java
1,222
/** * Get koppelingswijze * @return koppelingswijze **/
block_comment
nl
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import org.openapitools.client.model.Waardelijst; /** * Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze) */ @ApiModel(description = "Waardelijst in deze component : [koppelingswijze](http://www.kadaster.nl/schemas/waardelijsten/Koppelingswijze)") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class LocatieKadastraalObject { public static final String SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE = "nummeraanduidingIdentificatie"; @SerializedName(SERIALIZED_NAME_NUMMERAANDUIDING_IDENTIFICATIE) private String nummeraanduidingIdentificatie; public static final String SERIALIZED_NAME_KOPPELINGSWIJZE = "koppelingswijze"; @SerializedName(SERIALIZED_NAME_KOPPELINGSWIJZE) private Waardelijst koppelingswijze; public LocatieKadastraalObject nummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; return this; } /** * Get nummeraanduidingIdentificatie * @return nummeraanduidingIdentificatie **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public String getNummeraanduidingIdentificatie() { return nummeraanduidingIdentificatie; } public void setNummeraanduidingIdentificatie(String nummeraanduidingIdentificatie) { this.nummeraanduidingIdentificatie = nummeraanduidingIdentificatie; } public LocatieKadastraalObject koppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; return this; } /** * Get koppelingswijze <SUF>*/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Waardelijst getKoppelingswijze() { return koppelingswijze; } public void setKoppelingswijze(Waardelijst koppelingswijze) { this.koppelingswijze = koppelingswijze; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocatieKadastraalObject locatieKadastraalObject = (LocatieKadastraalObject) o; return Objects.equals(this.nummeraanduidingIdentificatie, locatieKadastraalObject.nummeraanduidingIdentificatie) && Objects.equals(this.koppelingswijze, locatieKadastraalObject.koppelingswijze); } @Override public int hashCode() { return Objects.hash(nummeraanduidingIdentificatie, koppelingswijze); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LocatieKadastraalObject {\n"); sb.append(" nummeraanduidingIdentificatie: ").append(toIndentedString(nummeraanduidingIdentificatie)).append("\n"); sb.append(" koppelingswijze: ").append(toIndentedString(koppelingswijze)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
201261_1
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.system; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.StockPlayDAO; import com.kapti.data.persistence.StockPlayDAOFactory; import com.kapti.exceptions.StockPlayException; import java.util.HashMap; /** * \brief Handler van de System.Database subklasse. * * Deze klasse is de handler van de System.Database subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class DatabaseHandler extends MethodClass { // // Methodes // public int Status() throws StockPlayException { StockPlayDAO tDAO = StockPlayDAOFactory.getDAO(); if (tDAO.testConnection()) return 1; else return 0; } public HashMap<String, Object> Stats() throws StockPlayException { HashMap<String, Object> oStats = new HashMap<String, Object>(); oStats.put("rate", getDAO().getRate()); oStats.put("uptime", Long.toString(getDAO().getUptime())); return oStats; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/system/DatabaseHandler.java
499
/** * \brief Handler van de System.Database subklasse. * * Deze klasse is de handler van de System.Database subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */
block_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.system; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.StockPlayDAO; import com.kapti.data.persistence.StockPlayDAOFactory; import com.kapti.exceptions.StockPlayException; import java.util.HashMap; /** * \brief <SUF>*/ public class DatabaseHandler extends MethodClass { // // Methodes // public int Status() throws StockPlayException { StockPlayDAO tDAO = StockPlayDAOFactory.getDAO(); if (tDAO.testConnection()) return 1; else return 0; } public HashMap<String, Object> Stats() throws StockPlayException { HashMap<String, Object> oStats = new HashMap<String, Object>(); oStats.put("rate", getDAO().getRate()); oStats.put("uptime", Long.toString(getDAO().getUptime())); return oStats; } }
201277_1
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.user; import com.kapti.backend.api.MethodClass; import com.kapti.data.UserSecurity; import com.kapti.data.UserSecurity.UserSecurityPK; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import com.kapti.filter.relation.RelationAnd; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief Handler van de User.Portfolio subklasse. * * Deze klasse is de handler van de User.Portfolio subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class PortfolioHandler extends MethodClass { // // Methodes // public Vector<HashMap<String, Object>> List() throws StockPlayException { return List("userid == '" + getUser().getId() + "'i"); } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.UserSecurity, UserSecurityPK> tUserSecurityDAO = getDAO().getUserSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isBackendAdmin()) { // TODO: isOrderAdmin filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, user); } else { filter = user; } } // Fetch and convert all Indexs Collection<UserSecurity> tUserSecurities = tUserSecurityDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.UserSecurity tUserSecurity : tUserSecurities) { oVector.add(tUserSecurity.toStruct( com.kapti.data.UserSecurity.Fields.AMOUNT, com.kapti.data.UserSecurity.Fields.ISIN, com.kapti.data.UserSecurity.Fields.USER)); } return oVector; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.UserSecurity, UserSecurityPK> tUserSecurityDAO = getDAO().getUserSecurityDAO(); // Instantiate a new exchange UserSecurity tUserSecurity = UserSecurity.fromStruct(iDetails); tUserSecurity.applyStruct(iDetails); tUserSecurityDAO.create(tUserSecurity); return 1; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/user/PortfolioHandler.java
922
/** * \brief Handler van de User.Portfolio subklasse. * * Deze klasse is de handler van de User.Portfolio subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */
block_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.user; import com.kapti.backend.api.MethodClass; import com.kapti.data.UserSecurity; import com.kapti.data.UserSecurity.UserSecurityPK; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import com.kapti.filter.relation.RelationAnd; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief <SUF>*/ public class PortfolioHandler extends MethodClass { // // Methodes // public Vector<HashMap<String, Object>> List() throws StockPlayException { return List("userid == '" + getUser().getId() + "'i"); } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.UserSecurity, UserSecurityPK> tUserSecurityDAO = getDAO().getUserSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isBackendAdmin()) { // TODO: isOrderAdmin filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, user); } else { filter = user; } } // Fetch and convert all Indexs Collection<UserSecurity> tUserSecurities = tUserSecurityDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.UserSecurity tUserSecurity : tUserSecurities) { oVector.add(tUserSecurity.toStruct( com.kapti.data.UserSecurity.Fields.AMOUNT, com.kapti.data.UserSecurity.Fields.ISIN, com.kapti.data.UserSecurity.Fields.USER)); } return oVector; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.UserSecurity, UserSecurityPK> tUserSecurityDAO = getDAO().getUserSecurityDAO(); // Instantiate a new exchange UserSecurity tUserSecurity = UserSecurity.fromStruct(iDetails); tUserSecurity.applyStruct(iDetails); tUserSecurityDAO.create(tUserSecurity); return 1; } }
201285_1
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.Exchange; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief Handler van de Finance.Exchange subklasse. * * Deze klasse is de handler van de Finance.Exchange subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class ExchangeHandler extends MethodClass { // // Methodes // public Vector<HashMap<String, Object>> List() throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Exchange, String> exDAO = getDAO().getExchangeDAO(); // Fetch and convert all exchanges Collection<com.kapti.data.Exchange> tExchanges = exDAO.findAll(); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.Exchange tExchange : tExchanges) { oVector.add(tExchange.toStruct( com.kapti.data.Exchange.Fields.SYMBOL, com.kapti.data.Exchange.Fields.NAME, com.kapti.data.Exchange.Fields.LOCATION)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Exchange, String> exDAO = getDAO().getExchangeDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all exchanges Collection<com.kapti.data.Exchange> tExchanges = exDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.Exchange tExchange : tExchanges) { oVector.add(tExchange.toStruct( com.kapti.data.Exchange.Fields.SYMBOL, com.kapti.data.Exchange.Fields.NAME, com.kapti.data.Exchange.Fields.LOCATION)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Exchange, String> exDAO = getDAO().getExchangeDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the exchanges we need to modify Collection<com.kapti.data.Exchange> tExchanges = exDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Exchange tExchange : tExchanges) { tExchange.applyStruct(iDetails); exDAO.update(tExchange); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Exchange, String> exDAO = getDAO().getExchangeDAO(); // Instantiate a new exchange Exchange tExchange = Exchange.fromStruct(iDetails); tExchange.applyStruct(iDetails); exDAO.create(tExchange); return 1; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/finance/ExchangeHandler.java
1,089
/** * \brief Handler van de Finance.Exchange subklasse. * * Deze klasse is de handler van de Finance.Exchange subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */
block_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.Exchange; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief <SUF>*/ public class ExchangeHandler extends MethodClass { // // Methodes // public Vector<HashMap<String, Object>> List() throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Exchange, String> exDAO = getDAO().getExchangeDAO(); // Fetch and convert all exchanges Collection<com.kapti.data.Exchange> tExchanges = exDAO.findAll(); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.Exchange tExchange : tExchanges) { oVector.add(tExchange.toStruct( com.kapti.data.Exchange.Fields.SYMBOL, com.kapti.data.Exchange.Fields.NAME, com.kapti.data.Exchange.Fields.LOCATION)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Exchange, String> exDAO = getDAO().getExchangeDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all exchanges Collection<com.kapti.data.Exchange> tExchanges = exDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.Exchange tExchange : tExchanges) { oVector.add(tExchange.toStruct( com.kapti.data.Exchange.Fields.SYMBOL, com.kapti.data.Exchange.Fields.NAME, com.kapti.data.Exchange.Fields.LOCATION)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Exchange, String> exDAO = getDAO().getExchangeDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the exchanges we need to modify Collection<com.kapti.data.Exchange> tExchanges = exDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Exchange tExchange : tExchanges) { tExchange.applyStruct(iDetails); exDAO.update(tExchange); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Exchange, String> exDAO = getDAO().getExchangeDAO(); // Instantiate a new exchange Exchange tExchange = Exchange.fromStruct(iDetails); tExchange.applyStruct(iDetails); exDAO.create(tExchange); return 1; } }
201286_1
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api; import com.kapti.backend.helpers.DateHelper; import com.kapti.backend.security.SessionsHandler; import com.kapti.data.User; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.InvocationException; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Vector; /** * \brief Handler van de User klasse. * * Deze klasse is de handler van de User klasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class UserHandler extends MethodClass { // // Methodes // public int Hello(String iClient, int iProtocolVersion) throws StockPlayException { getLogger().info("Client connected: " + iClient); if (iProtocolVersion != PROTOCOL_VERSION) { throw new InvocationException(InvocationException.Type.VERSION_NOT_SUPPORTED); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); // Instantiate a new user User tUser = User.fromStruct(iDetails); tUser.applyStruct(iDetails); tUser.setStartamount(100000); //TODO hier berekenen van het startamount tUser.setCash(100000); tUser.setRegdate(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return tUserDAO.create(tUser); } public Vector<HashMap<String, Object>> Details() throws StockPlayException { return Details("id == '" + getUser().getId() + "" + "'s"); } public Vector<HashMap<String, Object>> Details(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.EMAIL, com.kapti.data.User.Fields.LASTNAME, com.kapti.data.User.Fields.FIRSTNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.RRN, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public int Modify(HashMap<String, Object> iDetails) throws StockPlayException { return Modify(("id == '" + getUser().getId() + "" + "'s"), iDetails); } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Now apply the new properties // TODO: controleren of de struct geen ID field bevat, deze kan _enkel_ // gebruikt worden om een initiële Exchange aa nte maken (Create) for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUser.applyStruct(iDetails); tUserDAO.update(tUser); } return 1; } public int Remove(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUserDAO.delete(tUser); } return 1; } // Authenticatiemethode public String Validate(String nickname, String password) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse("nickname == '" + nickname + "'"); Collection<com.kapti.data.User> tUsers = tUserDAO.findByFilter(filter); if (tUsers.size() == 0) { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } Iterator<User> uIterator = tUsers.iterator(); User user = uIterator.next(); if (user.checkPassword(password)) { return createAndRegisterSession(user); } else { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } } public String CreateSessionForUser(int id) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); User u = tUserDAO.findById(id); return createAndRegisterSession(u); } private String createAndRegisterSession(User user) { //we generereren nu een sessie-id voor de gebruiker java.security.SecureRandom random = new SecureRandom(); String sessionid = new BigInteger(130, random).toString(32); SessionsHandler.getInstance().registerSession(sessionid, user); return sessionid; } public boolean ResetPassword(String nickname, String newpassword) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Filter f = Parser.getInstance().parse("nickname == '" + nickname + "'"); Collection<User> users = tUserDAO.findByFilter(f); if (!users.isEmpty()) { User u = users.iterator().next(); u.setPassword(newpassword); return tUserDAO.update(u); } else { throw new StockPlayException(98,"No user found with nickname " + nickname); } } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/UserHandler.java
2,237
/** * \brief Handler van de User klasse. * * Deze klasse is de handler van de User klasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */
block_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api; import com.kapti.backend.helpers.DateHelper; import com.kapti.backend.security.SessionsHandler; import com.kapti.data.User; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.InvocationException; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Vector; /** * \brief <SUF>*/ public class UserHandler extends MethodClass { // // Methodes // public int Hello(String iClient, int iProtocolVersion) throws StockPlayException { getLogger().info("Client connected: " + iClient); if (iProtocolVersion != PROTOCOL_VERSION) { throw new InvocationException(InvocationException.Type.VERSION_NOT_SUPPORTED); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); // Instantiate a new user User tUser = User.fromStruct(iDetails); tUser.applyStruct(iDetails); tUser.setStartamount(100000); //TODO hier berekenen van het startamount tUser.setCash(100000); tUser.setRegdate(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return tUserDAO.create(tUser); } public Vector<HashMap<String, Object>> Details() throws StockPlayException { return Details("id == '" + getUser().getId() + "" + "'s"); } public Vector<HashMap<String, Object>> Details(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.EMAIL, com.kapti.data.User.Fields.LASTNAME, com.kapti.data.User.Fields.FIRSTNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.RRN, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public int Modify(HashMap<String, Object> iDetails) throws StockPlayException { return Modify(("id == '" + getUser().getId() + "" + "'s"), iDetails); } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Now apply the new properties // TODO: controleren of de struct geen ID field bevat, deze kan _enkel_ // gebruikt worden om een initiële Exchange aa nte maken (Create) for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUser.applyStruct(iDetails); tUserDAO.update(tUser); } return 1; } public int Remove(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUserDAO.delete(tUser); } return 1; } // Authenticatiemethode public String Validate(String nickname, String password) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse("nickname == '" + nickname + "'"); Collection<com.kapti.data.User> tUsers = tUserDAO.findByFilter(filter); if (tUsers.size() == 0) { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } Iterator<User> uIterator = tUsers.iterator(); User user = uIterator.next(); if (user.checkPassword(password)) { return createAndRegisterSession(user); } else { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } } public String CreateSessionForUser(int id) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); User u = tUserDAO.findById(id); return createAndRegisterSession(u); } private String createAndRegisterSession(User user) { //we generereren nu een sessie-id voor de gebruiker java.security.SecureRandom random = new SecureRandom(); String sessionid = new BigInteger(130, random).toString(32); SessionsHandler.getInstance().registerSession(sessionid, user); return sessionid; } public boolean ResetPassword(String nickname, String newpassword) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Filter f = Parser.getInstance().parse("nickname == '" + nickname + "'"); Collection<User> users = tUserDAO.findByFilter(f); if (!users.isEmpty()) { User u = users.iterator().next(); u.setPassword(newpassword); return tUserDAO.update(u); } else { throw new StockPlayException(98,"No user found with nickname " + nickname); } } }
201286_4
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api; import com.kapti.backend.helpers.DateHelper; import com.kapti.backend.security.SessionsHandler; import com.kapti.data.User; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.InvocationException; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Vector; /** * \brief Handler van de User klasse. * * Deze klasse is de handler van de User klasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class UserHandler extends MethodClass { // // Methodes // public int Hello(String iClient, int iProtocolVersion) throws StockPlayException { getLogger().info("Client connected: " + iClient); if (iProtocolVersion != PROTOCOL_VERSION) { throw new InvocationException(InvocationException.Type.VERSION_NOT_SUPPORTED); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); // Instantiate a new user User tUser = User.fromStruct(iDetails); tUser.applyStruct(iDetails); tUser.setStartamount(100000); //TODO hier berekenen van het startamount tUser.setCash(100000); tUser.setRegdate(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return tUserDAO.create(tUser); } public Vector<HashMap<String, Object>> Details() throws StockPlayException { return Details("id == '" + getUser().getId() + "" + "'s"); } public Vector<HashMap<String, Object>> Details(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.EMAIL, com.kapti.data.User.Fields.LASTNAME, com.kapti.data.User.Fields.FIRSTNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.RRN, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public int Modify(HashMap<String, Object> iDetails) throws StockPlayException { return Modify(("id == '" + getUser().getId() + "" + "'s"), iDetails); } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Now apply the new properties // TODO: controleren of de struct geen ID field bevat, deze kan _enkel_ // gebruikt worden om een initiële Exchange aa nte maken (Create) for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUser.applyStruct(iDetails); tUserDAO.update(tUser); } return 1; } public int Remove(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUserDAO.delete(tUser); } return 1; } // Authenticatiemethode public String Validate(String nickname, String password) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse("nickname == '" + nickname + "'"); Collection<com.kapti.data.User> tUsers = tUserDAO.findByFilter(filter); if (tUsers.size() == 0) { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } Iterator<User> uIterator = tUsers.iterator(); User user = uIterator.next(); if (user.checkPassword(password)) { return createAndRegisterSession(user); } else { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } } public String CreateSessionForUser(int id) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); User u = tUserDAO.findById(id); return createAndRegisterSession(u); } private String createAndRegisterSession(User user) { //we generereren nu een sessie-id voor de gebruiker java.security.SecureRandom random = new SecureRandom(); String sessionid = new BigInteger(130, random).toString(32); SessionsHandler.getInstance().registerSession(sessionid, user); return sessionid; } public boolean ResetPassword(String nickname, String newpassword) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Filter f = Parser.getInstance().parse("nickname == '" + nickname + "'"); Collection<User> users = tUserDAO.findByFilter(f); if (!users.isEmpty()) { User u = users.iterator().next(); u.setPassword(newpassword); return tUserDAO.update(u); } else { throw new StockPlayException(98,"No user found with nickname " + nickname); } } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/UserHandler.java
2,237
//TODO hier berekenen van het startamount
line_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api; import com.kapti.backend.helpers.DateHelper; import com.kapti.backend.security.SessionsHandler; import com.kapti.data.User; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.InvocationException; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Vector; /** * \brief Handler van de User klasse. * * Deze klasse is de handler van de User klasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class UserHandler extends MethodClass { // // Methodes // public int Hello(String iClient, int iProtocolVersion) throws StockPlayException { getLogger().info("Client connected: " + iClient); if (iProtocolVersion != PROTOCOL_VERSION) { throw new InvocationException(InvocationException.Type.VERSION_NOT_SUPPORTED); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); // Instantiate a new user User tUser = User.fromStruct(iDetails); tUser.applyStruct(iDetails); tUser.setStartamount(100000); //TODO hier<SUF> tUser.setCash(100000); tUser.setRegdate(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return tUserDAO.create(tUser); } public Vector<HashMap<String, Object>> Details() throws StockPlayException { return Details("id == '" + getUser().getId() + "" + "'s"); } public Vector<HashMap<String, Object>> Details(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.EMAIL, com.kapti.data.User.Fields.LASTNAME, com.kapti.data.User.Fields.FIRSTNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.RRN, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public int Modify(HashMap<String, Object> iDetails) throws StockPlayException { return Modify(("id == '" + getUser().getId() + "" + "'s"), iDetails); } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Now apply the new properties // TODO: controleren of de struct geen ID field bevat, deze kan _enkel_ // gebruikt worden om een initiële Exchange aa nte maken (Create) for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUser.applyStruct(iDetails); tUserDAO.update(tUser); } return 1; } public int Remove(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUserDAO.delete(tUser); } return 1; } // Authenticatiemethode public String Validate(String nickname, String password) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse("nickname == '" + nickname + "'"); Collection<com.kapti.data.User> tUsers = tUserDAO.findByFilter(filter); if (tUsers.size() == 0) { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } Iterator<User> uIterator = tUsers.iterator(); User user = uIterator.next(); if (user.checkPassword(password)) { return createAndRegisterSession(user); } else { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } } public String CreateSessionForUser(int id) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); User u = tUserDAO.findById(id); return createAndRegisterSession(u); } private String createAndRegisterSession(User user) { //we generereren nu een sessie-id voor de gebruiker java.security.SecureRandom random = new SecureRandom(); String sessionid = new BigInteger(130, random).toString(32); SessionsHandler.getInstance().registerSession(sessionid, user); return sessionid; } public boolean ResetPassword(String nickname, String newpassword) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Filter f = Parser.getInstance().parse("nickname == '" + nickname + "'"); Collection<User> users = tUserDAO.findByFilter(f); if (!users.isEmpty()) { User u = users.iterator().next(); u.setPassword(newpassword); return tUserDAO.update(u); } else { throw new StockPlayException(98,"No user found with nickname " + nickname); } } }
201286_11
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api; import com.kapti.backend.helpers.DateHelper; import com.kapti.backend.security.SessionsHandler; import com.kapti.data.User; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.InvocationException; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Vector; /** * \brief Handler van de User klasse. * * Deze klasse is de handler van de User klasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class UserHandler extends MethodClass { // // Methodes // public int Hello(String iClient, int iProtocolVersion) throws StockPlayException { getLogger().info("Client connected: " + iClient); if (iProtocolVersion != PROTOCOL_VERSION) { throw new InvocationException(InvocationException.Type.VERSION_NOT_SUPPORTED); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); // Instantiate a new user User tUser = User.fromStruct(iDetails); tUser.applyStruct(iDetails); tUser.setStartamount(100000); //TODO hier berekenen van het startamount tUser.setCash(100000); tUser.setRegdate(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return tUserDAO.create(tUser); } public Vector<HashMap<String, Object>> Details() throws StockPlayException { return Details("id == '" + getUser().getId() + "" + "'s"); } public Vector<HashMap<String, Object>> Details(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.EMAIL, com.kapti.data.User.Fields.LASTNAME, com.kapti.data.User.Fields.FIRSTNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.RRN, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public int Modify(HashMap<String, Object> iDetails) throws StockPlayException { return Modify(("id == '" + getUser().getId() + "" + "'s"), iDetails); } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Now apply the new properties // TODO: controleren of de struct geen ID field bevat, deze kan _enkel_ // gebruikt worden om een initiële Exchange aa nte maken (Create) for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUser.applyStruct(iDetails); tUserDAO.update(tUser); } return 1; } public int Remove(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUserDAO.delete(tUser); } return 1; } // Authenticatiemethode public String Validate(String nickname, String password) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse("nickname == '" + nickname + "'"); Collection<com.kapti.data.User> tUsers = tUserDAO.findByFilter(filter); if (tUsers.size() == 0) { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } Iterator<User> uIterator = tUsers.iterator(); User user = uIterator.next(); if (user.checkPassword(password)) { return createAndRegisterSession(user); } else { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } } public String CreateSessionForUser(int id) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); User u = tUserDAO.findById(id); return createAndRegisterSession(u); } private String createAndRegisterSession(User user) { //we generereren nu een sessie-id voor de gebruiker java.security.SecureRandom random = new SecureRandom(); String sessionid = new BigInteger(130, random).toString(32); SessionsHandler.getInstance().registerSession(sessionid, user); return sessionid; } public boolean ResetPassword(String nickname, String newpassword) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Filter f = Parser.getInstance().parse("nickname == '" + nickname + "'"); Collection<User> users = tUserDAO.findByFilter(f); if (!users.isEmpty()) { User u = users.iterator().next(); u.setPassword(newpassword); return tUserDAO.update(u); } else { throw new StockPlayException(98,"No user found with nickname " + nickname); } } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/UserHandler.java
2,237
// TODO: controleren of de struct geen ID field bevat, deze kan _enkel_
line_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api; import com.kapti.backend.helpers.DateHelper; import com.kapti.backend.security.SessionsHandler; import com.kapti.data.User; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.InvocationException; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Vector; /** * \brief Handler van de User klasse. * * Deze klasse is de handler van de User klasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class UserHandler extends MethodClass { // // Methodes // public int Hello(String iClient, int iProtocolVersion) throws StockPlayException { getLogger().info("Client connected: " + iClient); if (iProtocolVersion != PROTOCOL_VERSION) { throw new InvocationException(InvocationException.Type.VERSION_NOT_SUPPORTED); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); // Instantiate a new user User tUser = User.fromStruct(iDetails); tUser.applyStruct(iDetails); tUser.setStartamount(100000); //TODO hier berekenen van het startamount tUser.setCash(100000); tUser.setRegdate(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return tUserDAO.create(tUser); } public Vector<HashMap<String, Object>> Details() throws StockPlayException { return Details("id == '" + getUser().getId() + "" + "'s"); } public Vector<HashMap<String, Object>> Details(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.EMAIL, com.kapti.data.User.Fields.LASTNAME, com.kapti.data.User.Fields.FIRSTNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.RRN, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public int Modify(HashMap<String, Object> iDetails) throws StockPlayException { return Modify(("id == '" + getUser().getId() + "" + "'s"), iDetails); } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Now apply the new properties // TODO: controleren<SUF> // gebruikt worden om een initiële Exchange aa nte maken (Create) for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUser.applyStruct(iDetails); tUserDAO.update(tUser); } return 1; } public int Remove(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUserDAO.delete(tUser); } return 1; } // Authenticatiemethode public String Validate(String nickname, String password) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse("nickname == '" + nickname + "'"); Collection<com.kapti.data.User> tUsers = tUserDAO.findByFilter(filter); if (tUsers.size() == 0) { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } Iterator<User> uIterator = tUsers.iterator(); User user = uIterator.next(); if (user.checkPassword(password)) { return createAndRegisterSession(user); } else { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } } public String CreateSessionForUser(int id) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); User u = tUserDAO.findById(id); return createAndRegisterSession(u); } private String createAndRegisterSession(User user) { //we generereren nu een sessie-id voor de gebruiker java.security.SecureRandom random = new SecureRandom(); String sessionid = new BigInteger(130, random).toString(32); SessionsHandler.getInstance().registerSession(sessionid, user); return sessionid; } public boolean ResetPassword(String nickname, String newpassword) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Filter f = Parser.getInstance().parse("nickname == '" + nickname + "'"); Collection<User> users = tUserDAO.findByFilter(f); if (!users.isEmpty()) { User u = users.iterator().next(); u.setPassword(newpassword); return tUserDAO.update(u); } else { throw new StockPlayException(98,"No user found with nickname " + nickname); } } }
201286_12
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api; import com.kapti.backend.helpers.DateHelper; import com.kapti.backend.security.SessionsHandler; import com.kapti.data.User; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.InvocationException; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Vector; /** * \brief Handler van de User klasse. * * Deze klasse is de handler van de User klasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class UserHandler extends MethodClass { // // Methodes // public int Hello(String iClient, int iProtocolVersion) throws StockPlayException { getLogger().info("Client connected: " + iClient); if (iProtocolVersion != PROTOCOL_VERSION) { throw new InvocationException(InvocationException.Type.VERSION_NOT_SUPPORTED); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); // Instantiate a new user User tUser = User.fromStruct(iDetails); tUser.applyStruct(iDetails); tUser.setStartamount(100000); //TODO hier berekenen van het startamount tUser.setCash(100000); tUser.setRegdate(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return tUserDAO.create(tUser); } public Vector<HashMap<String, Object>> Details() throws StockPlayException { return Details("id == '" + getUser().getId() + "" + "'s"); } public Vector<HashMap<String, Object>> Details(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.EMAIL, com.kapti.data.User.Fields.LASTNAME, com.kapti.data.User.Fields.FIRSTNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.RRN, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public int Modify(HashMap<String, Object> iDetails) throws StockPlayException { return Modify(("id == '" + getUser().getId() + "" + "'s"), iDetails); } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Now apply the new properties // TODO: controleren of de struct geen ID field bevat, deze kan _enkel_ // gebruikt worden om een initiële Exchange aa nte maken (Create) for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUser.applyStruct(iDetails); tUserDAO.update(tUser); } return 1; } public int Remove(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUserDAO.delete(tUser); } return 1; } // Authenticatiemethode public String Validate(String nickname, String password) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse("nickname == '" + nickname + "'"); Collection<com.kapti.data.User> tUsers = tUserDAO.findByFilter(filter); if (tUsers.size() == 0) { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } Iterator<User> uIterator = tUsers.iterator(); User user = uIterator.next(); if (user.checkPassword(password)) { return createAndRegisterSession(user); } else { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } } public String CreateSessionForUser(int id) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); User u = tUserDAO.findById(id); return createAndRegisterSession(u); } private String createAndRegisterSession(User user) { //we generereren nu een sessie-id voor de gebruiker java.security.SecureRandom random = new SecureRandom(); String sessionid = new BigInteger(130, random).toString(32); SessionsHandler.getInstance().registerSession(sessionid, user); return sessionid; } public boolean ResetPassword(String nickname, String newpassword) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Filter f = Parser.getInstance().parse("nickname == '" + nickname + "'"); Collection<User> users = tUserDAO.findByFilter(f); if (!users.isEmpty()) { User u = users.iterator().next(); u.setPassword(newpassword); return tUserDAO.update(u); } else { throw new StockPlayException(98,"No user found with nickname " + nickname); } } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/UserHandler.java
2,237
// gebruikt worden om een initiële Exchange aa nte maken (Create)
line_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api; import com.kapti.backend.helpers.DateHelper; import com.kapti.backend.security.SessionsHandler; import com.kapti.data.User; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.InvocationException; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Vector; /** * \brief Handler van de User klasse. * * Deze klasse is de handler van de User klasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class UserHandler extends MethodClass { // // Methodes // public int Hello(String iClient, int iProtocolVersion) throws StockPlayException { getLogger().info("Client connected: " + iClient); if (iProtocolVersion != PROTOCOL_VERSION) { throw new InvocationException(InvocationException.Type.VERSION_NOT_SUPPORTED); } return 1; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); // Instantiate a new user User tUser = User.fromStruct(iDetails); tUser.applyStruct(iDetails); tUser.setStartamount(100000); //TODO hier berekenen van het startamount tUser.setCash(100000); tUser.setRegdate(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return tUserDAO.create(tUser); } public Vector<HashMap<String, Object>> Details() throws StockPlayException { return Details("id == '" + getUser().getId() + "" + "'s"); } public Vector<HashMap<String, Object>> Details(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.EMAIL, com.kapti.data.User.Fields.LASTNAME, com.kapti.data.User.Fields.FIRSTNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.RRN, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> userDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.User> tUsers = userDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.User tUser : tUsers) { oVector.add(tUser.toStruct( com.kapti.data.User.Fields.ID, com.kapti.data.User.Fields.NICKNAME, com.kapti.data.User.Fields.CASH, com.kapti.data.User.Fields.ROLE, com.kapti.data.User.Fields.STARTAMOUNT, com.kapti.data.User.Fields.REGDATE, com.kapti.data.User.Fields.POINTS)); } return oVector; } public int Modify(HashMap<String, Object> iDetails) throws StockPlayException { return Modify(("id == '" + getUser().getId() + "" + "'s"), iDetails); } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Now apply the new properties // TODO: controleren of de struct geen ID field bevat, deze kan _enkel_ // gebruikt worden<SUF> for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUser.applyStruct(iDetails); tUserDAO.update(tUser); } return 1; } public int Remove(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); for (com.kapti.data.User tUser : tUserDAO.findByFilter(filter)) { tUserDAO.delete(tUser); } return 1; } // Authenticatiemethode public String Validate(String nickname, String password) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse("nickname == '" + nickname + "'"); Collection<com.kapti.data.User> tUsers = tUserDAO.findByFilter(filter); if (tUsers.size() == 0) { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } Iterator<User> uIterator = tUsers.iterator(); User user = uIterator.next(); if (user.checkPassword(password)) { return createAndRegisterSession(user); } else { throw new ServiceException(ServiceException.Type.INVALID_CREDENTIALS); } } public String CreateSessionForUser(int id) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); User u = tUserDAO.findById(id); return createAndRegisterSession(u); } private String createAndRegisterSession(User user) { //we generereren nu een sessie-id voor de gebruiker java.security.SecureRandom random = new SecureRandom(); String sessionid = new BigInteger(130, random).toString(32); SessionsHandler.getInstance().registerSession(sessionid, user); return sessionid; } public boolean ResetPassword(String nickname, String newpassword) throws StockPlayException { GenericDAO<com.kapti.data.User, Integer> tUserDAO = getDAO().getUserDAO(); Filter f = Parser.getInstance().parse("nickname == '" + nickname + "'"); Collection<User> users = tUserDAO.findByFilter(f); if (!users.isEmpty()) { User u = users.iterator().next(); u.setPassword(newpassword); return tUserDAO.update(u); } else { throw new StockPlayException(98,"No user found with nickname " + nickname); } } }
201287_1
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.IndexSecurity; import com.kapti.data.IndexSecurity.IndexSecurityPK; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief Handler van de User.Portfolio subklasse. * * Deze klasse is de handler van de User.Portfolio subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class IndexSecurityHandler extends MethodClass { // // Methodes // public Vector<HashMap<String, Object>> List() throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.IndexSecurity, IndexSecurityPK> tIndexSecurityDAO = getDAO().getIndexSecurityDAO(); // Fetch and convert all IndexSecurities Collection<IndexSecurity> tIndexSecurities = tIndexSecurityDAO.findAll(); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.IndexSecurity tIndexSecurity : tIndexSecurities) { oVector.add(tIndexSecurity.toStruct( com.kapti.data.IndexSecurity.Fields.INDEX_ISIN, com.kapti.data.IndexSecurity.Fields.SECURITY_ISIN)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.IndexSecurity, IndexSecurityPK> tIndexSecurityDAO = getDAO().getIndexSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all IndexSecurities Collection<IndexSecurity> tIndexSecurities = tIndexSecurityDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.IndexSecurity tIndexSecurity : tIndexSecurities) { oVector.add(tIndexSecurity.toStruct( com.kapti.data.IndexSecurity.Fields.INDEX_ISIN, com.kapti.data.IndexSecurity.Fields.SECURITY_ISIN)); } return oVector; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.IndexSecurity, IndexSecurityPK> tIndexSecurityDAO = getDAO().getIndexSecurityDAO(); // Instantiate a new exchange IndexSecurity tIndexSecurity = IndexSecurity.fromStruct(iDetails); tIndexSecurity.applyStruct(iDetails); tIndexSecurityDAO.create(tIndexSecurity); return 1; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/finance/IndexSecurityHandler.java
946
/** * \brief Handler van de User.Portfolio subklasse. * * Deze klasse is de handler van de User.Portfolio subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */
block_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.IndexSecurity; import com.kapti.data.IndexSecurity.IndexSecurityPK; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief <SUF>*/ public class IndexSecurityHandler extends MethodClass { // // Methodes // public Vector<HashMap<String, Object>> List() throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.IndexSecurity, IndexSecurityPK> tIndexSecurityDAO = getDAO().getIndexSecurityDAO(); // Fetch and convert all IndexSecurities Collection<IndexSecurity> tIndexSecurities = tIndexSecurityDAO.findAll(); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.IndexSecurity tIndexSecurity : tIndexSecurities) { oVector.add(tIndexSecurity.toStruct( com.kapti.data.IndexSecurity.Fields.INDEX_ISIN, com.kapti.data.IndexSecurity.Fields.SECURITY_ISIN)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.IndexSecurity, IndexSecurityPK> tIndexSecurityDAO = getDAO().getIndexSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all IndexSecurities Collection<IndexSecurity> tIndexSecurities = tIndexSecurityDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.IndexSecurity tIndexSecurity : tIndexSecurities) { oVector.add(tIndexSecurity.toStruct( com.kapti.data.IndexSecurity.Fields.INDEX_ISIN, com.kapti.data.IndexSecurity.Fields.SECURITY_ISIN)); } return oVector; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.IndexSecurity, IndexSecurityPK> tIndexSecurityDAO = getDAO().getIndexSecurityDAO(); // Instantiate a new exchange IndexSecurity tIndexSecurity = IndexSecurity.fromStruct(iDetails); tIndexSecurity.applyStruct(iDetails); tIndexSecurityDAO.create(tIndexSecurity); return 1; } }
201288_1
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.user; import com.kapti.backend.api.MethodClass; import com.kapti.data.PointsTransaction; import com.kapti.data.PointsTransaction.Fields; import com.kapti.data.PointsTransaction.PointsTransactionPK; import com.kapti.data.Rank; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericPointsTransactionDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import com.kapti.filter.relation.RelationAnd; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief Handler van de User.Points subklasse. * * Deze klasse is de handler van de User.Points subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class PointsHandler extends MethodClass { public Vector<HashMap<String, Object>> Ranking(String iFilter) throws StockPlayException { // Get DAO reference GenericPointsTransactionDAO tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<Rank> tRanking = tPointsTransactionDAO.findRankingByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (Rank tRank : tRanking) { oVector.add(tRank.toStruct( Rank.Fields.ID, Rank.Fields.TOTAL, Rank.Fields.RANK)); } return oVector; } public Vector<HashMap<String, Object>> EventRanking(String iFilter) throws StockPlayException { // Get DAO reference GenericPointsTransactionDAO tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<PointsTransaction> tRanking = tPointsTransactionDAO.findRankingEventByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (PointsTransaction tPoints : tRanking) { oVector.add(tPoints.toStruct( Fields.USER, Fields.TYPE, Fields.TIMESTAMP, Fields.DELTA, Fields.COMMENTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isPointsAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, user); } else { filter = user; } } // Fetch and convert all Indexs Collection<PointsTransaction> tTransactions = tPointsTransactionDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (PointsTransaction tTransaction : tTransactions) { oVector.add(tTransaction.toStruct( Fields.USER, Fields.TYPE, Fields.TIMESTAMP, Fields.DELTA, Fields.COMMENTS)); } return oVector; } public int CreateTransaction(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Instantiate a new transaction //iDetails.put(Fields.TIMESTAMP.toString(), DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); PointsTransaction tTransaction = PointsTransaction.fromStruct(iDetails); tTransaction.applyStruct(iDetails); return tPointsTransactionDAO.create(tTransaction); } public int DeleteTransaction(HashMap<String, Object> iDetails) throws StockPlayException{ // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); PointsTransaction tTransaction = PointsTransaction.fromStruct(iDetails); return tPointsTransactionDAO.delete(tTransaction) ? 1:0; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/user/PointsHandler.java
1,363
/** * \brief Handler van de User.Points subklasse. * * Deze klasse is de handler van de User.Points subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */
block_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.user; import com.kapti.backend.api.MethodClass; import com.kapti.data.PointsTransaction; import com.kapti.data.PointsTransaction.Fields; import com.kapti.data.PointsTransaction.PointsTransactionPK; import com.kapti.data.Rank; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericPointsTransactionDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import com.kapti.filter.relation.RelationAnd; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief <SUF>*/ public class PointsHandler extends MethodClass { public Vector<HashMap<String, Object>> Ranking(String iFilter) throws StockPlayException { // Get DAO reference GenericPointsTransactionDAO tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<Rank> tRanking = tPointsTransactionDAO.findRankingByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (Rank tRank : tRanking) { oVector.add(tRank.toStruct( Rank.Fields.ID, Rank.Fields.TOTAL, Rank.Fields.RANK)); } return oVector; } public Vector<HashMap<String, Object>> EventRanking(String iFilter) throws StockPlayException { // Get DAO reference GenericPointsTransactionDAO tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<PointsTransaction> tRanking = tPointsTransactionDAO.findRankingEventByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (PointsTransaction tPoints : tRanking) { oVector.add(tPoints.toStruct( Fields.USER, Fields.TYPE, Fields.TIMESTAMP, Fields.DELTA, Fields.COMMENTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isPointsAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, user); } else { filter = user; } } // Fetch and convert all Indexs Collection<PointsTransaction> tTransactions = tPointsTransactionDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (PointsTransaction tTransaction : tTransactions) { oVector.add(tTransaction.toStruct( Fields.USER, Fields.TYPE, Fields.TIMESTAMP, Fields.DELTA, Fields.COMMENTS)); } return oVector; } public int CreateTransaction(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Instantiate a new transaction //iDetails.put(Fields.TIMESTAMP.toString(), DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); PointsTransaction tTransaction = PointsTransaction.fromStruct(iDetails); tTransaction.applyStruct(iDetails); return tPointsTransactionDAO.create(tTransaction); } public int DeleteTransaction(HashMap<String, Object> iDetails) throws StockPlayException{ // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); PointsTransaction tTransaction = PointsTransaction.fromStruct(iDetails); return tPointsTransactionDAO.delete(tTransaction) ? 1:0; } }
201288_13
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.user; import com.kapti.backend.api.MethodClass; import com.kapti.data.PointsTransaction; import com.kapti.data.PointsTransaction.Fields; import com.kapti.data.PointsTransaction.PointsTransactionPK; import com.kapti.data.Rank; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericPointsTransactionDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import com.kapti.filter.relation.RelationAnd; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief Handler van de User.Points subklasse. * * Deze klasse is de handler van de User.Points subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class PointsHandler extends MethodClass { public Vector<HashMap<String, Object>> Ranking(String iFilter) throws StockPlayException { // Get DAO reference GenericPointsTransactionDAO tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<Rank> tRanking = tPointsTransactionDAO.findRankingByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (Rank tRank : tRanking) { oVector.add(tRank.toStruct( Rank.Fields.ID, Rank.Fields.TOTAL, Rank.Fields.RANK)); } return oVector; } public Vector<HashMap<String, Object>> EventRanking(String iFilter) throws StockPlayException { // Get DAO reference GenericPointsTransactionDAO tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<PointsTransaction> tRanking = tPointsTransactionDAO.findRankingEventByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (PointsTransaction tPoints : tRanking) { oVector.add(tPoints.toStruct( Fields.USER, Fields.TYPE, Fields.TIMESTAMP, Fields.DELTA, Fields.COMMENTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isPointsAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, user); } else { filter = user; } } // Fetch and convert all Indexs Collection<PointsTransaction> tTransactions = tPointsTransactionDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (PointsTransaction tTransaction : tTransactions) { oVector.add(tTransaction.toStruct( Fields.USER, Fields.TYPE, Fields.TIMESTAMP, Fields.DELTA, Fields.COMMENTS)); } return oVector; } public int CreateTransaction(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Instantiate a new transaction //iDetails.put(Fields.TIMESTAMP.toString(), DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); PointsTransaction tTransaction = PointsTransaction.fromStruct(iDetails); tTransaction.applyStruct(iDetails); return tPointsTransactionDAO.create(tTransaction); } public int DeleteTransaction(HashMap<String, Object> iDetails) throws StockPlayException{ // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); PointsTransaction tTransaction = PointsTransaction.fromStruct(iDetails); return tPointsTransactionDAO.delete(tTransaction) ? 1:0; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/user/PointsHandler.java
1,363
//iDetails.put(Fields.TIMESTAMP.toString(), DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime());
line_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.user; import com.kapti.backend.api.MethodClass; import com.kapti.data.PointsTransaction; import com.kapti.data.PointsTransaction.Fields; import com.kapti.data.PointsTransaction.PointsTransactionPK; import com.kapti.data.Rank; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericPointsTransactionDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import com.kapti.filter.relation.RelationAnd; import java.util.Collection; import java.util.HashMap; import java.util.Vector; /** * \brief Handler van de User.Points subklasse. * * Deze klasse is de handler van de User.Points subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class PointsHandler extends MethodClass { public Vector<HashMap<String, Object>> Ranking(String iFilter) throws StockPlayException { // Get DAO reference GenericPointsTransactionDAO tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<Rank> tRanking = tPointsTransactionDAO.findRankingByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (Rank tRank : tRanking) { oVector.add(tRank.toStruct( Rank.Fields.ID, Rank.Fields.TOTAL, Rank.Fields.RANK)); } return oVector; } public Vector<HashMap<String, Object>> EventRanking(String iFilter) throws StockPlayException { // Get DAO reference GenericPointsTransactionDAO tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<PointsTransaction> tRanking = tPointsTransactionDAO.findRankingEventByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (PointsTransaction tPoints : tRanking) { oVector.add(tPoints.toStruct( Fields.USER, Fields.TYPE, Fields.TIMESTAMP, Fields.DELTA, Fields.COMMENTS)); } return oVector; } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isPointsAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, user); } else { filter = user; } } // Fetch and convert all Indexs Collection<PointsTransaction> tTransactions = tPointsTransactionDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (PointsTransaction tTransaction : tTransactions) { oVector.add(tTransaction.toStruct( Fields.USER, Fields.TYPE, Fields.TIMESTAMP, Fields.DELTA, Fields.COMMENTS)); } return oVector; } public int CreateTransaction(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); // Instantiate a new transaction //iDetails.put(Fields.TIMESTAMP.toString(), DateHelper.convertCalendar(Calendar.getInstance(),<SUF> PointsTransaction tTransaction = PointsTransaction.fromStruct(iDetails); tTransaction.applyStruct(iDetails); return tPointsTransactionDAO.create(tTransaction); } public int DeleteTransaction(HashMap<String, Object> iDetails) throws StockPlayException{ // Get DAO reference GenericDAO<PointsTransaction, PointsTransactionPK> tPointsTransactionDAO = getDAO().getPointsTransactionDAO(); PointsTransaction tTransaction = PointsTransaction.fromStruct(iDetails); return tPointsTransactionDAO.delete(tTransaction) ? 1:0; } }
201289_1
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.user; import com.kapti.backend.api.MethodClass; import com.kapti.backend.helpers.DateHelper; import com.kapti.data.Order; import com.kapti.data.OrderStatus; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import com.kapti.filter.relation.RelationAnd; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.TimeZone; import java.util.Vector; /** * \brief Handler van de User.Order subklasse. * * Deze klasse is de handler van de User.Order subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class OrderHandler extends MethodClass { public Vector<HashMap<String, Object>> List() throws StockPlayException { return List(""); } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Order, Integer> orDAO = getDAO().getOrderDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isBackendAdmin() || getRole().isTransactionAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, user); } else { filter = user; } } // Fetch and convert all orders Collection<com.kapti.data.Order> tOrders = orDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.Order tOrder : tOrders) { oVector.add(tOrder.toStruct( com.kapti.data.Order.Fields.ID, com.kapti.data.Order.Fields.USER, com.kapti.data.Order.Fields.TYPE, com.kapti.data.Order.Fields.ISIN, com.kapti.data.Order.Fields.AMOUNT, com.kapti.data.Order.Fields.STATUS, com.kapti.data.Order.Fields.CREATIONTIME, com.kapti.data.Order.Fields.EXECUTIONTIME, com.kapti.data.Order.Fields.EXPIRATIONTIME, com.kapti.data.Order.Fields.SECONDAIRYLIMIT, com.kapti.data.Order.Fields.PRICE)); } return oVector; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Order, Integer> orDAO = getDAO().getOrderDAO(); // Restrict the input hash if (!getRole().isBackendAdmin() || getRole().isTransactionAdmin()) { for (String tKey : iDetails.keySet()) { if (tKey.equalsIgnoreCase(Order.Fields.USER.toString())) { int tId = (Integer) iDetails.get(tKey); if (tId != getUser().getId()) throw new ServiceException(ServiceException.Type.UNAUTHORIZED); } } } // Instantiate a new order Order tOrder = Order.fromStruct(iDetails); tOrder.applyStruct(iDetails); tOrder.setStatus(OrderStatus.ACCEPTED); tOrder.setCreationTime(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return orDAO.create(tOrder); } public boolean Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Order, Integer> orDAO = getDAO().getOrderDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isBackendAdmin() || getRole().isTransactionAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); filter = Filter.merge(RelationAnd.class, base, user); } // Get the orders we need to modify Collection<com.kapti.data.Order> tOrders = orDAO.findByFilter(filter); // Now apply the cancelation boolean success = true; for (com.kapti.data.Order tOrder : tOrders) { tOrder.applyStruct(iDetails); if (!orDAO.update(tOrder)) success = false; } return success; } public int Cancel(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Order, Integer> orDAO = getDAO().getOrderDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isBackendAdmin() || getRole().isTransactionAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); filter = Filter.merge(RelationAnd.class, base, user); } // Get the exchanges we need to modify Collection<com.kapti.data.Order> tOrders = orDAO.findByFilter(filter); // Now apply the cancelation for (com.kapti.data.Order tOrder : tOrders) { tOrder.setStatus(OrderStatus.CANCELLED); orDAO.update(tOrder); } return 1; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/user/OrderHandler.java
1,762
/** * \brief Handler van de User.Order subklasse. * * Deze klasse is de handler van de User.Order subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */
block_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.user; import com.kapti.backend.api.MethodClass; import com.kapti.backend.helpers.DateHelper; import com.kapti.data.Order; import com.kapti.data.OrderStatus; import com.kapti.data.persistence.GenericDAO; import com.kapti.exceptions.ServiceException; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import com.kapti.filter.relation.RelationAnd; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.TimeZone; import java.util.Vector; /** * \brief <SUF>*/ public class OrderHandler extends MethodClass { public Vector<HashMap<String, Object>> List() throws StockPlayException { return List(""); } public Vector<HashMap<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Order, Integer> orDAO = getDAO().getOrderDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isBackendAdmin() || getRole().isTransactionAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, user); } else { filter = user; } } // Fetch and convert all orders Collection<com.kapti.data.Order> tOrders = orDAO.findByFilter(filter); Vector<HashMap<String, Object>> oVector = new Vector<HashMap<String, Object>>(); for (com.kapti.data.Order tOrder : tOrders) { oVector.add(tOrder.toStruct( com.kapti.data.Order.Fields.ID, com.kapti.data.Order.Fields.USER, com.kapti.data.Order.Fields.TYPE, com.kapti.data.Order.Fields.ISIN, com.kapti.data.Order.Fields.AMOUNT, com.kapti.data.Order.Fields.STATUS, com.kapti.data.Order.Fields.CREATIONTIME, com.kapti.data.Order.Fields.EXECUTIONTIME, com.kapti.data.Order.Fields.EXPIRATIONTIME, com.kapti.data.Order.Fields.SECONDAIRYLIMIT, com.kapti.data.Order.Fields.PRICE)); } return oVector; } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Order, Integer> orDAO = getDAO().getOrderDAO(); // Restrict the input hash if (!getRole().isBackendAdmin() || getRole().isTransactionAdmin()) { for (String tKey : iDetails.keySet()) { if (tKey.equalsIgnoreCase(Order.Fields.USER.toString())) { int tId = (Integer) iDetails.get(tKey); if (tId != getUser().getId()) throw new ServiceException(ServiceException.Type.UNAUTHORIZED); } } } // Instantiate a new order Order tOrder = Order.fromStruct(iDetails); tOrder.applyStruct(iDetails); tOrder.setStatus(OrderStatus.ACCEPTED); tOrder.setCreationTime(DateHelper.convertCalendar(Calendar.getInstance(), TimeZone.getTimeZone("GMT")).getTime()); return orDAO.create(tOrder); } public boolean Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Order, Integer> orDAO = getDAO().getOrderDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isBackendAdmin() || getRole().isTransactionAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); filter = Filter.merge(RelationAnd.class, base, user); } // Get the orders we need to modify Collection<com.kapti.data.Order> tOrders = orDAO.findByFilter(filter); // Now apply the cancelation boolean success = true; for (com.kapti.data.Order tOrder : tOrders) { tOrder.applyStruct(iDetails); if (!orDAO.update(tOrder)) success = false; } return success; } public int Cancel(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Order, Integer> orDAO = getDAO().getOrderDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole().isBackendAdmin() || getRole().isTransactionAdmin()) { filter = base; } else { Filter user = parser.parse("userid == '" + getUser().getId() + "'i"); filter = Filter.merge(RelationAnd.class, base, user); } // Get the exchanges we need to modify Collection<com.kapti.data.Order> tOrders = orDAO.findByFilter(filter); // Now apply the cancelation for (com.kapti.data.Order tOrder : tOrders) { tOrder.setStatus(OrderStatus.CANCELLED); orDAO.update(tOrder); } return 1; } }
201299_1
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericQuoteDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Vector; import com.kapti.data.Quote; import com.kapti.data.Security; import com.kapti.exceptions.FilterException; import com.kapti.filter.relation.RelationAnd; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.xmlrpc.XmlRpcException; /** * \brief Handler van de Finance.Security subklasse. * * Deze klasse is de handler van de Finance.Security subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class SecurityHandler extends MethodClass { // // Methodes // public List<Map<String, Object>> List() throws StockPlayException { return List(""); } public List<Map<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole() != null && getRole().isBackendAdmin()) { filter = base; } else { Filter visible = parser.parse("visible == 1"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, visible); } else { filter = visible; } } // Fetch and convert all Indexs Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Security tIndex : tSecurities) { oVector.add(tIndex.toStruct( com.kapti.data.Security.Fields.ISIN, com.kapti.data.Security.Fields.SYMBOL, com.kapti.data.Security.Fields.NAME, com.kapti.data.Security.Fields.EXCHANGE, com.kapti.data.Security.Fields.VISIBLE, com.kapti.data.Security.Fields.SUSPENDED)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the Indexs we need to modify Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Security tSecurity : tSecurities) { tSecurity.applyStruct(iDetails); tSecurityDAO.update(tSecurity); } // Deze waarde kan gebruikt worden bij de unit tests om te verzekeren // dat het correct aantal securities aangepast zijn. return tSecurities.size(); } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Instantiate a new security Security tSecurity = Security.fromStruct(iDetails); tSecurity.applyStruct(iDetails); tSecurityDAO.create(tSecurity); return 1; } public int Remove(String iFilter) throws StockPlayException { GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); for(com.kapti.data.Security security : tSecurities) tSecurityDAO.delete(security); return tSecurities.size(); } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen, gelimiteerd * tot een bepaalde range en "breedte". * @param iStart * @param iEnd * @param iSpan * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(Date iStart, Date iEnd, int iSpan, String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findSpanByFilter(iStart, iEnd, iSpan, filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> LatestQuotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findLatestByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } public List<Timestamp> QuoteRange(String isin) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); return tQuoteDAO.getRange(isin); } public double getHighest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getHighest(filter); } public double getLowest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getLowest(filter); } public int Update(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails); tQuote.applyStruct(iDetails); tQuoteDAO.create(tQuote); return 1; } public int UpdateBulk(Vector<HashMap<String, Object>> iQuotes) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); List<Quote> tQuotes = new ArrayList<Quote>(); for (HashMap<String, Object> iDetails : iQuotes) { HashMap<String, Object> iDetails2 = new HashMap<String, Object>(iDetails); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails2); tQuote.applyStruct(iDetails2); tQuotes.add(tQuote); } tQuoteDAO.createBulk(tQuotes); return 1; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/finance/SecurityHandler.java
2,936
/** * \brief Handler van de Finance.Security subklasse. * * Deze klasse is de handler van de Finance.Security subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */
block_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericQuoteDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Vector; import com.kapti.data.Quote; import com.kapti.data.Security; import com.kapti.exceptions.FilterException; import com.kapti.filter.relation.RelationAnd; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.xmlrpc.XmlRpcException; /** * \brief <SUF>*/ public class SecurityHandler extends MethodClass { // // Methodes // public List<Map<String, Object>> List() throws StockPlayException { return List(""); } public List<Map<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole() != null && getRole().isBackendAdmin()) { filter = base; } else { Filter visible = parser.parse("visible == 1"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, visible); } else { filter = visible; } } // Fetch and convert all Indexs Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Security tIndex : tSecurities) { oVector.add(tIndex.toStruct( com.kapti.data.Security.Fields.ISIN, com.kapti.data.Security.Fields.SYMBOL, com.kapti.data.Security.Fields.NAME, com.kapti.data.Security.Fields.EXCHANGE, com.kapti.data.Security.Fields.VISIBLE, com.kapti.data.Security.Fields.SUSPENDED)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the Indexs we need to modify Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Security tSecurity : tSecurities) { tSecurity.applyStruct(iDetails); tSecurityDAO.update(tSecurity); } // Deze waarde kan gebruikt worden bij de unit tests om te verzekeren // dat het correct aantal securities aangepast zijn. return tSecurities.size(); } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Instantiate a new security Security tSecurity = Security.fromStruct(iDetails); tSecurity.applyStruct(iDetails); tSecurityDAO.create(tSecurity); return 1; } public int Remove(String iFilter) throws StockPlayException { GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); for(com.kapti.data.Security security : tSecurities) tSecurityDAO.delete(security); return tSecurities.size(); } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen, gelimiteerd * tot een bepaalde range en "breedte". * @param iStart * @param iEnd * @param iSpan * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(Date iStart, Date iEnd, int iSpan, String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findSpanByFilter(iStart, iEnd, iSpan, filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> LatestQuotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findLatestByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } public List<Timestamp> QuoteRange(String isin) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); return tQuoteDAO.getRange(isin); } public double getHighest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getHighest(filter); } public double getLowest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getLowest(filter); } public int Update(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails); tQuote.applyStruct(iDetails); tQuoteDAO.create(tQuote); return 1; } public int UpdateBulk(Vector<HashMap<String, Object>> iQuotes) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); List<Quote> tQuotes = new ArrayList<Quote>(); for (HashMap<String, Object> iDetails : iQuotes) { HashMap<String, Object> iDetails2 = new HashMap<String, Object>(iDetails); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails2); tQuote.applyStruct(iDetails2); tQuotes.add(tQuote); } tQuoteDAO.createBulk(tQuotes); return 1; } }
201299_8
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericQuoteDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Vector; import com.kapti.data.Quote; import com.kapti.data.Security; import com.kapti.exceptions.FilterException; import com.kapti.filter.relation.RelationAnd; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.xmlrpc.XmlRpcException; /** * \brief Handler van de Finance.Security subklasse. * * Deze klasse is de handler van de Finance.Security subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class SecurityHandler extends MethodClass { // // Methodes // public List<Map<String, Object>> List() throws StockPlayException { return List(""); } public List<Map<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole() != null && getRole().isBackendAdmin()) { filter = base; } else { Filter visible = parser.parse("visible == 1"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, visible); } else { filter = visible; } } // Fetch and convert all Indexs Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Security tIndex : tSecurities) { oVector.add(tIndex.toStruct( com.kapti.data.Security.Fields.ISIN, com.kapti.data.Security.Fields.SYMBOL, com.kapti.data.Security.Fields.NAME, com.kapti.data.Security.Fields.EXCHANGE, com.kapti.data.Security.Fields.VISIBLE, com.kapti.data.Security.Fields.SUSPENDED)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the Indexs we need to modify Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Security tSecurity : tSecurities) { tSecurity.applyStruct(iDetails); tSecurityDAO.update(tSecurity); } // Deze waarde kan gebruikt worden bij de unit tests om te verzekeren // dat het correct aantal securities aangepast zijn. return tSecurities.size(); } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Instantiate a new security Security tSecurity = Security.fromStruct(iDetails); tSecurity.applyStruct(iDetails); tSecurityDAO.create(tSecurity); return 1; } public int Remove(String iFilter) throws StockPlayException { GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); for(com.kapti.data.Security security : tSecurities) tSecurityDAO.delete(security); return tSecurities.size(); } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen, gelimiteerd * tot een bepaalde range en "breedte". * @param iStart * @param iEnd * @param iSpan * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(Date iStart, Date iEnd, int iSpan, String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findSpanByFilter(iStart, iEnd, iSpan, filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> LatestQuotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findLatestByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } public List<Timestamp> QuoteRange(String isin) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); return tQuoteDAO.getRange(isin); } public double getHighest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getHighest(filter); } public double getLowest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getLowest(filter); } public int Update(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails); tQuote.applyStruct(iDetails); tQuoteDAO.create(tQuote); return 1; } public int UpdateBulk(Vector<HashMap<String, Object>> iQuotes) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); List<Quote> tQuotes = new ArrayList<Quote>(); for (HashMap<String, Object> iDetails : iQuotes) { HashMap<String, Object> iDetails2 = new HashMap<String, Object>(iDetails); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails2); tQuote.applyStruct(iDetails2); tQuotes.add(tQuote); } tQuoteDAO.createBulk(tQuotes); return 1; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/finance/SecurityHandler.java
2,936
// Deze waarde kan gebruikt worden bij de unit tests om te verzekeren
line_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericQuoteDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Vector; import com.kapti.data.Quote; import com.kapti.data.Security; import com.kapti.exceptions.FilterException; import com.kapti.filter.relation.RelationAnd; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.xmlrpc.XmlRpcException; /** * \brief Handler van de Finance.Security subklasse. * * Deze klasse is de handler van de Finance.Security subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class SecurityHandler extends MethodClass { // // Methodes // public List<Map<String, Object>> List() throws StockPlayException { return List(""); } public List<Map<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole() != null && getRole().isBackendAdmin()) { filter = base; } else { Filter visible = parser.parse("visible == 1"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, visible); } else { filter = visible; } } // Fetch and convert all Indexs Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Security tIndex : tSecurities) { oVector.add(tIndex.toStruct( com.kapti.data.Security.Fields.ISIN, com.kapti.data.Security.Fields.SYMBOL, com.kapti.data.Security.Fields.NAME, com.kapti.data.Security.Fields.EXCHANGE, com.kapti.data.Security.Fields.VISIBLE, com.kapti.data.Security.Fields.SUSPENDED)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the Indexs we need to modify Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Security tSecurity : tSecurities) { tSecurity.applyStruct(iDetails); tSecurityDAO.update(tSecurity); } // Deze waarde<SUF> // dat het correct aantal securities aangepast zijn. return tSecurities.size(); } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Instantiate a new security Security tSecurity = Security.fromStruct(iDetails); tSecurity.applyStruct(iDetails); tSecurityDAO.create(tSecurity); return 1; } public int Remove(String iFilter) throws StockPlayException { GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); for(com.kapti.data.Security security : tSecurities) tSecurityDAO.delete(security); return tSecurities.size(); } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen, gelimiteerd * tot een bepaalde range en "breedte". * @param iStart * @param iEnd * @param iSpan * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(Date iStart, Date iEnd, int iSpan, String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findSpanByFilter(iStart, iEnd, iSpan, filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> LatestQuotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findLatestByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } public List<Timestamp> QuoteRange(String isin) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); return tQuoteDAO.getRange(isin); } public double getHighest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getHighest(filter); } public double getLowest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getLowest(filter); } public int Update(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails); tQuote.applyStruct(iDetails); tQuoteDAO.create(tQuote); return 1; } public int UpdateBulk(Vector<HashMap<String, Object>> iQuotes) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); List<Quote> tQuotes = new ArrayList<Quote>(); for (HashMap<String, Object> iDetails : iQuotes) { HashMap<String, Object> iDetails2 = new HashMap<String, Object>(iDetails); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails2); tQuote.applyStruct(iDetails2); tQuotes.add(tQuote); } tQuoteDAO.createBulk(tQuotes); return 1; } }
201299_9
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericQuoteDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Vector; import com.kapti.data.Quote; import com.kapti.data.Security; import com.kapti.exceptions.FilterException; import com.kapti.filter.relation.RelationAnd; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.xmlrpc.XmlRpcException; /** * \brief Handler van de Finance.Security subklasse. * * Deze klasse is de handler van de Finance.Security subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class SecurityHandler extends MethodClass { // // Methodes // public List<Map<String, Object>> List() throws StockPlayException { return List(""); } public List<Map<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole() != null && getRole().isBackendAdmin()) { filter = base; } else { Filter visible = parser.parse("visible == 1"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, visible); } else { filter = visible; } } // Fetch and convert all Indexs Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Security tIndex : tSecurities) { oVector.add(tIndex.toStruct( com.kapti.data.Security.Fields.ISIN, com.kapti.data.Security.Fields.SYMBOL, com.kapti.data.Security.Fields.NAME, com.kapti.data.Security.Fields.EXCHANGE, com.kapti.data.Security.Fields.VISIBLE, com.kapti.data.Security.Fields.SUSPENDED)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the Indexs we need to modify Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Security tSecurity : tSecurities) { tSecurity.applyStruct(iDetails); tSecurityDAO.update(tSecurity); } // Deze waarde kan gebruikt worden bij de unit tests om te verzekeren // dat het correct aantal securities aangepast zijn. return tSecurities.size(); } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Instantiate a new security Security tSecurity = Security.fromStruct(iDetails); tSecurity.applyStruct(iDetails); tSecurityDAO.create(tSecurity); return 1; } public int Remove(String iFilter) throws StockPlayException { GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); for(com.kapti.data.Security security : tSecurities) tSecurityDAO.delete(security); return tSecurities.size(); } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen, gelimiteerd * tot een bepaalde range en "breedte". * @param iStart * @param iEnd * @param iSpan * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(Date iStart, Date iEnd, int iSpan, String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findSpanByFilter(iStart, iEnd, iSpan, filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> LatestQuotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findLatestByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } public List<Timestamp> QuoteRange(String isin) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); return tQuoteDAO.getRange(isin); } public double getHighest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getHighest(filter); } public double getLowest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getLowest(filter); } public int Update(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails); tQuote.applyStruct(iDetails); tQuoteDAO.create(tQuote); return 1; } public int UpdateBulk(Vector<HashMap<String, Object>> iQuotes) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); List<Quote> tQuotes = new ArrayList<Quote>(); for (HashMap<String, Object> iDetails : iQuotes) { HashMap<String, Object> iDetails2 = new HashMap<String, Object>(iDetails); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails2); tQuote.applyStruct(iDetails2); tQuotes.add(tQuote); } tQuoteDAO.createBulk(tQuotes); return 1; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/finance/SecurityHandler.java
2,936
// dat het correct aantal securities aangepast zijn.
line_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericQuoteDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Vector; import com.kapti.data.Quote; import com.kapti.data.Security; import com.kapti.exceptions.FilterException; import com.kapti.filter.relation.RelationAnd; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.xmlrpc.XmlRpcException; /** * \brief Handler van de Finance.Security subklasse. * * Deze klasse is de handler van de Finance.Security subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class SecurityHandler extends MethodClass { // // Methodes // public List<Map<String, Object>> List() throws StockPlayException { return List(""); } public List<Map<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole() != null && getRole().isBackendAdmin()) { filter = base; } else { Filter visible = parser.parse("visible == 1"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, visible); } else { filter = visible; } } // Fetch and convert all Indexs Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Security tIndex : tSecurities) { oVector.add(tIndex.toStruct( com.kapti.data.Security.Fields.ISIN, com.kapti.data.Security.Fields.SYMBOL, com.kapti.data.Security.Fields.NAME, com.kapti.data.Security.Fields.EXCHANGE, com.kapti.data.Security.Fields.VISIBLE, com.kapti.data.Security.Fields.SUSPENDED)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the Indexs we need to modify Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Security tSecurity : tSecurities) { tSecurity.applyStruct(iDetails); tSecurityDAO.update(tSecurity); } // Deze waarde kan gebruikt worden bij de unit tests om te verzekeren // dat het<SUF> return tSecurities.size(); } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Instantiate a new security Security tSecurity = Security.fromStruct(iDetails); tSecurity.applyStruct(iDetails); tSecurityDAO.create(tSecurity); return 1; } public int Remove(String iFilter) throws StockPlayException { GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); for(com.kapti.data.Security security : tSecurities) tSecurityDAO.delete(security); return tSecurities.size(); } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen, gelimiteerd * tot een bepaalde range en "breedte". * @param iStart * @param iEnd * @param iSpan * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(Date iStart, Date iEnd, int iSpan, String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findSpanByFilter(iStart, iEnd, iSpan, filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> LatestQuotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findLatestByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } public List<Timestamp> QuoteRange(String isin) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); return tQuoteDAO.getRange(isin); } public double getHighest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getHighest(filter); } public double getLowest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getLowest(filter); } public int Update(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails); tQuote.applyStruct(iDetails); tQuoteDAO.create(tQuote); return 1; } public int UpdateBulk(Vector<HashMap<String, Object>> iQuotes) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); List<Quote> tQuotes = new ArrayList<Quote>(); for (HashMap<String, Object> iDetails : iQuotes) { HashMap<String, Object> iDetails2 = new HashMap<String, Object>(iDetails); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails2); tQuote.applyStruct(iDetails2); tQuotes.add(tQuote); } tQuoteDAO.createBulk(tQuotes); return 1; } }
201299_15
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericQuoteDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Vector; import com.kapti.data.Quote; import com.kapti.data.Security; import com.kapti.exceptions.FilterException; import com.kapti.filter.relation.RelationAnd; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.xmlrpc.XmlRpcException; /** * \brief Handler van de Finance.Security subklasse. * * Deze klasse is de handler van de Finance.Security subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class SecurityHandler extends MethodClass { // // Methodes // public List<Map<String, Object>> List() throws StockPlayException { return List(""); } public List<Map<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole() != null && getRole().isBackendAdmin()) { filter = base; } else { Filter visible = parser.parse("visible == 1"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, visible); } else { filter = visible; } } // Fetch and convert all Indexs Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Security tIndex : tSecurities) { oVector.add(tIndex.toStruct( com.kapti.data.Security.Fields.ISIN, com.kapti.data.Security.Fields.SYMBOL, com.kapti.data.Security.Fields.NAME, com.kapti.data.Security.Fields.EXCHANGE, com.kapti.data.Security.Fields.VISIBLE, com.kapti.data.Security.Fields.SUSPENDED)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the Indexs we need to modify Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Security tSecurity : tSecurities) { tSecurity.applyStruct(iDetails); tSecurityDAO.update(tSecurity); } // Deze waarde kan gebruikt worden bij de unit tests om te verzekeren // dat het correct aantal securities aangepast zijn. return tSecurities.size(); } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Instantiate a new security Security tSecurity = Security.fromStruct(iDetails); tSecurity.applyStruct(iDetails); tSecurityDAO.create(tSecurity); return 1; } public int Remove(String iFilter) throws StockPlayException { GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); for(com.kapti.data.Security security : tSecurities) tSecurityDAO.delete(security); return tSecurities.size(); } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen, gelimiteerd * tot een bepaalde range en "breedte". * @param iStart * @param iEnd * @param iSpan * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(Date iStart, Date iEnd, int iSpan, String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findSpanByFilter(iStart, iEnd, iSpan, filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> LatestQuotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findLatestByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } public List<Timestamp> QuoteRange(String isin) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); return tQuoteDAO.getRange(isin); } public double getHighest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getHighest(filter); } public double getLowest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getLowest(filter); } public int Update(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails); tQuote.applyStruct(iDetails); tQuoteDAO.create(tQuote); return 1; } public int UpdateBulk(Vector<HashMap<String, Object>> iQuotes) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); List<Quote> tQuotes = new ArrayList<Quote>(); for (HashMap<String, Object> iDetails : iQuotes) { HashMap<String, Object> iDetails2 = new HashMap<String, Object>(iDetails); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails2); tQuote.applyStruct(iDetails2); tQuotes.add(tQuote); } tQuoteDAO.createBulk(tQuotes); return 1; } }
maleadt/stockplay
src/backend/src/java/com/kapti/backend/api/finance/SecurityHandler.java
2,936
/** * Geeft alle koersen die aan aan de opgegeven filter voldoen, gelimiteerd * tot een bepaalde range en "breedte". * @param iStart * @param iEnd * @param iSpan * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */
block_comment
nl
/* * Copyright (c) 2010 StockPlay development team * All rights reserved. * * 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. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.kapti.backend.api.finance; import com.kapti.backend.api.MethodClass; import com.kapti.data.persistence.GenericDAO; import com.kapti.data.persistence.GenericQuoteDAO; import com.kapti.exceptions.StockPlayException; import com.kapti.filter.Filter; import com.kapti.filter.parsing.Parser; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Vector; import com.kapti.data.Quote; import com.kapti.data.Security; import com.kapti.exceptions.FilterException; import com.kapti.filter.relation.RelationAnd; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import org.apache.xmlrpc.XmlRpcException; /** * \brief Handler van de Finance.Security subklasse. * * Deze klasse is de handler van de Finance.Security subklasse. Ze staat in * voor de verwerking van aanroepen van functies die zich in deze klasse * bevinden, lokaal de correcte aanvragen uit te voeren, en het resultaat * op conforme wijze terug te sturen. */ public class SecurityHandler extends MethodClass { // // Methodes // public List<Map<String, Object>> List() throws StockPlayException { return List(""); } public List<Map<String, Object>> List(String iFilter) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Create a filter Parser parser = Parser.getInstance(); Filter filter = null; Filter base = parser.parse(iFilter); if (getRole() != null && getRole().isBackendAdmin()) { filter = base; } else { Filter visible = parser.parse("visible == 1"); if (!base.empty()) { filter = Filter.merge(RelationAnd.class, base, visible); } else { filter = visible; } } // Fetch and convert all Indexs Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Security tIndex : tSecurities) { oVector.add(tIndex.toStruct( com.kapti.data.Security.Fields.ISIN, com.kapti.data.Security.Fields.SYMBOL, com.kapti.data.Security.Fields.NAME, com.kapti.data.Security.Fields.EXCHANGE, com.kapti.data.Security.Fields.VISIBLE, com.kapti.data.Security.Fields.SUSPENDED)); } return oVector; } public int Modify(String iFilter, HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Get the Indexs we need to modify Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); // Now apply the new properties for (com.kapti.data.Security tSecurity : tSecurities) { tSecurity.applyStruct(iDetails); tSecurityDAO.update(tSecurity); } // Deze waarde kan gebruikt worden bij de unit tests om te verzekeren // dat het correct aantal securities aangepast zijn. return tSecurities.size(); } public int Create(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); // Instantiate a new security Security tSecurity = Security.fromStruct(iDetails); tSecurity.applyStruct(iDetails); tSecurityDAO.create(tSecurity); return 1; } public int Remove(String iFilter) throws StockPlayException { GenericDAO<com.kapti.data.Security, String> tSecurityDAO = getDAO().getSecurityDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); Collection<com.kapti.data.Security> tSecurities = tSecurityDAO.findByFilter(filter); for(com.kapti.data.Security security : tSecurities) tSecurityDAO.delete(security); return tSecurities.size(); } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> Quotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen<SUF>*/ public List<Map<String, Object>> Quotes(Date iStart, Date iEnd, int iSpan, String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findSpanByFilter(iStart, iEnd, iSpan, filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } /** * Geeft alle koersen die aan aan de opgegeven filter voldoen * @param iFilter * @return * @throws XmlRpcException * @throws StockPlayException * @throws FilterException * @throws ParserException */ public List<Map<String, Object>> LatestQuotes(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); // Fetch and convert all Indexs Collection<com.kapti.data.Quote> tQuotes = tQuoteDAO.findLatestByFilter(filter); Vector<Map<String, Object>> oVector = new Vector<Map<String, Object>>(); for (com.kapti.data.Quote tQuote : tQuotes) { oVector.add(tQuote.toStruct( Quote.Fields.ISIN, Quote.Fields.TIME, Quote.Fields.PRICE, Quote.Fields.VOLUME, Quote.Fields.BID, Quote.Fields.ASK, Quote.Fields.LOW, Quote.Fields.HIGH, Quote.Fields.OPEN)); } return oVector; } public List<Timestamp> QuoteRange(String isin) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); return tQuoteDAO.getRange(isin); } public double getHighest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getHighest(filter); } public double getLowest(String iFilter) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); Parser parser = Parser.getInstance(); Filter filter = parser.parse(iFilter); return tQuoteDAO.getLowest(filter); } public int Update(HashMap<String, Object> iDetails) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails); tQuote.applyStruct(iDetails); tQuoteDAO.create(tQuote); return 1; } public int UpdateBulk(Vector<HashMap<String, Object>> iQuotes) throws StockPlayException { // Get DAO reference GenericQuoteDAO tQuoteDAO = getDAO().getQuoteDAO(); List<Quote> tQuotes = new ArrayList<Quote>(); for (HashMap<String, Object> iDetails : iQuotes) { HashMap<String, Object> iDetails2 = new HashMap<String, Object>(iDetails); // Instantiate a new quote Quote tQuote = Quote.fromStruct(iDetails2); tQuote.applyStruct(iDetails2); tQuotes.add(tQuote); } tQuoteDAO.createBulk(tQuotes); return 1; } }
201303_2
package org.vanbest.xmltv; /* Copyright (c) 2012-2015 Jan-Pascal van Best <[email protected]> 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. The full license text can be found in the LICENSE file. */ import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.log4j.Level; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class ZiggoGids extends AbstractEPGSource implements EPGSource { private static final String base_data_root="https://api2.ziggo-apps.nl/base_data"; private static final String epg_data_root="https://api2.ziggo-apps.nl/programs"; private static final String programs_data_root="https://api2.ziggo-apps.nl/program_details"; private static final String channel_image_root="https://static.ziggo-apps.nl/images/channels/"; private static final String program_image_root="https://static.ziggo-apps.nl/images/programs/"; // NOTE: // the base_data json object also contains information about program Genres // IDs, icon base urls, and kijkwijzer IDs private static final int MAX_PROGRAMMES_PER_DAY = 9999; private static final int MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS = 7; //private static final int MAX_CHANNELS_PER_REQUEST = 25; public final static String NAME="ziggogids.nl"; static Logger logger = Logger.getLogger(ZiggoGids.class); class Statics { Map<String,String> genre; // id => name Map<String,String> kijkwijzer; // id => description; FIXME: also contains icons } private Statics statics = null; public ZiggoGids(Config config) { super(config); } public String getName() { return NAME; } // https://api2.ziggo-apps.nl/programs?channelIDs=1&date=2015-02-20+8&period=3 // period: number of hours ahead to fetch program data // TODO: multiple channels, "channelIDs=1,2,3" public static URL programmeUrl(Channel channel, int day, int hour, int period) throws Exception { StringBuilder s = new StringBuilder(epg_data_root); s.append("?channelIDs="); s.append(channel.id); GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, 0); String date = new SimpleDateFormat("yyyy-MM-dd+HH").format(cal.getTime()); s.append("&date="+date); s.append("&period="+period); return new URL(s.toString()); } // https://api2.ziggo-apps.nl/program_details?programID=1011424477400760329465668 public static URL detailUrl(String id) throws Exception { StringBuilder s = new StringBuilder(programs_data_root); s.append("?programID="); s.append(id); return new URL(s.toString()); } public void fetchStatics() { if (statics != null) return; URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating ziggo base data url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo base data from "+base_data_root, e); return; } statics = new Statics(); statics.genre = new HashMap<String,String>(); statics.kijkwijzer = new HashMap<String,String>(); JSONArray genres = base_data.getJSONArray("Genres"); for(int i=0; i<genres.size(); i++) { JSONObject genre = genres.getJSONObject(i); logger.debug("Genre " + genre.getString("id") + ": " + genre.getString("name")); statics.genre.put(genre.getString("id"), genre.getString("name")); } JSONArray parentals = base_data.getJSONArray("ParentalGuidances"); for(int i=0; i<parentals.size(); i++) { JSONObject parental = parentals.getJSONObject(i); String rating = parental.getString("name").replace("Kijkwijzer","").trim(); logger.debug("Rating " + parental.getString("id") + ": " + rating); statics.kijkwijzer.put(parental.getString("id"), rating); } } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getChannels() */ @Override public List<Channel> getChannels() { List<Channel> result = new ArrayList<Channel>(100); URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating horizon channel list url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo channel list from "+base_data_root, e); return result; } logger.debug("ziggogids channels json: " + base_data.toString()); JSONArray channels = base_data.getJSONArray("Channels"); for(int i=0; i < channels.size(); i++) { JSONObject zender = channels.getJSONObject(i); String name = zender.getString("name"); String id = zender.getString("id"); String xmltv = id + "." + getName(); String icon = channel_image_root + zender.getString("icon"); Channel c = Channel.getChannel(getName(), id, xmltv, name); c.addIcon(icon); result.add(c); } return result; } private void fillDetails(String id, Programme result) throws Exception { URL url = detailUrl(id); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Program"); JSONObject program = programs.getJSONObject(0); if (program.has("genre")) { String genre = statics.genre.get("" + program.getInt("genre")); if (genre != null) { result.addCategory(config.translateCategory(genre)); } // logger.debug(" FIXME genre: " + program.getInt("genre")); } JSONArray detail_list = json.getJSONArray("ProgramDetails"); JSONObject details = detail_list.getJSONObject(0); if (details.has("description")) { result.addDescription(details.getString("description")); } if (details.has("parentalGuidances")) { // logger.debug(" FIXME kijkwijzer " + details.getJSONArray("parentalGuidances").toString()); JSONArray guidances = details.getJSONArray("parentalGuidances"); List<String> kijkwijzers = new ArrayList<String>(guidances.size()); for(int i=0; i<guidances.size(); i++) { kijkwijzers.add(statics.kijkwijzer.get("" + guidances.getInt(i))); } result.addRating("kijkwijzer", StringUtils.join(kijkwijzers, ",")); } if (details.has("rerun")) { // TODO // logger.debug(" FIXME rerun: " + details.getString("rerun")); boolean rerun = details.getString("rerun").equals("true"); if (rerun) { result.setPreviouslyShown(); } } if (details.has("infoUrl")) { String info = details.getString("infoUrl"); if (info != null && ! info.isEmpty()) { result.addUrl(info); } } /* ppe: some kind of pay-per-view if (details.has("ppeUrl")) { String ppe = details.getString("ppeUrl"); if (ppe != null && ! ppe.isEmpty()) { logger.debug(" FIXME ppe URL: " + ppe); } } */ } /* { "title" : "NOS Journaal", "inHome" : "1", "endDateTime" : "2015-02-20 19:30:00", "id" : "1011424458800760329485668", "startDate" : "2015-02-20", "startDateTime" : "2015-02-20 19:00:00", "outOfCountry" : "0", "genre" : 12, "series_key" : "1_NOS Journaal", "outOfHome" : "1", "channel" : "1" }, */ private Programme programmeFromJSON(JSONObject json, boolean fetchDetails) throws Exception { String id = json.getString("id"); Programme result = cache.get(getName(), id); boolean cached = (result != null); boolean doNotCache = false; if (result == null) { stats.cacheMisses++; result = new Programme(); if (json.has("title")){ result.addTitle(json.getString("title")); } } else { stats.cacheHits++; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", new Locale("nl")); //Calendar cal = df.getCalendar(); //cal.setTimeZone(TimeZone.getTimeZone("UTC")); //df.setCalendar(cal); df.setTimeZone(TimeZone.getTimeZone("UTC")); result.startTime = df.parse(json.getString("startDateTime")); result.endTime = df.parse(json.getString("endDateTime")); if (fetchDetails && !cached) { // TODO also read details if those have not been cached fillDetails(id, result); } if (!cached) { // FIXME where to do this? cache.put(getName(), id, result); } logger.debug(result); return result; } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getProgrammes(java.util.List, int, * boolean) */ @Override public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception { fetchStatics(); List<Programme> result = new ArrayList<Programme>(); if (day > MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS) { return result; // empty list } // TODO fetch multiple channels in one go for (Channel c : channels) { // start day hour=0 with 24 hours ahead URL url = programmeUrl(c, day, 0, 24); logger.debug("url: "+url); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Programs"); for (int i = 0; i < programs.size(); i++) { JSONObject program = programs.getJSONObject(i); Programme p = programmeFromJSON(program, config.fetchDetails); p.channel = c.getXmltvChannelId(); result.add(p); } } return result; } /** * @param args */ public static void main(String[] args) { Config config = Config.getDefaultConfig(); logger.setLevel(Level.TRACE); ZiggoGids gids = new ZiggoGids(config); try { List<Channel> channels = gids.getChannels(); System.out.println("Channels: " + channels); XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(new FileWriter("ziggogids.xml")); writer.writeStartDocument(); writer.writeCharacters("\n"); writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">"); writer.writeCharacters("\n"); writer.writeStartElement("tv"); //List<Channel> my_channels = channels; //List<Channel> my_channels = channels.subList(0, 15); List<Channel> my_channels = channels.subList(0, 4); for (Channel c : my_channels) { c.serialize(writer, true); } writer.flush(); List<Programme> programmes = gids.getProgrammes(my_channels, 2); for (Programme p : programmes) { p.serialize(writer); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); if (!config.quiet) { EPGSource.Stats stats = gids.getStats(); System.out.println("Number of programmes from cache: " + stats.cacheHits); System.out.println("Number of programmes fetched: " + stats.cacheMisses); System.out.println("Number of fetch errors: " + stats.fetchErrors); } gids.close(); } catch (Exception e) { logger.error("Error in ziggogids testing", e); } } }
janpascal/tv_grab_nl_java
src/main/java/org/vanbest/xmltv/ZiggoGids.java
3,702
// IDs, icon base urls, and kijkwijzer IDs
line_comment
nl
package org.vanbest.xmltv; /* Copyright (c) 2012-2015 Jan-Pascal van Best <[email protected]> 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. The full license text can be found in the LICENSE file. */ import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.log4j.Level; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class ZiggoGids extends AbstractEPGSource implements EPGSource { private static final String base_data_root="https://api2.ziggo-apps.nl/base_data"; private static final String epg_data_root="https://api2.ziggo-apps.nl/programs"; private static final String programs_data_root="https://api2.ziggo-apps.nl/program_details"; private static final String channel_image_root="https://static.ziggo-apps.nl/images/channels/"; private static final String program_image_root="https://static.ziggo-apps.nl/images/programs/"; // NOTE: // the base_data json object also contains information about program Genres // IDs, icon<SUF> private static final int MAX_PROGRAMMES_PER_DAY = 9999; private static final int MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS = 7; //private static final int MAX_CHANNELS_PER_REQUEST = 25; public final static String NAME="ziggogids.nl"; static Logger logger = Logger.getLogger(ZiggoGids.class); class Statics { Map<String,String> genre; // id => name Map<String,String> kijkwijzer; // id => description; FIXME: also contains icons } private Statics statics = null; public ZiggoGids(Config config) { super(config); } public String getName() { return NAME; } // https://api2.ziggo-apps.nl/programs?channelIDs=1&date=2015-02-20+8&period=3 // period: number of hours ahead to fetch program data // TODO: multiple channels, "channelIDs=1,2,3" public static URL programmeUrl(Channel channel, int day, int hour, int period) throws Exception { StringBuilder s = new StringBuilder(epg_data_root); s.append("?channelIDs="); s.append(channel.id); GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, 0); String date = new SimpleDateFormat("yyyy-MM-dd+HH").format(cal.getTime()); s.append("&date="+date); s.append("&period="+period); return new URL(s.toString()); } // https://api2.ziggo-apps.nl/program_details?programID=1011424477400760329465668 public static URL detailUrl(String id) throws Exception { StringBuilder s = new StringBuilder(programs_data_root); s.append("?programID="); s.append(id); return new URL(s.toString()); } public void fetchStatics() { if (statics != null) return; URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating ziggo base data url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo base data from "+base_data_root, e); return; } statics = new Statics(); statics.genre = new HashMap<String,String>(); statics.kijkwijzer = new HashMap<String,String>(); JSONArray genres = base_data.getJSONArray("Genres"); for(int i=0; i<genres.size(); i++) { JSONObject genre = genres.getJSONObject(i); logger.debug("Genre " + genre.getString("id") + ": " + genre.getString("name")); statics.genre.put(genre.getString("id"), genre.getString("name")); } JSONArray parentals = base_data.getJSONArray("ParentalGuidances"); for(int i=0; i<parentals.size(); i++) { JSONObject parental = parentals.getJSONObject(i); String rating = parental.getString("name").replace("Kijkwijzer","").trim(); logger.debug("Rating " + parental.getString("id") + ": " + rating); statics.kijkwijzer.put(parental.getString("id"), rating); } } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getChannels() */ @Override public List<Channel> getChannels() { List<Channel> result = new ArrayList<Channel>(100); URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating horizon channel list url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo channel list from "+base_data_root, e); return result; } logger.debug("ziggogids channels json: " + base_data.toString()); JSONArray channels = base_data.getJSONArray("Channels"); for(int i=0; i < channels.size(); i++) { JSONObject zender = channels.getJSONObject(i); String name = zender.getString("name"); String id = zender.getString("id"); String xmltv = id + "." + getName(); String icon = channel_image_root + zender.getString("icon"); Channel c = Channel.getChannel(getName(), id, xmltv, name); c.addIcon(icon); result.add(c); } return result; } private void fillDetails(String id, Programme result) throws Exception { URL url = detailUrl(id); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Program"); JSONObject program = programs.getJSONObject(0); if (program.has("genre")) { String genre = statics.genre.get("" + program.getInt("genre")); if (genre != null) { result.addCategory(config.translateCategory(genre)); } // logger.debug(" FIXME genre: " + program.getInt("genre")); } JSONArray detail_list = json.getJSONArray("ProgramDetails"); JSONObject details = detail_list.getJSONObject(0); if (details.has("description")) { result.addDescription(details.getString("description")); } if (details.has("parentalGuidances")) { // logger.debug(" FIXME kijkwijzer " + details.getJSONArray("parentalGuidances").toString()); JSONArray guidances = details.getJSONArray("parentalGuidances"); List<String> kijkwijzers = new ArrayList<String>(guidances.size()); for(int i=0; i<guidances.size(); i++) { kijkwijzers.add(statics.kijkwijzer.get("" + guidances.getInt(i))); } result.addRating("kijkwijzer", StringUtils.join(kijkwijzers, ",")); } if (details.has("rerun")) { // TODO // logger.debug(" FIXME rerun: " + details.getString("rerun")); boolean rerun = details.getString("rerun").equals("true"); if (rerun) { result.setPreviouslyShown(); } } if (details.has("infoUrl")) { String info = details.getString("infoUrl"); if (info != null && ! info.isEmpty()) { result.addUrl(info); } } /* ppe: some kind of pay-per-view if (details.has("ppeUrl")) { String ppe = details.getString("ppeUrl"); if (ppe != null && ! ppe.isEmpty()) { logger.debug(" FIXME ppe URL: " + ppe); } } */ } /* { "title" : "NOS Journaal", "inHome" : "1", "endDateTime" : "2015-02-20 19:30:00", "id" : "1011424458800760329485668", "startDate" : "2015-02-20", "startDateTime" : "2015-02-20 19:00:00", "outOfCountry" : "0", "genre" : 12, "series_key" : "1_NOS Journaal", "outOfHome" : "1", "channel" : "1" }, */ private Programme programmeFromJSON(JSONObject json, boolean fetchDetails) throws Exception { String id = json.getString("id"); Programme result = cache.get(getName(), id); boolean cached = (result != null); boolean doNotCache = false; if (result == null) { stats.cacheMisses++; result = new Programme(); if (json.has("title")){ result.addTitle(json.getString("title")); } } else { stats.cacheHits++; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", new Locale("nl")); //Calendar cal = df.getCalendar(); //cal.setTimeZone(TimeZone.getTimeZone("UTC")); //df.setCalendar(cal); df.setTimeZone(TimeZone.getTimeZone("UTC")); result.startTime = df.parse(json.getString("startDateTime")); result.endTime = df.parse(json.getString("endDateTime")); if (fetchDetails && !cached) { // TODO also read details if those have not been cached fillDetails(id, result); } if (!cached) { // FIXME where to do this? cache.put(getName(), id, result); } logger.debug(result); return result; } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getProgrammes(java.util.List, int, * boolean) */ @Override public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception { fetchStatics(); List<Programme> result = new ArrayList<Programme>(); if (day > MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS) { return result; // empty list } // TODO fetch multiple channels in one go for (Channel c : channels) { // start day hour=0 with 24 hours ahead URL url = programmeUrl(c, day, 0, 24); logger.debug("url: "+url); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Programs"); for (int i = 0; i < programs.size(); i++) { JSONObject program = programs.getJSONObject(i); Programme p = programmeFromJSON(program, config.fetchDetails); p.channel = c.getXmltvChannelId(); result.add(p); } } return result; } /** * @param args */ public static void main(String[] args) { Config config = Config.getDefaultConfig(); logger.setLevel(Level.TRACE); ZiggoGids gids = new ZiggoGids(config); try { List<Channel> channels = gids.getChannels(); System.out.println("Channels: " + channels); XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(new FileWriter("ziggogids.xml")); writer.writeStartDocument(); writer.writeCharacters("\n"); writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">"); writer.writeCharacters("\n"); writer.writeStartElement("tv"); //List<Channel> my_channels = channels; //List<Channel> my_channels = channels.subList(0, 15); List<Channel> my_channels = channels.subList(0, 4); for (Channel c : my_channels) { c.serialize(writer, true); } writer.flush(); List<Programme> programmes = gids.getProgrammes(my_channels, 2); for (Programme p : programmes) { p.serialize(writer); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); if (!config.quiet) { EPGSource.Stats stats = gids.getStats(); System.out.println("Number of programmes from cache: " + stats.cacheHits); System.out.println("Number of programmes fetched: " + stats.cacheMisses); System.out.println("Number of fetch errors: " + stats.fetchErrors); } gids.close(); } catch (Exception e) { logger.error("Error in ziggogids testing", e); } } }
201303_8
package org.vanbest.xmltv; /* Copyright (c) 2012-2015 Jan-Pascal van Best <[email protected]> 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. The full license text can be found in the LICENSE file. */ import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.log4j.Level; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class ZiggoGids extends AbstractEPGSource implements EPGSource { private static final String base_data_root="https://api2.ziggo-apps.nl/base_data"; private static final String epg_data_root="https://api2.ziggo-apps.nl/programs"; private static final String programs_data_root="https://api2.ziggo-apps.nl/program_details"; private static final String channel_image_root="https://static.ziggo-apps.nl/images/channels/"; private static final String program_image_root="https://static.ziggo-apps.nl/images/programs/"; // NOTE: // the base_data json object also contains information about program Genres // IDs, icon base urls, and kijkwijzer IDs private static final int MAX_PROGRAMMES_PER_DAY = 9999; private static final int MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS = 7; //private static final int MAX_CHANNELS_PER_REQUEST = 25; public final static String NAME="ziggogids.nl"; static Logger logger = Logger.getLogger(ZiggoGids.class); class Statics { Map<String,String> genre; // id => name Map<String,String> kijkwijzer; // id => description; FIXME: also contains icons } private Statics statics = null; public ZiggoGids(Config config) { super(config); } public String getName() { return NAME; } // https://api2.ziggo-apps.nl/programs?channelIDs=1&date=2015-02-20+8&period=3 // period: number of hours ahead to fetch program data // TODO: multiple channels, "channelIDs=1,2,3" public static URL programmeUrl(Channel channel, int day, int hour, int period) throws Exception { StringBuilder s = new StringBuilder(epg_data_root); s.append("?channelIDs="); s.append(channel.id); GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, 0); String date = new SimpleDateFormat("yyyy-MM-dd+HH").format(cal.getTime()); s.append("&date="+date); s.append("&period="+period); return new URL(s.toString()); } // https://api2.ziggo-apps.nl/program_details?programID=1011424477400760329465668 public static URL detailUrl(String id) throws Exception { StringBuilder s = new StringBuilder(programs_data_root); s.append("?programID="); s.append(id); return new URL(s.toString()); } public void fetchStatics() { if (statics != null) return; URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating ziggo base data url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo base data from "+base_data_root, e); return; } statics = new Statics(); statics.genre = new HashMap<String,String>(); statics.kijkwijzer = new HashMap<String,String>(); JSONArray genres = base_data.getJSONArray("Genres"); for(int i=0; i<genres.size(); i++) { JSONObject genre = genres.getJSONObject(i); logger.debug("Genre " + genre.getString("id") + ": " + genre.getString("name")); statics.genre.put(genre.getString("id"), genre.getString("name")); } JSONArray parentals = base_data.getJSONArray("ParentalGuidances"); for(int i=0; i<parentals.size(); i++) { JSONObject parental = parentals.getJSONObject(i); String rating = parental.getString("name").replace("Kijkwijzer","").trim(); logger.debug("Rating " + parental.getString("id") + ": " + rating); statics.kijkwijzer.put(parental.getString("id"), rating); } } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getChannels() */ @Override public List<Channel> getChannels() { List<Channel> result = new ArrayList<Channel>(100); URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating horizon channel list url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo channel list from "+base_data_root, e); return result; } logger.debug("ziggogids channels json: " + base_data.toString()); JSONArray channels = base_data.getJSONArray("Channels"); for(int i=0; i < channels.size(); i++) { JSONObject zender = channels.getJSONObject(i); String name = zender.getString("name"); String id = zender.getString("id"); String xmltv = id + "." + getName(); String icon = channel_image_root + zender.getString("icon"); Channel c = Channel.getChannel(getName(), id, xmltv, name); c.addIcon(icon); result.add(c); } return result; } private void fillDetails(String id, Programme result) throws Exception { URL url = detailUrl(id); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Program"); JSONObject program = programs.getJSONObject(0); if (program.has("genre")) { String genre = statics.genre.get("" + program.getInt("genre")); if (genre != null) { result.addCategory(config.translateCategory(genre)); } // logger.debug(" FIXME genre: " + program.getInt("genre")); } JSONArray detail_list = json.getJSONArray("ProgramDetails"); JSONObject details = detail_list.getJSONObject(0); if (details.has("description")) { result.addDescription(details.getString("description")); } if (details.has("parentalGuidances")) { // logger.debug(" FIXME kijkwijzer " + details.getJSONArray("parentalGuidances").toString()); JSONArray guidances = details.getJSONArray("parentalGuidances"); List<String> kijkwijzers = new ArrayList<String>(guidances.size()); for(int i=0; i<guidances.size(); i++) { kijkwijzers.add(statics.kijkwijzer.get("" + guidances.getInt(i))); } result.addRating("kijkwijzer", StringUtils.join(kijkwijzers, ",")); } if (details.has("rerun")) { // TODO // logger.debug(" FIXME rerun: " + details.getString("rerun")); boolean rerun = details.getString("rerun").equals("true"); if (rerun) { result.setPreviouslyShown(); } } if (details.has("infoUrl")) { String info = details.getString("infoUrl"); if (info != null && ! info.isEmpty()) { result.addUrl(info); } } /* ppe: some kind of pay-per-view if (details.has("ppeUrl")) { String ppe = details.getString("ppeUrl"); if (ppe != null && ! ppe.isEmpty()) { logger.debug(" FIXME ppe URL: " + ppe); } } */ } /* { "title" : "NOS Journaal", "inHome" : "1", "endDateTime" : "2015-02-20 19:30:00", "id" : "1011424458800760329485668", "startDate" : "2015-02-20", "startDateTime" : "2015-02-20 19:00:00", "outOfCountry" : "0", "genre" : 12, "series_key" : "1_NOS Journaal", "outOfHome" : "1", "channel" : "1" }, */ private Programme programmeFromJSON(JSONObject json, boolean fetchDetails) throws Exception { String id = json.getString("id"); Programme result = cache.get(getName(), id); boolean cached = (result != null); boolean doNotCache = false; if (result == null) { stats.cacheMisses++; result = new Programme(); if (json.has("title")){ result.addTitle(json.getString("title")); } } else { stats.cacheHits++; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", new Locale("nl")); //Calendar cal = df.getCalendar(); //cal.setTimeZone(TimeZone.getTimeZone("UTC")); //df.setCalendar(cal); df.setTimeZone(TimeZone.getTimeZone("UTC")); result.startTime = df.parse(json.getString("startDateTime")); result.endTime = df.parse(json.getString("endDateTime")); if (fetchDetails && !cached) { // TODO also read details if those have not been cached fillDetails(id, result); } if (!cached) { // FIXME where to do this? cache.put(getName(), id, result); } logger.debug(result); return result; } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getProgrammes(java.util.List, int, * boolean) */ @Override public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception { fetchStatics(); List<Programme> result = new ArrayList<Programme>(); if (day > MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS) { return result; // empty list } // TODO fetch multiple channels in one go for (Channel c : channels) { // start day hour=0 with 24 hours ahead URL url = programmeUrl(c, day, 0, 24); logger.debug("url: "+url); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Programs"); for (int i = 0; i < programs.size(); i++) { JSONObject program = programs.getJSONObject(i); Programme p = programmeFromJSON(program, config.fetchDetails); p.channel = c.getXmltvChannelId(); result.add(p); } } return result; } /** * @param args */ public static void main(String[] args) { Config config = Config.getDefaultConfig(); logger.setLevel(Level.TRACE); ZiggoGids gids = new ZiggoGids(config); try { List<Channel> channels = gids.getChannels(); System.out.println("Channels: " + channels); XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(new FileWriter("ziggogids.xml")); writer.writeStartDocument(); writer.writeCharacters("\n"); writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">"); writer.writeCharacters("\n"); writer.writeStartElement("tv"); //List<Channel> my_channels = channels; //List<Channel> my_channels = channels.subList(0, 15); List<Channel> my_channels = channels.subList(0, 4); for (Channel c : my_channels) { c.serialize(writer, true); } writer.flush(); List<Programme> programmes = gids.getProgrammes(my_channels, 2); for (Programme p : programmes) { p.serialize(writer); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); if (!config.quiet) { EPGSource.Stats stats = gids.getStats(); System.out.println("Number of programmes from cache: " + stats.cacheHits); System.out.println("Number of programmes fetched: " + stats.cacheMisses); System.out.println("Number of fetch errors: " + stats.fetchErrors); } gids.close(); } catch (Exception e) { logger.error("Error in ziggogids testing", e); } } }
janpascal/tv_grab_nl_java
src/main/java/org/vanbest/xmltv/ZiggoGids.java
3,702
/* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getChannels() */
block_comment
nl
package org.vanbest.xmltv; /* Copyright (c) 2012-2015 Jan-Pascal van Best <[email protected]> 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. The full license text can be found in the LICENSE file. */ import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.log4j.Level; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class ZiggoGids extends AbstractEPGSource implements EPGSource { private static final String base_data_root="https://api2.ziggo-apps.nl/base_data"; private static final String epg_data_root="https://api2.ziggo-apps.nl/programs"; private static final String programs_data_root="https://api2.ziggo-apps.nl/program_details"; private static final String channel_image_root="https://static.ziggo-apps.nl/images/channels/"; private static final String program_image_root="https://static.ziggo-apps.nl/images/programs/"; // NOTE: // the base_data json object also contains information about program Genres // IDs, icon base urls, and kijkwijzer IDs private static final int MAX_PROGRAMMES_PER_DAY = 9999; private static final int MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS = 7; //private static final int MAX_CHANNELS_PER_REQUEST = 25; public final static String NAME="ziggogids.nl"; static Logger logger = Logger.getLogger(ZiggoGids.class); class Statics { Map<String,String> genre; // id => name Map<String,String> kijkwijzer; // id => description; FIXME: also contains icons } private Statics statics = null; public ZiggoGids(Config config) { super(config); } public String getName() { return NAME; } // https://api2.ziggo-apps.nl/programs?channelIDs=1&date=2015-02-20+8&period=3 // period: number of hours ahead to fetch program data // TODO: multiple channels, "channelIDs=1,2,3" public static URL programmeUrl(Channel channel, int day, int hour, int period) throws Exception { StringBuilder s = new StringBuilder(epg_data_root); s.append("?channelIDs="); s.append(channel.id); GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, 0); String date = new SimpleDateFormat("yyyy-MM-dd+HH").format(cal.getTime()); s.append("&date="+date); s.append("&period="+period); return new URL(s.toString()); } // https://api2.ziggo-apps.nl/program_details?programID=1011424477400760329465668 public static URL detailUrl(String id) throws Exception { StringBuilder s = new StringBuilder(programs_data_root); s.append("?programID="); s.append(id); return new URL(s.toString()); } public void fetchStatics() { if (statics != null) return; URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating ziggo base data url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo base data from "+base_data_root, e); return; } statics = new Statics(); statics.genre = new HashMap<String,String>(); statics.kijkwijzer = new HashMap<String,String>(); JSONArray genres = base_data.getJSONArray("Genres"); for(int i=0; i<genres.size(); i++) { JSONObject genre = genres.getJSONObject(i); logger.debug("Genre " + genre.getString("id") + ": " + genre.getString("name")); statics.genre.put(genre.getString("id"), genre.getString("name")); } JSONArray parentals = base_data.getJSONArray("ParentalGuidances"); for(int i=0; i<parentals.size(); i++) { JSONObject parental = parentals.getJSONObject(i); String rating = parental.getString("name").replace("Kijkwijzer","").trim(); logger.debug("Rating " + parental.getString("id") + ": " + rating); statics.kijkwijzer.put(parental.getString("id"), rating); } } /* * (non-Javadoc) <SUF>*/ @Override public List<Channel> getChannels() { List<Channel> result = new ArrayList<Channel>(100); URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating horizon channel list url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo channel list from "+base_data_root, e); return result; } logger.debug("ziggogids channels json: " + base_data.toString()); JSONArray channels = base_data.getJSONArray("Channels"); for(int i=0; i < channels.size(); i++) { JSONObject zender = channels.getJSONObject(i); String name = zender.getString("name"); String id = zender.getString("id"); String xmltv = id + "." + getName(); String icon = channel_image_root + zender.getString("icon"); Channel c = Channel.getChannel(getName(), id, xmltv, name); c.addIcon(icon); result.add(c); } return result; } private void fillDetails(String id, Programme result) throws Exception { URL url = detailUrl(id); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Program"); JSONObject program = programs.getJSONObject(0); if (program.has("genre")) { String genre = statics.genre.get("" + program.getInt("genre")); if (genre != null) { result.addCategory(config.translateCategory(genre)); } // logger.debug(" FIXME genre: " + program.getInt("genre")); } JSONArray detail_list = json.getJSONArray("ProgramDetails"); JSONObject details = detail_list.getJSONObject(0); if (details.has("description")) { result.addDescription(details.getString("description")); } if (details.has("parentalGuidances")) { // logger.debug(" FIXME kijkwijzer " + details.getJSONArray("parentalGuidances").toString()); JSONArray guidances = details.getJSONArray("parentalGuidances"); List<String> kijkwijzers = new ArrayList<String>(guidances.size()); for(int i=0; i<guidances.size(); i++) { kijkwijzers.add(statics.kijkwijzer.get("" + guidances.getInt(i))); } result.addRating("kijkwijzer", StringUtils.join(kijkwijzers, ",")); } if (details.has("rerun")) { // TODO // logger.debug(" FIXME rerun: " + details.getString("rerun")); boolean rerun = details.getString("rerun").equals("true"); if (rerun) { result.setPreviouslyShown(); } } if (details.has("infoUrl")) { String info = details.getString("infoUrl"); if (info != null && ! info.isEmpty()) { result.addUrl(info); } } /* ppe: some kind of pay-per-view if (details.has("ppeUrl")) { String ppe = details.getString("ppeUrl"); if (ppe != null && ! ppe.isEmpty()) { logger.debug(" FIXME ppe URL: " + ppe); } } */ } /* { "title" : "NOS Journaal", "inHome" : "1", "endDateTime" : "2015-02-20 19:30:00", "id" : "1011424458800760329485668", "startDate" : "2015-02-20", "startDateTime" : "2015-02-20 19:00:00", "outOfCountry" : "0", "genre" : 12, "series_key" : "1_NOS Journaal", "outOfHome" : "1", "channel" : "1" }, */ private Programme programmeFromJSON(JSONObject json, boolean fetchDetails) throws Exception { String id = json.getString("id"); Programme result = cache.get(getName(), id); boolean cached = (result != null); boolean doNotCache = false; if (result == null) { stats.cacheMisses++; result = new Programme(); if (json.has("title")){ result.addTitle(json.getString("title")); } } else { stats.cacheHits++; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", new Locale("nl")); //Calendar cal = df.getCalendar(); //cal.setTimeZone(TimeZone.getTimeZone("UTC")); //df.setCalendar(cal); df.setTimeZone(TimeZone.getTimeZone("UTC")); result.startTime = df.parse(json.getString("startDateTime")); result.endTime = df.parse(json.getString("endDateTime")); if (fetchDetails && !cached) { // TODO also read details if those have not been cached fillDetails(id, result); } if (!cached) { // FIXME where to do this? cache.put(getName(), id, result); } logger.debug(result); return result; } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getProgrammes(java.util.List, int, * boolean) */ @Override public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception { fetchStatics(); List<Programme> result = new ArrayList<Programme>(); if (day > MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS) { return result; // empty list } // TODO fetch multiple channels in one go for (Channel c : channels) { // start day hour=0 with 24 hours ahead URL url = programmeUrl(c, day, 0, 24); logger.debug("url: "+url); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Programs"); for (int i = 0; i < programs.size(); i++) { JSONObject program = programs.getJSONObject(i); Programme p = programmeFromJSON(program, config.fetchDetails); p.channel = c.getXmltvChannelId(); result.add(p); } } return result; } /** * @param args */ public static void main(String[] args) { Config config = Config.getDefaultConfig(); logger.setLevel(Level.TRACE); ZiggoGids gids = new ZiggoGids(config); try { List<Channel> channels = gids.getChannels(); System.out.println("Channels: " + channels); XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(new FileWriter("ziggogids.xml")); writer.writeStartDocument(); writer.writeCharacters("\n"); writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">"); writer.writeCharacters("\n"); writer.writeStartElement("tv"); //List<Channel> my_channels = channels; //List<Channel> my_channels = channels.subList(0, 15); List<Channel> my_channels = channels.subList(0, 4); for (Channel c : my_channels) { c.serialize(writer, true); } writer.flush(); List<Programme> programmes = gids.getProgrammes(my_channels, 2); for (Programme p : programmes) { p.serialize(writer); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); if (!config.quiet) { EPGSource.Stats stats = gids.getStats(); System.out.println("Number of programmes from cache: " + stats.cacheHits); System.out.println("Number of programmes fetched: " + stats.cacheMisses); System.out.println("Number of fetch errors: " + stats.fetchErrors); } gids.close(); } catch (Exception e) { logger.error("Error in ziggogids testing", e); } } }
201303_10
package org.vanbest.xmltv; /* Copyright (c) 2012-2015 Jan-Pascal van Best <[email protected]> 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. The full license text can be found in the LICENSE file. */ import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.log4j.Level; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class ZiggoGids extends AbstractEPGSource implements EPGSource { private static final String base_data_root="https://api2.ziggo-apps.nl/base_data"; private static final String epg_data_root="https://api2.ziggo-apps.nl/programs"; private static final String programs_data_root="https://api2.ziggo-apps.nl/program_details"; private static final String channel_image_root="https://static.ziggo-apps.nl/images/channels/"; private static final String program_image_root="https://static.ziggo-apps.nl/images/programs/"; // NOTE: // the base_data json object also contains information about program Genres // IDs, icon base urls, and kijkwijzer IDs private static final int MAX_PROGRAMMES_PER_DAY = 9999; private static final int MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS = 7; //private static final int MAX_CHANNELS_PER_REQUEST = 25; public final static String NAME="ziggogids.nl"; static Logger logger = Logger.getLogger(ZiggoGids.class); class Statics { Map<String,String> genre; // id => name Map<String,String> kijkwijzer; // id => description; FIXME: also contains icons } private Statics statics = null; public ZiggoGids(Config config) { super(config); } public String getName() { return NAME; } // https://api2.ziggo-apps.nl/programs?channelIDs=1&date=2015-02-20+8&period=3 // period: number of hours ahead to fetch program data // TODO: multiple channels, "channelIDs=1,2,3" public static URL programmeUrl(Channel channel, int day, int hour, int period) throws Exception { StringBuilder s = new StringBuilder(epg_data_root); s.append("?channelIDs="); s.append(channel.id); GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, 0); String date = new SimpleDateFormat("yyyy-MM-dd+HH").format(cal.getTime()); s.append("&date="+date); s.append("&period="+period); return new URL(s.toString()); } // https://api2.ziggo-apps.nl/program_details?programID=1011424477400760329465668 public static URL detailUrl(String id) throws Exception { StringBuilder s = new StringBuilder(programs_data_root); s.append("?programID="); s.append(id); return new URL(s.toString()); } public void fetchStatics() { if (statics != null) return; URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating ziggo base data url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo base data from "+base_data_root, e); return; } statics = new Statics(); statics.genre = new HashMap<String,String>(); statics.kijkwijzer = new HashMap<String,String>(); JSONArray genres = base_data.getJSONArray("Genres"); for(int i=0; i<genres.size(); i++) { JSONObject genre = genres.getJSONObject(i); logger.debug("Genre " + genre.getString("id") + ": " + genre.getString("name")); statics.genre.put(genre.getString("id"), genre.getString("name")); } JSONArray parentals = base_data.getJSONArray("ParentalGuidances"); for(int i=0; i<parentals.size(); i++) { JSONObject parental = parentals.getJSONObject(i); String rating = parental.getString("name").replace("Kijkwijzer","").trim(); logger.debug("Rating " + parental.getString("id") + ": " + rating); statics.kijkwijzer.put(parental.getString("id"), rating); } } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getChannels() */ @Override public List<Channel> getChannels() { List<Channel> result = new ArrayList<Channel>(100); URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating horizon channel list url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo channel list from "+base_data_root, e); return result; } logger.debug("ziggogids channels json: " + base_data.toString()); JSONArray channels = base_data.getJSONArray("Channels"); for(int i=0; i < channels.size(); i++) { JSONObject zender = channels.getJSONObject(i); String name = zender.getString("name"); String id = zender.getString("id"); String xmltv = id + "." + getName(); String icon = channel_image_root + zender.getString("icon"); Channel c = Channel.getChannel(getName(), id, xmltv, name); c.addIcon(icon); result.add(c); } return result; } private void fillDetails(String id, Programme result) throws Exception { URL url = detailUrl(id); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Program"); JSONObject program = programs.getJSONObject(0); if (program.has("genre")) { String genre = statics.genre.get("" + program.getInt("genre")); if (genre != null) { result.addCategory(config.translateCategory(genre)); } // logger.debug(" FIXME genre: " + program.getInt("genre")); } JSONArray detail_list = json.getJSONArray("ProgramDetails"); JSONObject details = detail_list.getJSONObject(0); if (details.has("description")) { result.addDescription(details.getString("description")); } if (details.has("parentalGuidances")) { // logger.debug(" FIXME kijkwijzer " + details.getJSONArray("parentalGuidances").toString()); JSONArray guidances = details.getJSONArray("parentalGuidances"); List<String> kijkwijzers = new ArrayList<String>(guidances.size()); for(int i=0; i<guidances.size(); i++) { kijkwijzers.add(statics.kijkwijzer.get("" + guidances.getInt(i))); } result.addRating("kijkwijzer", StringUtils.join(kijkwijzers, ",")); } if (details.has("rerun")) { // TODO // logger.debug(" FIXME rerun: " + details.getString("rerun")); boolean rerun = details.getString("rerun").equals("true"); if (rerun) { result.setPreviouslyShown(); } } if (details.has("infoUrl")) { String info = details.getString("infoUrl"); if (info != null && ! info.isEmpty()) { result.addUrl(info); } } /* ppe: some kind of pay-per-view if (details.has("ppeUrl")) { String ppe = details.getString("ppeUrl"); if (ppe != null && ! ppe.isEmpty()) { logger.debug(" FIXME ppe URL: " + ppe); } } */ } /* { "title" : "NOS Journaal", "inHome" : "1", "endDateTime" : "2015-02-20 19:30:00", "id" : "1011424458800760329485668", "startDate" : "2015-02-20", "startDateTime" : "2015-02-20 19:00:00", "outOfCountry" : "0", "genre" : 12, "series_key" : "1_NOS Journaal", "outOfHome" : "1", "channel" : "1" }, */ private Programme programmeFromJSON(JSONObject json, boolean fetchDetails) throws Exception { String id = json.getString("id"); Programme result = cache.get(getName(), id); boolean cached = (result != null); boolean doNotCache = false; if (result == null) { stats.cacheMisses++; result = new Programme(); if (json.has("title")){ result.addTitle(json.getString("title")); } } else { stats.cacheHits++; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", new Locale("nl")); //Calendar cal = df.getCalendar(); //cal.setTimeZone(TimeZone.getTimeZone("UTC")); //df.setCalendar(cal); df.setTimeZone(TimeZone.getTimeZone("UTC")); result.startTime = df.parse(json.getString("startDateTime")); result.endTime = df.parse(json.getString("endDateTime")); if (fetchDetails && !cached) { // TODO also read details if those have not been cached fillDetails(id, result); } if (!cached) { // FIXME where to do this? cache.put(getName(), id, result); } logger.debug(result); return result; } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getProgrammes(java.util.List, int, * boolean) */ @Override public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception { fetchStatics(); List<Programme> result = new ArrayList<Programme>(); if (day > MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS) { return result; // empty list } // TODO fetch multiple channels in one go for (Channel c : channels) { // start day hour=0 with 24 hours ahead URL url = programmeUrl(c, day, 0, 24); logger.debug("url: "+url); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Programs"); for (int i = 0; i < programs.size(); i++) { JSONObject program = programs.getJSONObject(i); Programme p = programmeFromJSON(program, config.fetchDetails); p.channel = c.getXmltvChannelId(); result.add(p); } } return result; } /** * @param args */ public static void main(String[] args) { Config config = Config.getDefaultConfig(); logger.setLevel(Level.TRACE); ZiggoGids gids = new ZiggoGids(config); try { List<Channel> channels = gids.getChannels(); System.out.println("Channels: " + channels); XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(new FileWriter("ziggogids.xml")); writer.writeStartDocument(); writer.writeCharacters("\n"); writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">"); writer.writeCharacters("\n"); writer.writeStartElement("tv"); //List<Channel> my_channels = channels; //List<Channel> my_channels = channels.subList(0, 15); List<Channel> my_channels = channels.subList(0, 4); for (Channel c : my_channels) { c.serialize(writer, true); } writer.flush(); List<Programme> programmes = gids.getProgrammes(my_channels, 2); for (Programme p : programmes) { p.serialize(writer); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); if (!config.quiet) { EPGSource.Stats stats = gids.getStats(); System.out.println("Number of programmes from cache: " + stats.cacheHits); System.out.println("Number of programmes fetched: " + stats.cacheMisses); System.out.println("Number of fetch errors: " + stats.fetchErrors); } gids.close(); } catch (Exception e) { logger.error("Error in ziggogids testing", e); } } }
janpascal/tv_grab_nl_java
src/main/java/org/vanbest/xmltv/ZiggoGids.java
3,702
// logger.debug(" FIXME kijkwijzer " + details.getJSONArray("parentalGuidances").toString());
line_comment
nl
package org.vanbest.xmltv; /* Copyright (c) 2012-2015 Jan-Pascal van Best <[email protected]> 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. The full license text can be found in the LICENSE file. */ import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.log4j.Level; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class ZiggoGids extends AbstractEPGSource implements EPGSource { private static final String base_data_root="https://api2.ziggo-apps.nl/base_data"; private static final String epg_data_root="https://api2.ziggo-apps.nl/programs"; private static final String programs_data_root="https://api2.ziggo-apps.nl/program_details"; private static final String channel_image_root="https://static.ziggo-apps.nl/images/channels/"; private static final String program_image_root="https://static.ziggo-apps.nl/images/programs/"; // NOTE: // the base_data json object also contains information about program Genres // IDs, icon base urls, and kijkwijzer IDs private static final int MAX_PROGRAMMES_PER_DAY = 9999; private static final int MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS = 7; //private static final int MAX_CHANNELS_PER_REQUEST = 25; public final static String NAME="ziggogids.nl"; static Logger logger = Logger.getLogger(ZiggoGids.class); class Statics { Map<String,String> genre; // id => name Map<String,String> kijkwijzer; // id => description; FIXME: also contains icons } private Statics statics = null; public ZiggoGids(Config config) { super(config); } public String getName() { return NAME; } // https://api2.ziggo-apps.nl/programs?channelIDs=1&date=2015-02-20+8&period=3 // period: number of hours ahead to fetch program data // TODO: multiple channels, "channelIDs=1,2,3" public static URL programmeUrl(Channel channel, int day, int hour, int period) throws Exception { StringBuilder s = new StringBuilder(epg_data_root); s.append("?channelIDs="); s.append(channel.id); GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, 0); String date = new SimpleDateFormat("yyyy-MM-dd+HH").format(cal.getTime()); s.append("&date="+date); s.append("&period="+period); return new URL(s.toString()); } // https://api2.ziggo-apps.nl/program_details?programID=1011424477400760329465668 public static URL detailUrl(String id) throws Exception { StringBuilder s = new StringBuilder(programs_data_root); s.append("?programID="); s.append(id); return new URL(s.toString()); } public void fetchStatics() { if (statics != null) return; URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating ziggo base data url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo base data from "+base_data_root, e); return; } statics = new Statics(); statics.genre = new HashMap<String,String>(); statics.kijkwijzer = new HashMap<String,String>(); JSONArray genres = base_data.getJSONArray("Genres"); for(int i=0; i<genres.size(); i++) { JSONObject genre = genres.getJSONObject(i); logger.debug("Genre " + genre.getString("id") + ": " + genre.getString("name")); statics.genre.put(genre.getString("id"), genre.getString("name")); } JSONArray parentals = base_data.getJSONArray("ParentalGuidances"); for(int i=0; i<parentals.size(); i++) { JSONObject parental = parentals.getJSONObject(i); String rating = parental.getString("name").replace("Kijkwijzer","").trim(); logger.debug("Rating " + parental.getString("id") + ": " + rating); statics.kijkwijzer.put(parental.getString("id"), rating); } } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getChannels() */ @Override public List<Channel> getChannels() { List<Channel> result = new ArrayList<Channel>(100); URL url = null; try { url = new URL(base_data_root); } catch (MalformedURLException e) { logger.error("Exception creating horizon channel list url", e); } JSONObject base_data; try { base_data = fetchJSON(url); } catch (Exception e) { logger.error("IO Exception trying to get ziggo channel list from "+base_data_root, e); return result; } logger.debug("ziggogids channels json: " + base_data.toString()); JSONArray channels = base_data.getJSONArray("Channels"); for(int i=0; i < channels.size(); i++) { JSONObject zender = channels.getJSONObject(i); String name = zender.getString("name"); String id = zender.getString("id"); String xmltv = id + "." + getName(); String icon = channel_image_root + zender.getString("icon"); Channel c = Channel.getChannel(getName(), id, xmltv, name); c.addIcon(icon); result.add(c); } return result; } private void fillDetails(String id, Programme result) throws Exception { URL url = detailUrl(id); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Program"); JSONObject program = programs.getJSONObject(0); if (program.has("genre")) { String genre = statics.genre.get("" + program.getInt("genre")); if (genre != null) { result.addCategory(config.translateCategory(genre)); } // logger.debug(" FIXME genre: " + program.getInt("genre")); } JSONArray detail_list = json.getJSONArray("ProgramDetails"); JSONObject details = detail_list.getJSONObject(0); if (details.has("description")) { result.addDescription(details.getString("description")); } if (details.has("parentalGuidances")) { // logger.debug(" <SUF> JSONArray guidances = details.getJSONArray("parentalGuidances"); List<String> kijkwijzers = new ArrayList<String>(guidances.size()); for(int i=0; i<guidances.size(); i++) { kijkwijzers.add(statics.kijkwijzer.get("" + guidances.getInt(i))); } result.addRating("kijkwijzer", StringUtils.join(kijkwijzers, ",")); } if (details.has("rerun")) { // TODO // logger.debug(" FIXME rerun: " + details.getString("rerun")); boolean rerun = details.getString("rerun").equals("true"); if (rerun) { result.setPreviouslyShown(); } } if (details.has("infoUrl")) { String info = details.getString("infoUrl"); if (info != null && ! info.isEmpty()) { result.addUrl(info); } } /* ppe: some kind of pay-per-view if (details.has("ppeUrl")) { String ppe = details.getString("ppeUrl"); if (ppe != null && ! ppe.isEmpty()) { logger.debug(" FIXME ppe URL: " + ppe); } } */ } /* { "title" : "NOS Journaal", "inHome" : "1", "endDateTime" : "2015-02-20 19:30:00", "id" : "1011424458800760329485668", "startDate" : "2015-02-20", "startDateTime" : "2015-02-20 19:00:00", "outOfCountry" : "0", "genre" : 12, "series_key" : "1_NOS Journaal", "outOfHome" : "1", "channel" : "1" }, */ private Programme programmeFromJSON(JSONObject json, boolean fetchDetails) throws Exception { String id = json.getString("id"); Programme result = cache.get(getName(), id); boolean cached = (result != null); boolean doNotCache = false; if (result == null) { stats.cacheMisses++; result = new Programme(); if (json.has("title")){ result.addTitle(json.getString("title")); } } else { stats.cacheHits++; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", new Locale("nl")); //Calendar cal = df.getCalendar(); //cal.setTimeZone(TimeZone.getTimeZone("UTC")); //df.setCalendar(cal); df.setTimeZone(TimeZone.getTimeZone("UTC")); result.startTime = df.parse(json.getString("startDateTime")); result.endTime = df.parse(json.getString("endDateTime")); if (fetchDetails && !cached) { // TODO also read details if those have not been cached fillDetails(id, result); } if (!cached) { // FIXME where to do this? cache.put(getName(), id, result); } logger.debug(result); return result; } /* * (non-Javadoc) * * @see org.vanbest.xmltv.EPGSource#getProgrammes(java.util.List, int, * boolean) */ @Override public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception { fetchStatics(); List<Programme> result = new ArrayList<Programme>(); if (day > MAX_DAYS_AHEAD_SUPPORTED_BY_ZIGGOGIDS) { return result; // empty list } // TODO fetch multiple channels in one go for (Channel c : channels) { // start day hour=0 with 24 hours ahead URL url = programmeUrl(c, day, 0, 24); logger.debug("url: "+url); JSONObject json = fetchJSON(url); logger.debug(json.toString()); JSONArray programs = json.getJSONArray("Programs"); for (int i = 0; i < programs.size(); i++) { JSONObject program = programs.getJSONObject(i); Programme p = programmeFromJSON(program, config.fetchDetails); p.channel = c.getXmltvChannelId(); result.add(p); } } return result; } /** * @param args */ public static void main(String[] args) { Config config = Config.getDefaultConfig(); logger.setLevel(Level.TRACE); ZiggoGids gids = new ZiggoGids(config); try { List<Channel> channels = gids.getChannels(); System.out.println("Channels: " + channels); XMLStreamWriter writer = XMLOutputFactory.newInstance() .createXMLStreamWriter(new FileWriter("ziggogids.xml")); writer.writeStartDocument(); writer.writeCharacters("\n"); writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">"); writer.writeCharacters("\n"); writer.writeStartElement("tv"); //List<Channel> my_channels = channels; //List<Channel> my_channels = channels.subList(0, 15); List<Channel> my_channels = channels.subList(0, 4); for (Channel c : my_channels) { c.serialize(writer, true); } writer.flush(); List<Programme> programmes = gids.getProgrammes(my_channels, 2); for (Programme p : programmes) { p.serialize(writer); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); if (!config.quiet) { EPGSource.Stats stats = gids.getStats(); System.out.println("Number of programmes from cache: " + stats.cacheHits); System.out.println("Number of programmes fetched: " + stats.cacheMisses); System.out.println("Number of fetch errors: " + stats.fetchErrors); } gids.close(); } catch (Exception e) { logger.error("Error in ziggogids testing", e); } } }
201309_0
package domein; import java.util.Objects; public class Auto implements Comparable<Auto> { private String nummerplaat; private String merk; private String model; public Auto(String nummerplaat, String merk, String model) { setNummerplaat(nummerplaat); setMerk(merk); setModel(model); } public String getMerk() { return merk; } private void setMerk(String merk) { this.merk = merk; } public String getModel() { return model; } private void setModel(String model) { this.model = model; } public String getNummerplaat() { return nummerplaat; } private void setNummerplaat(String nummerplaat) { this.nummerplaat = nummerplaat; } @Override public String toString() { return String.format("%s %s met nummerplaat %s", merk, model, nummerplaat); } // Twee auto zijn gelijk als dezelfde nummerplaat hebben // Override de methodes equals en hashCode uit Object // Zorg ook dat deze klasse de interface Comparable implementeert, // auto worden op natuurlijke wijze gesorteerd op nummerplaat (alfabetisch) @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Auto)) return false; Auto auto = (Auto) o; return Objects.equals(getNummerplaat(), auto.getNummerplaat()); } @Override public int hashCode() { return Objects.hash(getNummerplaat()); } @Override public int compareTo(Auto a) { return getNummerplaat().compareTo(a.getNummerplaat()); } }
Swesje/OO-Software-Development-II
H6 - Collections /Oefeningen/Oefeningen Oefening 1 - Garage/src/domein/Auto.java
461
// Twee auto zijn gelijk als dezelfde nummerplaat hebben
line_comment
nl
package domein; import java.util.Objects; public class Auto implements Comparable<Auto> { private String nummerplaat; private String merk; private String model; public Auto(String nummerplaat, String merk, String model) { setNummerplaat(nummerplaat); setMerk(merk); setModel(model); } public String getMerk() { return merk; } private void setMerk(String merk) { this.merk = merk; } public String getModel() { return model; } private void setModel(String model) { this.model = model; } public String getNummerplaat() { return nummerplaat; } private void setNummerplaat(String nummerplaat) { this.nummerplaat = nummerplaat; } @Override public String toString() { return String.format("%s %s met nummerplaat %s", merk, model, nummerplaat); } // Twee auto<SUF> // Override de methodes equals en hashCode uit Object // Zorg ook dat deze klasse de interface Comparable implementeert, // auto worden op natuurlijke wijze gesorteerd op nummerplaat (alfabetisch) @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Auto)) return false; Auto auto = (Auto) o; return Objects.equals(getNummerplaat(), auto.getNummerplaat()); } @Override public int hashCode() { return Objects.hash(getNummerplaat()); } @Override public int compareTo(Auto a) { return getNummerplaat().compareTo(a.getNummerplaat()); } }
201309_2
package domein; import java.util.Objects; public class Auto implements Comparable<Auto> { private String nummerplaat; private String merk; private String model; public Auto(String nummerplaat, String merk, String model) { setNummerplaat(nummerplaat); setMerk(merk); setModel(model); } public String getMerk() { return merk; } private void setMerk(String merk) { this.merk = merk; } public String getModel() { return model; } private void setModel(String model) { this.model = model; } public String getNummerplaat() { return nummerplaat; } private void setNummerplaat(String nummerplaat) { this.nummerplaat = nummerplaat; } @Override public String toString() { return String.format("%s %s met nummerplaat %s", merk, model, nummerplaat); } // Twee auto zijn gelijk als dezelfde nummerplaat hebben // Override de methodes equals en hashCode uit Object // Zorg ook dat deze klasse de interface Comparable implementeert, // auto worden op natuurlijke wijze gesorteerd op nummerplaat (alfabetisch) @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Auto)) return false; Auto auto = (Auto) o; return Objects.equals(getNummerplaat(), auto.getNummerplaat()); } @Override public int hashCode() { return Objects.hash(getNummerplaat()); } @Override public int compareTo(Auto a) { return getNummerplaat().compareTo(a.getNummerplaat()); } }
Swesje/OO-Software-Development-II
H6 - Collections /Oefeningen/Oefeningen Oefening 1 - Garage/src/domein/Auto.java
461
// Zorg ook dat deze klasse de interface Comparable implementeert,
line_comment
nl
package domein; import java.util.Objects; public class Auto implements Comparable<Auto> { private String nummerplaat; private String merk; private String model; public Auto(String nummerplaat, String merk, String model) { setNummerplaat(nummerplaat); setMerk(merk); setModel(model); } public String getMerk() { return merk; } private void setMerk(String merk) { this.merk = merk; } public String getModel() { return model; } private void setModel(String model) { this.model = model; } public String getNummerplaat() { return nummerplaat; } private void setNummerplaat(String nummerplaat) { this.nummerplaat = nummerplaat; } @Override public String toString() { return String.format("%s %s met nummerplaat %s", merk, model, nummerplaat); } // Twee auto zijn gelijk als dezelfde nummerplaat hebben // Override de methodes equals en hashCode uit Object // Zorg ook<SUF> // auto worden op natuurlijke wijze gesorteerd op nummerplaat (alfabetisch) @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Auto)) return false; Auto auto = (Auto) o; return Objects.equals(getNummerplaat(), auto.getNummerplaat()); } @Override public int hashCode() { return Objects.hash(getNummerplaat()); } @Override public int compareTo(Auto a) { return getNummerplaat().compareTo(a.getNummerplaat()); } }
201309_3
package domein; import java.util.Objects; public class Auto implements Comparable<Auto> { private String nummerplaat; private String merk; private String model; public Auto(String nummerplaat, String merk, String model) { setNummerplaat(nummerplaat); setMerk(merk); setModel(model); } public String getMerk() { return merk; } private void setMerk(String merk) { this.merk = merk; } public String getModel() { return model; } private void setModel(String model) { this.model = model; } public String getNummerplaat() { return nummerplaat; } private void setNummerplaat(String nummerplaat) { this.nummerplaat = nummerplaat; } @Override public String toString() { return String.format("%s %s met nummerplaat %s", merk, model, nummerplaat); } // Twee auto zijn gelijk als dezelfde nummerplaat hebben // Override de methodes equals en hashCode uit Object // Zorg ook dat deze klasse de interface Comparable implementeert, // auto worden op natuurlijke wijze gesorteerd op nummerplaat (alfabetisch) @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Auto)) return false; Auto auto = (Auto) o; return Objects.equals(getNummerplaat(), auto.getNummerplaat()); } @Override public int hashCode() { return Objects.hash(getNummerplaat()); } @Override public int compareTo(Auto a) { return getNummerplaat().compareTo(a.getNummerplaat()); } }
Swesje/OO-Software-Development-II
H6 - Collections /Oefeningen/Oefeningen Oefening 1 - Garage/src/domein/Auto.java
461
// auto worden op natuurlijke wijze gesorteerd op nummerplaat (alfabetisch)
line_comment
nl
package domein; import java.util.Objects; public class Auto implements Comparable<Auto> { private String nummerplaat; private String merk; private String model; public Auto(String nummerplaat, String merk, String model) { setNummerplaat(nummerplaat); setMerk(merk); setModel(model); } public String getMerk() { return merk; } private void setMerk(String merk) { this.merk = merk; } public String getModel() { return model; } private void setModel(String model) { this.model = model; } public String getNummerplaat() { return nummerplaat; } private void setNummerplaat(String nummerplaat) { this.nummerplaat = nummerplaat; } @Override public String toString() { return String.format("%s %s met nummerplaat %s", merk, model, nummerplaat); } // Twee auto zijn gelijk als dezelfde nummerplaat hebben // Override de methodes equals en hashCode uit Object // Zorg ook dat deze klasse de interface Comparable implementeert, // auto worden<SUF> @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Auto)) return false; Auto auto = (Auto) o; return Objects.equals(getNummerplaat(), auto.getNummerplaat()); } @Override public int hashCode() { return Objects.hash(getNummerplaat()); } @Override public int compareTo(Auto a) { return getNummerplaat().compareTo(a.getNummerplaat()); } }
201315_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.beheer.webapp.controllers.stamgegevens.autaut; import javax.inject.Inject; import javax.inject.Named; import nl.bzk.algemeenbrp.dal.domein.brp.enums.LeverwijzeSelectie; import nl.bzk.brp.beheer.webapp.configuratie.ControllerConstants; import nl.bzk.brp.beheer.webapp.controllers.AbstractReadonlyController; import nl.bzk.brp.beheer.webapp.repository.ReadonlyRepository; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Leverwijze Selectie controller. */ @RestController @RequestMapping(value = ControllerConstants.LEVERWIJZE_SELECTIE_URI) public final class LeverwijzeSelectieController extends AbstractReadonlyController<LeverwijzeSelectie, Integer> { /** * Constructor. * @param repository Leverwijze Selectie repository */ @Inject protected LeverwijzeSelectieController( @Named("leverwijzeSelectieRepository") final ReadonlyRepository<LeverwijzeSelectie, Integer> repository) { super(repository); } }
DDDNL/OperatieBRP
Broncode/operatiebrp-code-145.3/brp/beheer/beheer-api/src/main/java/nl/bzk/brp/beheer/webapp/controllers/stamgegevens/autaut/LeverwijzeSelectieController.java
373
/** * Leverwijze Selectie controller. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.beheer.webapp.controllers.stamgegevens.autaut; import javax.inject.Inject; import javax.inject.Named; import nl.bzk.algemeenbrp.dal.domein.brp.enums.LeverwijzeSelectie; import nl.bzk.brp.beheer.webapp.configuratie.ControllerConstants; import nl.bzk.brp.beheer.webapp.controllers.AbstractReadonlyController; import nl.bzk.brp.beheer.webapp.repository.ReadonlyRepository; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Leverwijze Selectie controller.<SUF>*/ @RestController @RequestMapping(value = ControllerConstants.LEVERWIJZE_SELECTIE_URI) public final class LeverwijzeSelectieController extends AbstractReadonlyController<LeverwijzeSelectie, Integer> { /** * Constructor. * @param repository Leverwijze Selectie repository */ @Inject protected LeverwijzeSelectieController( @Named("leverwijzeSelectieRepository") final ReadonlyRepository<LeverwijzeSelectie, Integer> repository) { super(repository); } }
201322_0
package objecten_en_velden; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; /** * @invar | getVelden() != null * @invar | getVelden().keySet().stream().allMatch(n -> n != null && getVelden().get(n) != null && getVelden().get(n).getNaam() == n && getVelden().get(n).getObject() == this) * @invar | getVerwijzendeVelden().stream().allMatch(v -> v != null && v.getWaarde() == this) */ public class JavaObject extends Waarde { /** * @invar | velden != null * @invar | velden.keySet().stream().allMatch(n -> n != null && velden.get(n) != null && velden.get(n).naam == n && velden.get(n).object == this) * @invar | verwijzendeVelden.stream().allMatch(v -> v != null && v.waarde == this) * @representationObject * @peerObjects | velden.values() */ HashMap<String, Veld> velden = new HashMap<>(); /** * @representationObject * @peerObjects */ HashSet<Veld> verwijzendeVelden = new HashSet<>(); /** * @creates | result * @peerObjects | result.values() */ public Map<String, Veld> getVelden() { return Map.copyOf(velden); } /** * @creates | result * @peerObjects */ public Set<Veld> getVerwijzendeVelden() { return Set.copyOf(verwijzendeVelden); } /** * @post | getVelden().isEmpty() * @post | getVerwijzendeVelden().isEmpty() */ public JavaObject() {} /** * @post | result == (this == obj) */ @Override public boolean equals(Object obj) { return this == obj; } public Iterator<JavaObject> getNextIterator() { return new Iterator<JavaObject>() { JavaObject object = JavaObject.this; @Override public boolean hasNext() { return object != null; } @Override public JavaObject next() { JavaObject result = object; if (object.velden.containsKey("next") && object.velden.get("next").waarde instanceof JavaObject o) object = o; else object = null; return result; } }; } public void forEachBereikbaarObject(Consumer<? super JavaObject> consumer) { consumer.accept(this); for (Veld veld : velden.values()) { if (veld.waarde instanceof JavaObject o) o.forEachBereikbaarObject(consumer); } } public Stream<String> getNamenVanObjectenVanVerwijzendeVelden() { return verwijzendeVelden.stream().flatMap(v -> v.object.velden.keySet().stream()); } }
btj/objecten_en_velden
objecten_en_velden/src/objecten_en_velden/JavaObject.java
805
/** * @invar | getVelden() != null * @invar | getVelden().keySet().stream().allMatch(n -> n != null && getVelden().get(n) != null && getVelden().get(n).getNaam() == n && getVelden().get(n).getObject() == this) * @invar | getVerwijzendeVelden().stream().allMatch(v -> v != null && v.getWaarde() == this) */
block_comment
nl
package objecten_en_velden; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; /** * @invar | getVelden()<SUF>*/ public class JavaObject extends Waarde { /** * @invar | velden != null * @invar | velden.keySet().stream().allMatch(n -> n != null && velden.get(n) != null && velden.get(n).naam == n && velden.get(n).object == this) * @invar | verwijzendeVelden.stream().allMatch(v -> v != null && v.waarde == this) * @representationObject * @peerObjects | velden.values() */ HashMap<String, Veld> velden = new HashMap<>(); /** * @representationObject * @peerObjects */ HashSet<Veld> verwijzendeVelden = new HashSet<>(); /** * @creates | result * @peerObjects | result.values() */ public Map<String, Veld> getVelden() { return Map.copyOf(velden); } /** * @creates | result * @peerObjects */ public Set<Veld> getVerwijzendeVelden() { return Set.copyOf(verwijzendeVelden); } /** * @post | getVelden().isEmpty() * @post | getVerwijzendeVelden().isEmpty() */ public JavaObject() {} /** * @post | result == (this == obj) */ @Override public boolean equals(Object obj) { return this == obj; } public Iterator<JavaObject> getNextIterator() { return new Iterator<JavaObject>() { JavaObject object = JavaObject.this; @Override public boolean hasNext() { return object != null; } @Override public JavaObject next() { JavaObject result = object; if (object.velden.containsKey("next") && object.velden.get("next").waarde instanceof JavaObject o) object = o; else object = null; return result; } }; } public void forEachBereikbaarObject(Consumer<? super JavaObject> consumer) { consumer.accept(this); for (Veld veld : velden.values()) { if (veld.waarde instanceof JavaObject o) o.forEachBereikbaarObject(consumer); } } public Stream<String> getNamenVanObjectenVanVerwijzendeVelden() { return verwijzendeVelden.stream().flatMap(v -> v.object.velden.keySet().stream()); } }
201322_1
package objecten_en_velden; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; /** * @invar | getVelden() != null * @invar | getVelden().keySet().stream().allMatch(n -> n != null && getVelden().get(n) != null && getVelden().get(n).getNaam() == n && getVelden().get(n).getObject() == this) * @invar | getVerwijzendeVelden().stream().allMatch(v -> v != null && v.getWaarde() == this) */ public class JavaObject extends Waarde { /** * @invar | velden != null * @invar | velden.keySet().stream().allMatch(n -> n != null && velden.get(n) != null && velden.get(n).naam == n && velden.get(n).object == this) * @invar | verwijzendeVelden.stream().allMatch(v -> v != null && v.waarde == this) * @representationObject * @peerObjects | velden.values() */ HashMap<String, Veld> velden = new HashMap<>(); /** * @representationObject * @peerObjects */ HashSet<Veld> verwijzendeVelden = new HashSet<>(); /** * @creates | result * @peerObjects | result.values() */ public Map<String, Veld> getVelden() { return Map.copyOf(velden); } /** * @creates | result * @peerObjects */ public Set<Veld> getVerwijzendeVelden() { return Set.copyOf(verwijzendeVelden); } /** * @post | getVelden().isEmpty() * @post | getVerwijzendeVelden().isEmpty() */ public JavaObject() {} /** * @post | result == (this == obj) */ @Override public boolean equals(Object obj) { return this == obj; } public Iterator<JavaObject> getNextIterator() { return new Iterator<JavaObject>() { JavaObject object = JavaObject.this; @Override public boolean hasNext() { return object != null; } @Override public JavaObject next() { JavaObject result = object; if (object.velden.containsKey("next") && object.velden.get("next").waarde instanceof JavaObject o) object = o; else object = null; return result; } }; } public void forEachBereikbaarObject(Consumer<? super JavaObject> consumer) { consumer.accept(this); for (Veld veld : velden.values()) { if (veld.waarde instanceof JavaObject o) o.forEachBereikbaarObject(consumer); } } public Stream<String> getNamenVanObjectenVanVerwijzendeVelden() { return verwijzendeVelden.stream().flatMap(v -> v.object.velden.keySet().stream()); } }
btj/objecten_en_velden
objecten_en_velden/src/objecten_en_velden/JavaObject.java
805
/** * @invar | velden != null * @invar | velden.keySet().stream().allMatch(n -> n != null && velden.get(n) != null && velden.get(n).naam == n && velden.get(n).object == this) * @invar | verwijzendeVelden.stream().allMatch(v -> v != null && v.waarde == this) * @representationObject * @peerObjects | velden.values() */
block_comment
nl
package objecten_en_velden; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; /** * @invar | getVelden() != null * @invar | getVelden().keySet().stream().allMatch(n -> n != null && getVelden().get(n) != null && getVelden().get(n).getNaam() == n && getVelden().get(n).getObject() == this) * @invar | getVerwijzendeVelden().stream().allMatch(v -> v != null && v.getWaarde() == this) */ public class JavaObject extends Waarde { /** * @invar | velden<SUF>*/ HashMap<String, Veld> velden = new HashMap<>(); /** * @representationObject * @peerObjects */ HashSet<Veld> verwijzendeVelden = new HashSet<>(); /** * @creates | result * @peerObjects | result.values() */ public Map<String, Veld> getVelden() { return Map.copyOf(velden); } /** * @creates | result * @peerObjects */ public Set<Veld> getVerwijzendeVelden() { return Set.copyOf(verwijzendeVelden); } /** * @post | getVelden().isEmpty() * @post | getVerwijzendeVelden().isEmpty() */ public JavaObject() {} /** * @post | result == (this == obj) */ @Override public boolean equals(Object obj) { return this == obj; } public Iterator<JavaObject> getNextIterator() { return new Iterator<JavaObject>() { JavaObject object = JavaObject.this; @Override public boolean hasNext() { return object != null; } @Override public JavaObject next() { JavaObject result = object; if (object.velden.containsKey("next") && object.velden.get("next").waarde instanceof JavaObject o) object = o; else object = null; return result; } }; } public void forEachBereikbaarObject(Consumer<? super JavaObject> consumer) { consumer.accept(this); for (Veld veld : velden.values()) { if (veld.waarde instanceof JavaObject o) o.forEachBereikbaarObject(consumer); } } public Stream<String> getNamenVanObjectenVanVerwijzendeVelden() { return verwijzendeVelden.stream().flatMap(v -> v.object.velden.keySet().stream()); } }
201322_5
package objecten_en_velden; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; /** * @invar | getVelden() != null * @invar | getVelden().keySet().stream().allMatch(n -> n != null && getVelden().get(n) != null && getVelden().get(n).getNaam() == n && getVelden().get(n).getObject() == this) * @invar | getVerwijzendeVelden().stream().allMatch(v -> v != null && v.getWaarde() == this) */ public class JavaObject extends Waarde { /** * @invar | velden != null * @invar | velden.keySet().stream().allMatch(n -> n != null && velden.get(n) != null && velden.get(n).naam == n && velden.get(n).object == this) * @invar | verwijzendeVelden.stream().allMatch(v -> v != null && v.waarde == this) * @representationObject * @peerObjects | velden.values() */ HashMap<String, Veld> velden = new HashMap<>(); /** * @representationObject * @peerObjects */ HashSet<Veld> verwijzendeVelden = new HashSet<>(); /** * @creates | result * @peerObjects | result.values() */ public Map<String, Veld> getVelden() { return Map.copyOf(velden); } /** * @creates | result * @peerObjects */ public Set<Veld> getVerwijzendeVelden() { return Set.copyOf(verwijzendeVelden); } /** * @post | getVelden().isEmpty() * @post | getVerwijzendeVelden().isEmpty() */ public JavaObject() {} /** * @post | result == (this == obj) */ @Override public boolean equals(Object obj) { return this == obj; } public Iterator<JavaObject> getNextIterator() { return new Iterator<JavaObject>() { JavaObject object = JavaObject.this; @Override public boolean hasNext() { return object != null; } @Override public JavaObject next() { JavaObject result = object; if (object.velden.containsKey("next") && object.velden.get("next").waarde instanceof JavaObject o) object = o; else object = null; return result; } }; } public void forEachBereikbaarObject(Consumer<? super JavaObject> consumer) { consumer.accept(this); for (Veld veld : velden.values()) { if (veld.waarde instanceof JavaObject o) o.forEachBereikbaarObject(consumer); } } public Stream<String> getNamenVanObjectenVanVerwijzendeVelden() { return verwijzendeVelden.stream().flatMap(v -> v.object.velden.keySet().stream()); } }
btj/objecten_en_velden
objecten_en_velden/src/objecten_en_velden/JavaObject.java
805
/** * @post | getVelden().isEmpty() * @post | getVerwijzendeVelden().isEmpty() */
block_comment
nl
package objecten_en_velden; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; /** * @invar | getVelden() != null * @invar | getVelden().keySet().stream().allMatch(n -> n != null && getVelden().get(n) != null && getVelden().get(n).getNaam() == n && getVelden().get(n).getObject() == this) * @invar | getVerwijzendeVelden().stream().allMatch(v -> v != null && v.getWaarde() == this) */ public class JavaObject extends Waarde { /** * @invar | velden != null * @invar | velden.keySet().stream().allMatch(n -> n != null && velden.get(n) != null && velden.get(n).naam == n && velden.get(n).object == this) * @invar | verwijzendeVelden.stream().allMatch(v -> v != null && v.waarde == this) * @representationObject * @peerObjects | velden.values() */ HashMap<String, Veld> velden = new HashMap<>(); /** * @representationObject * @peerObjects */ HashSet<Veld> verwijzendeVelden = new HashSet<>(); /** * @creates | result * @peerObjects | result.values() */ public Map<String, Veld> getVelden() { return Map.copyOf(velden); } /** * @creates | result * @peerObjects */ public Set<Veld> getVerwijzendeVelden() { return Set.copyOf(verwijzendeVelden); } /** * @post | getVelden().isEmpty()<SUF>*/ public JavaObject() {} /** * @post | result == (this == obj) */ @Override public boolean equals(Object obj) { return this == obj; } public Iterator<JavaObject> getNextIterator() { return new Iterator<JavaObject>() { JavaObject object = JavaObject.this; @Override public boolean hasNext() { return object != null; } @Override public JavaObject next() { JavaObject result = object; if (object.velden.containsKey("next") && object.velden.get("next").waarde instanceof JavaObject o) object = o; else object = null; return result; } }; } public void forEachBereikbaarObject(Consumer<? super JavaObject> consumer) { consumer.accept(this); for (Veld veld : velden.values()) { if (veld.waarde instanceof JavaObject o) o.forEachBereikbaarObject(consumer); } } public Stream<String> getNamenVanObjectenVanVerwijzendeVelden() { return verwijzendeVelden.stream().flatMap(v -> v.object.velden.keySet().stream()); } }
201379_10
package me.chanjar.weixin.mp.bean.material; import lombok.Data; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; import java.io.Serializable; /** * <pre> * 图文消息article. * 1. thumbMediaId (必填) 图文消息的封面图片素材id(必须是永久mediaID) * 2. author 图文消息的作者 * 3. title (必填) 图文消息的标题 * 4. contentSourceUrl 在图文消息页面点击“阅读原文”后的页面链接 * 5. content (必填) 图文消息页面的内容,支持HTML标签 * 6. digest 图文消息的描述 * 7. showCoverPic 是否显示封面,true为显示,false为不显示 * 8. url 点击图文消息跳转链接 * 9. need_open_comment(新增字段) 否 Uint32 是否打开评论,0不打开,1打开 * 10. only_fans_can_comment(新增字段) 否 Uint32 是否粉丝才可评论,0所有人可评论,1粉丝才可评论 * </pre> * * @author chanjarster */ @Data public class WxMpNewsArticle implements Serializable { private static final long serialVersionUID = -635384661692321171L; /** * (必填) 图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得. */ private String thumbMediaId; /** * 图文消息的封面url. */ private String thumbUrl; /** * 图文消息的作者. */ private String author; /** * (必填) 图文消息的标题. */ private String title; /** * 在图文消息页面点击“阅读原文”后的页面链接. */ private String contentSourceUrl; /** * (必填) 图文消息页面的内容,支持HTML标签. */ private String content; /** * 图文消息的描述. */ private String digest; /** * 是否显示封面,true为显示,false为不显示. */ private boolean showCoverPic; /** * 点击图文消息跳转链接. */ private String url; /** * need_open_comment * 是否打开评论,0不打开,1打开. */ private Boolean needOpenComment; /** * only_fans_can_comment * 是否粉丝才可评论,0所有人可评论,1粉丝才可评论. */ private Boolean onlyFansCanComment; @Override public String toString() { return WxMpGsonBuilder.create().toJson(this); } }
Wechat-Group/WxJava
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpNewsArticle.java
690
/** * need_open_comment * 是否打开评论,0不打开,1打开. */
block_comment
nl
package me.chanjar.weixin.mp.bean.material; import lombok.Data; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; import java.io.Serializable; /** * <pre> * 图文消息article. * 1. thumbMediaId (必填) 图文消息的封面图片素材id(必须是永久mediaID) * 2. author 图文消息的作者 * 3. title (必填) 图文消息的标题 * 4. contentSourceUrl 在图文消息页面点击“阅读原文”后的页面链接 * 5. content (必填) 图文消息页面的内容,支持HTML标签 * 6. digest 图文消息的描述 * 7. showCoverPic 是否显示封面,true为显示,false为不显示 * 8. url 点击图文消息跳转链接 * 9. need_open_comment(新增字段) 否 Uint32 是否打开评论,0不打开,1打开 * 10. only_fans_can_comment(新增字段) 否 Uint32 是否粉丝才可评论,0所有人可评论,1粉丝才可评论 * </pre> * * @author chanjarster */ @Data public class WxMpNewsArticle implements Serializable { private static final long serialVersionUID = -635384661692321171L; /** * (必填) 图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得. */ private String thumbMediaId; /** * 图文消息的封面url. */ private String thumbUrl; /** * 图文消息的作者. */ private String author; /** * (必填) 图文消息的标题. */ private String title; /** * 在图文消息页面点击“阅读原文”后的页面链接. */ private String contentSourceUrl; /** * (必填) 图文消息页面的内容,支持HTML标签. */ private String content; /** * 图文消息的描述. */ private String digest; /** * 是否显示封面,true为显示,false为不显示. */ private boolean showCoverPic; /** * 点击图文消息跳转链接. */ private String url; /** * need_open_comment <SUF>*/ private Boolean needOpenComment; /** * only_fans_can_comment * 是否粉丝才可评论,0所有人可评论,1粉丝才可评论. */ private Boolean onlyFansCanComment; @Override public String toString() { return WxMpGsonBuilder.create().toJson(this); } }
201415_7
/* * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.lang.ref.WeakReference; /* MacOSXPreferencesFile synchronization: Everything is synchronized on MacOSXPreferencesFile.class. This prevents: * simultaneous updates to cachedFiles or changedFiles * simultaneous creation of two objects for the same name+user+host triplet * simultaneous modifications to the same file * modifications during syncWorld/flushWorld * (in MacOSXPreferences.removeNodeSpi()) modification or sync during multi-step node removal process ... among other things. */ /* Timers. There are two timers that control synchronization of prefs data to and from disk. * Sync timer periodically calls syncWorld() to force external disk changes (e.g. from another VM) into the memory cache. The sync timer runs even if there are no outstanding local changes. The sync timer syncs all live MacOSXPreferencesFile objects (the cachedFiles list). The sync timer period is controlled by the java.util.prefs.syncInterval property (same as FileSystemPreferences). By default there is *no* sync timer (unlike FileSystemPreferences); it is only enabled if the syncInterval property is set. The minimum interval is 5 seconds. * Flush timer calls flushWorld() to force local changes to disk. The flush timer is scheduled to fire some time after each pref change, unless it's already scheduled to fire before that. syncWorld and flushWorld will cancel any outstanding flush timer as unnecessary. The flush timer flushes all changed files (the changedFiles list). The time between pref write and flush timer call is controlled by the java.util.prefs.flushDelay property (unlike FileSystemPreferences). The default is 60 seconds and the minimum is 5 seconds. The flush timer's behavior is required by the Java Preferences spec ("changes will eventually propagate to the persistent backing store with an implementation-dependent delay"). The sync timer is not required by the spec (multiple VMs are only required to not corrupt the prefs), but the periodic sync is implemented by FileSystemPreferences and may be useful to some programs. The sync timer is disabled by default because it's expensive and is usually not necessary. */ class MacOSXPreferencesFile { static { loadPrefsLib(); } @SuppressWarnings("removal") private static void loadPrefsLib() { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() { public Void run() { System.loadLibrary("prefs"); return null; } }); } private static class FlushTask extends TimerTask { public void run() { MacOSXPreferencesFile.flushWorld(); } } // Maps string -> weak reference to MacOSXPreferencesFile private static HashMap<String, WeakReference<MacOSXPreferencesFile>> cachedFiles; // Files that may have unflushed changes private static HashSet<MacOSXPreferencesFile> changedFiles; // Timer and pending sync and flush tasks (which are both scheduled // on the same timer) private static Timer timer = null; private static FlushTask flushTimerTask = null; private static long flushDelay = -1; // in seconds (min 5, default 60) private static long syncInterval = -1; // (min 5, default negative == off) private String appName; private long user; private long host; String name() { return appName; } long user() { return user; } long host() { return host; } // private constructor - use factory method getFile() instead private MacOSXPreferencesFile(String newName, long newUser, long newHost) { appName = newName; user = newUser; host = newHost; } // Factory method // Always returns the same object for the given name+user+host static synchronized MacOSXPreferencesFile getFile(String newName, boolean isUser) { MacOSXPreferencesFile result = null; if (cachedFiles == null) cachedFiles = new HashMap<>(); String hashkey = newName + String.valueOf(isUser); WeakReference<MacOSXPreferencesFile> hashvalue = cachedFiles.get(hashkey); if (hashvalue != null) { result = hashvalue.get(); } if (result == null) { // Java user node == CF current user, any host // Java system node == CF any user, current host result = new MacOSXPreferencesFile(newName, isUser ? cfCurrentUser : cfAnyUser, isUser ? cfAnyHost : cfCurrentHost); cachedFiles.put(hashkey, new WeakReference<MacOSXPreferencesFile>(result)); } // Don't schedule this file for flushing until some nodes or // keys are added to it. // Do set up the sync timer if requested; sync timer affects reads // as well as writes. initSyncTimerIfNeeded(); return result; } // Write all prefs changes to disk and clear all cached prefs values // (so the next read will read from disk). static synchronized boolean syncWorld() { boolean ok = true; if (cachedFiles != null && !cachedFiles.isEmpty()) { Iterator<WeakReference<MacOSXPreferencesFile>> iter = cachedFiles.values().iterator(); while (iter.hasNext()) { WeakReference<MacOSXPreferencesFile> ref = iter.next(); MacOSXPreferencesFile f = ref.get(); if (f != null) { if (!f.synchronize()) ok = false; } else { iter.remove(); } } } // Kill any pending flush if (flushTimerTask != null) { flushTimerTask.cancel(); flushTimerTask = null; } // Clear changed file list. The changed files were guaranteed to // have been in the cached file list (because there was a strong // reference from changedFiles. if (changedFiles != null) changedFiles.clear(); return ok; } // Sync only current user preferences static synchronized boolean syncUser() { boolean ok = true; if (cachedFiles != null && !cachedFiles.isEmpty()) { Iterator<WeakReference<MacOSXPreferencesFile>> iter = cachedFiles.values().iterator(); while (iter.hasNext()) { WeakReference<MacOSXPreferencesFile> ref = iter.next(); MacOSXPreferencesFile f = ref.get(); if (f != null && f.user == cfCurrentUser) { if (!f.synchronize()) { ok = false; } } else { iter.remove(); } } } // Remove synchronized file from changed file list. The changed files were // guaranteed to have been in the cached file list (because there was a strong // reference from changedFiles. if (changedFiles != null) { Iterator<MacOSXPreferencesFile> iterChanged = changedFiles.iterator(); while (iterChanged.hasNext()) { MacOSXPreferencesFile f = iterChanged.next(); if (f != null && f.user == cfCurrentUser) iterChanged.remove(); } } return ok; } //Flush only current user preferences static synchronized boolean flushUser() { boolean ok = true; if (changedFiles != null && !changedFiles.isEmpty()) { Iterator<MacOSXPreferencesFile> iterator = changedFiles.iterator(); while(iterator.hasNext()) { MacOSXPreferencesFile f = iterator.next(); if (f.user == cfCurrentUser) { if (!f.synchronize()) ok = false; else iterator.remove(); } } } return ok; } // Write all prefs changes to disk, but do not clear all cached prefs // values. Also kills any scheduled flush task. // There's no CFPreferencesFlush() (<rdar://problem/3049129>), so lots of cached prefs // are cleared anyway. static synchronized boolean flushWorld() { boolean ok = true; if (changedFiles != null && !changedFiles.isEmpty()) { for (MacOSXPreferencesFile f : changedFiles) { if (!f.synchronize()) ok = false; } changedFiles.clear(); } if (flushTimerTask != null) { flushTimerTask.cancel(); flushTimerTask = null; } return ok; } // Mark this prefs file as changed. The changes will be flushed in // at most flushDelay() seconds. // Must be called when synchronized on MacOSXPreferencesFile.class private void markChanged() { // Add this file to the changed file list if (changedFiles == null) changedFiles = new HashSet<>(); changedFiles.add(this); // Schedule a new flush and a shutdown hook, if necessary if (flushTimerTask == null) { flushTimerTask = new FlushTask(); timer().schedule(flushTimerTask, flushDelay() * 1000); } } // Return the flush delay, initializing from a property if necessary. private static synchronized long flushDelay() { if (flushDelay == -1) { try { // flush delay >= 5, default 60 flushDelay = Math.max(5, Integer.parseInt(System.getProperty("java.util.prefs.flushDelay", "60"))); } catch (NumberFormatException e) { flushDelay = 60; } } return flushDelay; } // Initialize and run the sync timer, if the sync timer property is set // and the sync timer hasn't already been started. private static synchronized void initSyncTimerIfNeeded() { // syncInterval: -1 is uninitialized, other negative is off, // positive is seconds between syncs (min 5). if (syncInterval == -1) { try { syncInterval = Integer.parseInt(System.getProperty("java.util.prefs.syncInterval", "-2")); if (syncInterval >= 0) { // minimum of 5 seconds syncInterval = Math.max(5, syncInterval); } else { syncInterval = -2; // default off } } catch (NumberFormatException e) { syncInterval = -2; // bad property value - default off } if (syncInterval > 0) { timer().schedule(new TimerTask() { @Override public void run() { MacOSXPreferencesFile.syncWorld();} }, syncInterval * 1000, syncInterval * 1000); } else { // syncInterval property not set. No sync timer ever. } } } // Return the timer used for flush and sync, creating it if necessary. private static synchronized Timer timer() { if (timer == null) { timer = new Timer(true); // daemon Thread flushThread = new Thread(null, null, "Flush Thread", 0, false) { @Override public void run() { flushWorld(); } }; /* Set context class loader to null in order to avoid * keeping a strong reference to an application classloader. */ flushThread.setContextClassLoader(null); Runtime.getRuntime().addShutdownHook(flushThread); } return timer; } // Node manipulation boolean addNode(String path) { synchronized(MacOSXPreferencesFile.class) { markChanged(); return addNode(path, appName, user, host); } } void removeNode(String path) { synchronized(MacOSXPreferencesFile.class) { markChanged(); removeNode(path, appName, user, host); } } boolean addChildToNode(String path, String child) { synchronized(MacOSXPreferencesFile.class) { markChanged(); return addChildToNode(path, child+"/", appName, user, host); } } void removeChildFromNode(String path, String child) { synchronized(MacOSXPreferencesFile.class) { markChanged(); removeChildFromNode(path, child+"/", appName, user, host); } } // Key manipulation void addKeyToNode(String path, String key, String value) { synchronized(MacOSXPreferencesFile.class) { markChanged(); addKeyToNode(path, key, value, appName, user, host); } } void removeKeyFromNode(String path, String key) { synchronized(MacOSXPreferencesFile.class) { markChanged(); removeKeyFromNode(path, key, appName, user, host); } } String getKeyFromNode(String path, String key) { synchronized(MacOSXPreferencesFile.class) { return getKeyFromNode(path, key, appName, user, host); } } // Enumerators String[] getChildrenForNode(String path) { synchronized(MacOSXPreferencesFile.class) { return getChildrenForNode(path, appName, user, host); } } String[] getKeysForNode(String path) { synchronized(MacOSXPreferencesFile.class) { return getKeysForNode(path, appName, user, host); } } // Synchronization boolean synchronize() { synchronized(MacOSXPreferencesFile.class) { return synchronize(appName, user, host); } } // CF functions // Must be called when synchronized on MacOSXPreferencesFile.class private static final native boolean addNode(String path, String name, long user, long host); private static final native void removeNode(String path, String name, long user, long host); private static final native boolean addChildToNode(String path, String child, String name, long user, long host); private static final native void removeChildFromNode(String path, String child, String name, long user, long host); private static final native void addKeyToNode(String path, String key, String value, String name, long user, long host); private static final native void removeKeyFromNode(String path, String key, String name, long user, long host); private static final native String getKeyFromNode(String path, String key, String name, long user, long host); private static final native String[] getChildrenForNode(String path, String name, long user, long host); private static final native String[] getKeysForNode(String path, String name, long user, long host); private static final native boolean synchronize(String name, long user, long host); // CFPreferences host and user values (CFStringRefs) private static long cfCurrentUser = currentUser(); private static long cfAnyUser = anyUser(); private static long cfCurrentHost = currentHost(); private static long cfAnyHost = anyHost(); // CFPreferences constant accessors private static final native long currentUser(); private static final native long anyUser(); private static final native long currentHost(); private static final native long anyHost(); }
openjdk/jdk
src/java.prefs/macosx/classes/java/util/prefs/MacOSXPreferencesFile.java
4,029
// in seconds (min 5, default 60)
line_comment
nl
/* * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.lang.ref.WeakReference; /* MacOSXPreferencesFile synchronization: Everything is synchronized on MacOSXPreferencesFile.class. This prevents: * simultaneous updates to cachedFiles or changedFiles * simultaneous creation of two objects for the same name+user+host triplet * simultaneous modifications to the same file * modifications during syncWorld/flushWorld * (in MacOSXPreferences.removeNodeSpi()) modification or sync during multi-step node removal process ... among other things. */ /* Timers. There are two timers that control synchronization of prefs data to and from disk. * Sync timer periodically calls syncWorld() to force external disk changes (e.g. from another VM) into the memory cache. The sync timer runs even if there are no outstanding local changes. The sync timer syncs all live MacOSXPreferencesFile objects (the cachedFiles list). The sync timer period is controlled by the java.util.prefs.syncInterval property (same as FileSystemPreferences). By default there is *no* sync timer (unlike FileSystemPreferences); it is only enabled if the syncInterval property is set. The minimum interval is 5 seconds. * Flush timer calls flushWorld() to force local changes to disk. The flush timer is scheduled to fire some time after each pref change, unless it's already scheduled to fire before that. syncWorld and flushWorld will cancel any outstanding flush timer as unnecessary. The flush timer flushes all changed files (the changedFiles list). The time between pref write and flush timer call is controlled by the java.util.prefs.flushDelay property (unlike FileSystemPreferences). The default is 60 seconds and the minimum is 5 seconds. The flush timer's behavior is required by the Java Preferences spec ("changes will eventually propagate to the persistent backing store with an implementation-dependent delay"). The sync timer is not required by the spec (multiple VMs are only required to not corrupt the prefs), but the periodic sync is implemented by FileSystemPreferences and may be useful to some programs. The sync timer is disabled by default because it's expensive and is usually not necessary. */ class MacOSXPreferencesFile { static { loadPrefsLib(); } @SuppressWarnings("removal") private static void loadPrefsLib() { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() { public Void run() { System.loadLibrary("prefs"); return null; } }); } private static class FlushTask extends TimerTask { public void run() { MacOSXPreferencesFile.flushWorld(); } } // Maps string -> weak reference to MacOSXPreferencesFile private static HashMap<String, WeakReference<MacOSXPreferencesFile>> cachedFiles; // Files that may have unflushed changes private static HashSet<MacOSXPreferencesFile> changedFiles; // Timer and pending sync and flush tasks (which are both scheduled // on the same timer) private static Timer timer = null; private static FlushTask flushTimerTask = null; private static long flushDelay = -1; // in seconds<SUF> private static long syncInterval = -1; // (min 5, default negative == off) private String appName; private long user; private long host; String name() { return appName; } long user() { return user; } long host() { return host; } // private constructor - use factory method getFile() instead private MacOSXPreferencesFile(String newName, long newUser, long newHost) { appName = newName; user = newUser; host = newHost; } // Factory method // Always returns the same object for the given name+user+host static synchronized MacOSXPreferencesFile getFile(String newName, boolean isUser) { MacOSXPreferencesFile result = null; if (cachedFiles == null) cachedFiles = new HashMap<>(); String hashkey = newName + String.valueOf(isUser); WeakReference<MacOSXPreferencesFile> hashvalue = cachedFiles.get(hashkey); if (hashvalue != null) { result = hashvalue.get(); } if (result == null) { // Java user node == CF current user, any host // Java system node == CF any user, current host result = new MacOSXPreferencesFile(newName, isUser ? cfCurrentUser : cfAnyUser, isUser ? cfAnyHost : cfCurrentHost); cachedFiles.put(hashkey, new WeakReference<MacOSXPreferencesFile>(result)); } // Don't schedule this file for flushing until some nodes or // keys are added to it. // Do set up the sync timer if requested; sync timer affects reads // as well as writes. initSyncTimerIfNeeded(); return result; } // Write all prefs changes to disk and clear all cached prefs values // (so the next read will read from disk). static synchronized boolean syncWorld() { boolean ok = true; if (cachedFiles != null && !cachedFiles.isEmpty()) { Iterator<WeakReference<MacOSXPreferencesFile>> iter = cachedFiles.values().iterator(); while (iter.hasNext()) { WeakReference<MacOSXPreferencesFile> ref = iter.next(); MacOSXPreferencesFile f = ref.get(); if (f != null) { if (!f.synchronize()) ok = false; } else { iter.remove(); } } } // Kill any pending flush if (flushTimerTask != null) { flushTimerTask.cancel(); flushTimerTask = null; } // Clear changed file list. The changed files were guaranteed to // have been in the cached file list (because there was a strong // reference from changedFiles. if (changedFiles != null) changedFiles.clear(); return ok; } // Sync only current user preferences static synchronized boolean syncUser() { boolean ok = true; if (cachedFiles != null && !cachedFiles.isEmpty()) { Iterator<WeakReference<MacOSXPreferencesFile>> iter = cachedFiles.values().iterator(); while (iter.hasNext()) { WeakReference<MacOSXPreferencesFile> ref = iter.next(); MacOSXPreferencesFile f = ref.get(); if (f != null && f.user == cfCurrentUser) { if (!f.synchronize()) { ok = false; } } else { iter.remove(); } } } // Remove synchronized file from changed file list. The changed files were // guaranteed to have been in the cached file list (because there was a strong // reference from changedFiles. if (changedFiles != null) { Iterator<MacOSXPreferencesFile> iterChanged = changedFiles.iterator(); while (iterChanged.hasNext()) { MacOSXPreferencesFile f = iterChanged.next(); if (f != null && f.user == cfCurrentUser) iterChanged.remove(); } } return ok; } //Flush only current user preferences static synchronized boolean flushUser() { boolean ok = true; if (changedFiles != null && !changedFiles.isEmpty()) { Iterator<MacOSXPreferencesFile> iterator = changedFiles.iterator(); while(iterator.hasNext()) { MacOSXPreferencesFile f = iterator.next(); if (f.user == cfCurrentUser) { if (!f.synchronize()) ok = false; else iterator.remove(); } } } return ok; } // Write all prefs changes to disk, but do not clear all cached prefs // values. Also kills any scheduled flush task. // There's no CFPreferencesFlush() (<rdar://problem/3049129>), so lots of cached prefs // are cleared anyway. static synchronized boolean flushWorld() { boolean ok = true; if (changedFiles != null && !changedFiles.isEmpty()) { for (MacOSXPreferencesFile f : changedFiles) { if (!f.synchronize()) ok = false; } changedFiles.clear(); } if (flushTimerTask != null) { flushTimerTask.cancel(); flushTimerTask = null; } return ok; } // Mark this prefs file as changed. The changes will be flushed in // at most flushDelay() seconds. // Must be called when synchronized on MacOSXPreferencesFile.class private void markChanged() { // Add this file to the changed file list if (changedFiles == null) changedFiles = new HashSet<>(); changedFiles.add(this); // Schedule a new flush and a shutdown hook, if necessary if (flushTimerTask == null) { flushTimerTask = new FlushTask(); timer().schedule(flushTimerTask, flushDelay() * 1000); } } // Return the flush delay, initializing from a property if necessary. private static synchronized long flushDelay() { if (flushDelay == -1) { try { // flush delay >= 5, default 60 flushDelay = Math.max(5, Integer.parseInt(System.getProperty("java.util.prefs.flushDelay", "60"))); } catch (NumberFormatException e) { flushDelay = 60; } } return flushDelay; } // Initialize and run the sync timer, if the sync timer property is set // and the sync timer hasn't already been started. private static synchronized void initSyncTimerIfNeeded() { // syncInterval: -1 is uninitialized, other negative is off, // positive is seconds between syncs (min 5). if (syncInterval == -1) { try { syncInterval = Integer.parseInt(System.getProperty("java.util.prefs.syncInterval", "-2")); if (syncInterval >= 0) { // minimum of 5 seconds syncInterval = Math.max(5, syncInterval); } else { syncInterval = -2; // default off } } catch (NumberFormatException e) { syncInterval = -2; // bad property value - default off } if (syncInterval > 0) { timer().schedule(new TimerTask() { @Override public void run() { MacOSXPreferencesFile.syncWorld();} }, syncInterval * 1000, syncInterval * 1000); } else { // syncInterval property not set. No sync timer ever. } } } // Return the timer used for flush and sync, creating it if necessary. private static synchronized Timer timer() { if (timer == null) { timer = new Timer(true); // daemon Thread flushThread = new Thread(null, null, "Flush Thread", 0, false) { @Override public void run() { flushWorld(); } }; /* Set context class loader to null in order to avoid * keeping a strong reference to an application classloader. */ flushThread.setContextClassLoader(null); Runtime.getRuntime().addShutdownHook(flushThread); } return timer; } // Node manipulation boolean addNode(String path) { synchronized(MacOSXPreferencesFile.class) { markChanged(); return addNode(path, appName, user, host); } } void removeNode(String path) { synchronized(MacOSXPreferencesFile.class) { markChanged(); removeNode(path, appName, user, host); } } boolean addChildToNode(String path, String child) { synchronized(MacOSXPreferencesFile.class) { markChanged(); return addChildToNode(path, child+"/", appName, user, host); } } void removeChildFromNode(String path, String child) { synchronized(MacOSXPreferencesFile.class) { markChanged(); removeChildFromNode(path, child+"/", appName, user, host); } } // Key manipulation void addKeyToNode(String path, String key, String value) { synchronized(MacOSXPreferencesFile.class) { markChanged(); addKeyToNode(path, key, value, appName, user, host); } } void removeKeyFromNode(String path, String key) { synchronized(MacOSXPreferencesFile.class) { markChanged(); removeKeyFromNode(path, key, appName, user, host); } } String getKeyFromNode(String path, String key) { synchronized(MacOSXPreferencesFile.class) { return getKeyFromNode(path, key, appName, user, host); } } // Enumerators String[] getChildrenForNode(String path) { synchronized(MacOSXPreferencesFile.class) { return getChildrenForNode(path, appName, user, host); } } String[] getKeysForNode(String path) { synchronized(MacOSXPreferencesFile.class) { return getKeysForNode(path, appName, user, host); } } // Synchronization boolean synchronize() { synchronized(MacOSXPreferencesFile.class) { return synchronize(appName, user, host); } } // CF functions // Must be called when synchronized on MacOSXPreferencesFile.class private static final native boolean addNode(String path, String name, long user, long host); private static final native void removeNode(String path, String name, long user, long host); private static final native boolean addChildToNode(String path, String child, String name, long user, long host); private static final native void removeChildFromNode(String path, String child, String name, long user, long host); private static final native void addKeyToNode(String path, String key, String value, String name, long user, long host); private static final native void removeKeyFromNode(String path, String key, String name, long user, long host); private static final native String getKeyFromNode(String path, String key, String name, long user, long host); private static final native String[] getChildrenForNode(String path, String name, long user, long host); private static final native String[] getKeysForNode(String path, String name, long user, long host); private static final native boolean synchronize(String name, long user, long host); // CFPreferences host and user values (CFStringRefs) private static long cfCurrentUser = currentUser(); private static long cfAnyUser = anyUser(); private static long cfCurrentHost = currentHost(); private static long cfAnyHost = anyHost(); // CFPreferences constant accessors private static final native long currentUser(); private static final native long anyUser(); private static final native long currentHost(); private static final native long anyHost(); }
201421_20
/* * Copyright 2015 Realm 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 io.realm; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import io.realm.exceptions.RealmFileException; import io.realm.internal.Capabilities; import io.realm.internal.ObjectServerFacade; import io.realm.internal.OsObjectStore; import io.realm.internal.OsRealmConfig; import io.realm.internal.OsSharedRealm; import io.realm.internal.RealmNotifier; import io.realm.internal.Util; import io.realm.internal.android.AndroidCapabilities; import io.realm.internal.android.AndroidRealmNotifier; import io.realm.internal.async.RealmAsyncTaskImpl; import io.realm.internal.util.Pair; import io.realm.log.RealmLog; /** * To cache {@link Realm}, {@link DynamicRealm} instances and related resources. * Every thread will share the same {@link Realm} and {@link DynamicRealm} instances which are referred to the same * {@link RealmConfiguration}. * One {@link RealmCache} is created for each {@link RealmConfiguration}, and it caches all the {@link Realm} and * {@link DynamicRealm} instances which are created from the same {@link RealmConfiguration}. */ final class RealmCache { interface Callback { void onResult(int count); } interface Callback0 { void onCall(); } private abstract static class ReferenceCounter { // How many references to this Realm instance in this thread. protected final ThreadLocal<Integer> localCount = new ThreadLocal<>(); // How many threads have instances refer to this configuration. protected AtomicInteger globalCount = new AtomicInteger(0); // Returns `true` if an instance of the Realm is available on the caller thread. abstract boolean hasInstanceAvailableForThread(); // Increment how many times an instance has been handed out for the current thread. public void incrementThreadCount(int increment) { Integer currentCount = localCount.get(); localCount.set(currentCount != null ? currentCount + increment : increment); } // Returns the Realm instance for the caller thread abstract BaseRealm getRealmInstance(); // Cache the Realm instance. Should only be called when `hasInstanceAvailableForThread` returns false. abstract void onRealmCreated(BaseRealm realm); // Clears the the cache for a given thread when all Realms on that thread are closed. abstract void clearThreadLocalCache(); // Returns the number of instances handed out for the caller thread. abstract int getThreadLocalCount(); // Updates the number of references handed out for a given thread public void setThreadCount(int refCount) { localCount.set(refCount); } // Returns the number of gloal instances handed out. This is roughly equivalent // to the number of threads currently using the Realm as each thread also does // reference counting of Realm instances. public int getGlobalCount() { return globalCount.get(); } } // Reference counter for Realms that are accessible across all threads private static class GlobalReferenceCounter extends ReferenceCounter { private BaseRealm cachedRealm; @Override boolean hasInstanceAvailableForThread() { return cachedRealm != null; } @Override BaseRealm getRealmInstance() { return cachedRealm; } @Override void onRealmCreated(BaseRealm realm) { // The Realm instance has been created without exceptions. Cache and reference count can be updated now. cachedRealm = realm; localCount.set(0); // This is the first instance in current thread, increase the global count. globalCount.incrementAndGet(); } @Override public void clearThreadLocalCache() { String canonicalPath = cachedRealm.getPath(); // The last instance in this thread. // Clears local ref & counter. localCount.set(null); cachedRealm = null; // Clears global counter. if (globalCount.decrementAndGet() < 0) { // Should never happen. throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " not be negative."); } } @Override int getThreadLocalCount() { // For frozen Realms the Realm can be accessed from all threads, so the concept // of a thread local count doesn't make sense. Just return the global count instead. return globalCount.get(); } } // Reference counter for Realms that are thread confined private static class ThreadConfinedReferenceCounter extends ReferenceCounter { // The Realm instance in this thread. private final ThreadLocal<BaseRealm> localRealm = new ThreadLocal<>(); @Override public boolean hasInstanceAvailableForThread() { return localRealm.get() != null; } @Override public BaseRealm getRealmInstance() { return localRealm.get(); } @Override public void onRealmCreated(BaseRealm realm) { // The Realm instance has been created without exceptions. Cache and reference count can be updated now. localRealm.set(realm); localCount.set(0); // This is the first instance in current thread, increase the global count. globalCount.incrementAndGet(); } @Override public void clearThreadLocalCache() { String canonicalPath = localRealm.get().getPath(); // The last instance in this thread. // Clears local ref & counter. localCount.set(null); localRealm.set(null); // Clears global counter. if (globalCount.decrementAndGet() < 0) { // Should never happen. throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " can not be negative."); } } @Override public int getThreadLocalCount() { Integer refCount = localCount.get(); return (refCount != null) ? refCount : 0; } } private enum RealmCacheType { TYPED_REALM, DYNAMIC_REALM; static RealmCacheType valueOf(Class<? extends BaseRealm> clazz) { if (clazz == Realm.class) { return TYPED_REALM; } else if (clazz == DynamicRealm.class) { return DYNAMIC_REALM; } throw new IllegalArgumentException(WRONG_REALM_CLASS_MESSAGE); } } private static class CreateRealmRunnable<T extends BaseRealm> implements Runnable { private final RealmConfiguration configuration; private final BaseRealm.InstanceCallback<T> callback; private final Class<T> realmClass; private final CountDownLatch canReleaseBackgroundInstanceLatch = new CountDownLatch(1); private final RealmNotifier notifier; // The Future this runnable belongs to. private Future future; CreateRealmRunnable(RealmNotifier notifier, RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { this.configuration = configuration; this.realmClass = realmClass; this.callback = callback; this.notifier = notifier; } public void setFuture(Future future) { this.future = future; } @Override public void run() { T instance = null; try { // First call that will run all schema validation, migrations or initial transactions. instance = createRealmOrGetFromCache(configuration, realmClass); boolean results = notifier.post(new Runnable() { @Override public void run() { // If the RealmAsyncTask.cancel() is called before, we just return without creating the Realm // instance on the caller thread. // Thread.isInterrupted() cannot be used for checking here since CountDownLatch.await() will // will clear interrupted status. // Using the future to check which this runnable belongs to is to ensure if it is canceled from // the caller thread before, the callback will never be delivered. if (future == null || future.isCancelled()) { canReleaseBackgroundInstanceLatch.countDown(); return; } T instanceToReturn = null; Throwable throwable = null; try { // This will run on the caller thread, but since the first `createRealmOrGetFromCache` // should have completed at this point, all expensive initializer functions have already // run. instanceToReturn = createRealmOrGetFromCache(configuration, realmClass); } catch (Throwable e) { throwable = e; } finally { canReleaseBackgroundInstanceLatch.countDown(); } if (instanceToReturn != null) { callback.onSuccess(instanceToReturn); } else { // throwable is non-null //noinspection ConstantConditions callback.onError(throwable); } } }); if (!results) { canReleaseBackgroundInstanceLatch.countDown(); } // There is a small chance that the posted runnable cannot be executed because of the thread terminated // before the runnable gets fetched from the event queue. if (!canReleaseBackgroundInstanceLatch.await(2, TimeUnit.SECONDS)) { RealmLog.warn("Timeout for creating Realm instance in foreground thread in `CreateRealmRunnable` "); } } catch (InterruptedException e) { RealmLog.warn(e, "`CreateRealmRunnable` has been interrupted."); } catch (final Throwable e) { // DownloadingRealmInterruptedException is treated specially. // It async open is canceled, this could interrupt the download, but the user should // not care in this case, so just ignore it. if (!ObjectServerFacade.getSyncFacadeIfPossible().wasDownloadInterrupted(e)) { RealmLog.error(e, "`CreateRealmRunnable` failed."); notifier.post(new Runnable() { @Override public void run() { callback.onError(e); } }); } } finally { if (instance != null) { instance.close(); } } } } private static final String ASYNC_NOT_ALLOWED_MSG = "Realm instances cannot be loaded asynchronously on a non-looper thread."; private static final String ASYNC_CALLBACK_NULL_MSG = "The callback cannot be null."; // Separated references and counters for typed Realm and dynamic Realm. private final Map<Pair<RealmCacheType, OsSharedRealm.VersionID>, ReferenceCounter> refAndCountMap = new HashMap<>(); // Path to the Realm file to identify this cache. private final String realmPath; // This will be only valid if getTotalGlobalRefCount() > 0. // NOTE: We do reset this when globalCount reaches 0, but if exception thrown in doCreateRealmOrGetFromCache at the // first time when globalCount == 0, this could have a non-null value but it will be reset when the next // doCreateRealmOrGetFromCache is called with globalCount == 0. private RealmConfiguration configuration; // Realm path will be used to identify different RealmCaches. Different Realm configurations with same path // are not allowed and an exception will be thrown when trying to add it to the cache list. // A weak ref is used to hold the RealmCache instance. The weak ref entry will be cleared if and only if there // is no Realm instance holding a strong ref to it and there is no Realm instance associated it is BEING created. private static final List<WeakReference<RealmCache>> cachesList = new ArrayList<WeakReference<RealmCache>>(); // See leak() // isLeaked flag is used to avoid adding strong ref multiple times without iterating the list. private final AtomicBoolean isLeaked = new AtomicBoolean(false); // Keep strong ref to the leaked RealmCache @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private static final Collection<RealmCache> leakedCaches = new ConcurrentLinkedQueue<RealmCache>(); // Keeps track if a Realm needs to download its initial remote data private final Set<String> pendingRealmFileCreation = new HashSet<>(); private static final String DIFFERENT_KEY_MESSAGE = "Wrong key used to decrypt Realm."; private static final String WRONG_REALM_CLASS_MESSAGE = "The type of Realm class must be Realm or DynamicRealm."; private RealmCache(String path) { realmPath = path; } private static RealmCache getCache(String realmPath, boolean createIfNotExist) { RealmCache cacheToReturn = null; synchronized (cachesList) { Iterator<WeakReference<RealmCache>> it = cachesList.iterator(); while (it.hasNext()) { RealmCache cache = it.next().get(); if (cache == null) { // Clear the entry if there is no one holding the RealmCache. it.remove(); } else if (cache.realmPath.equals(realmPath)) { cacheToReturn = cache; } } if (cacheToReturn == null && createIfNotExist) { cacheToReturn = new RealmCache(realmPath); cachesList.add(new WeakReference<RealmCache>(cacheToReturn)); } } return cacheToReturn; } static <T extends BaseRealm> RealmAsyncTask createRealmOrGetFromCacheAsync( RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCacheAsync(configuration, callback, realmClass); } private synchronized <T extends BaseRealm> RealmAsyncTask doCreateRealmOrGetFromCacheAsync( RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { Capabilities capabilities = new AndroidCapabilities(); capabilities.checkCanDeliverNotification(ASYNC_NOT_ALLOWED_MSG); //noinspection ConstantConditions if (callback == null) { throw new IllegalArgumentException(ASYNC_CALLBACK_NULL_MSG); } // If there is no Realm file it means that we need to sync the initial remote data in the worker thread. if (configuration.isSyncConfiguration() && !configuration.realmExists()) { pendingRealmFileCreation.add(configuration.getPath()); } // Always create a Realm instance in the background thread even when there are instances existing on current // thread. This to ensure that onSuccess will always be called in the following event loop but not current one. CreateRealmRunnable<T> createRealmRunnable = new CreateRealmRunnable<T>( new AndroidRealmNotifier(null, capabilities), configuration, callback, realmClass); Future<?> future = BaseRealm.asyncTaskExecutor.submitTransaction(createRealmRunnable); createRealmRunnable.setFuture(future); // For Realms using Async Open on the server, we need to create the session right away // in order to interact with it in a imperative way, e.g. by attaching download progress // listeners ObjectServerFacade.getSyncFacadeIfPossible().createNativeSyncSession(configuration); return new RealmAsyncTaskImpl(future, BaseRealm.asyncTaskExecutor); } /** * Creates a new Realm instance or get an existing instance for current thread. * * @param configuration {@link RealmConfiguration} will be used to create or get the instance. * @param realmClass class of {@link Realm} or {@link DynamicRealm} to be created in or gotten from the cache. * @return the {@link Realm} or {@link DynamicRealm} instance. */ static <E extends BaseRealm> E createRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCache(configuration, realmClass, OsSharedRealm.VersionID.LIVE); } static <E extends BaseRealm> E createRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCache(configuration, realmClass, version); } private synchronized <E extends BaseRealm> E doCreateRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { ReferenceCounter referenceCounter = getRefCounter(realmClass, version); boolean firstRealmInstanceInProcess = (getTotalGlobalRefCount() == 0); if (firstRealmInstanceInProcess) { copyAssetFileIfNeeded(configuration); // If waitForInitialRemoteData() was enabled, we need to make sure that all data is downloaded // before proceeding. We need to open the Realm instance first to start any potential underlying // SyncSession so this will work. boolean realmFileIsBeingCreated = !configuration.realmExists(); if (configuration.isSyncConfiguration() && (realmFileIsBeingCreated || pendingRealmFileCreation.contains(configuration.getPath()))) { // Manually create the Java session wrapper session as this might otherwise // not be created OsRealmConfig osConfig = new OsRealmConfig.Builder(configuration).build(); ObjectServerFacade.getSyncFacadeIfPossible().wrapObjectStoreSessionIfRequired(osConfig); // Fully synchronized Realms are supported by AsyncOpen ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialRemoteChanges(configuration); // Initial remote data has been synced at this point pendingRealmFileCreation.remove(configuration.getPath()); } // We are holding the lock, and we can set the valid configuration since there is no global ref to it. this.configuration = configuration; } else { // Throws exception if validation failed. validateConfiguration(configuration); } if (!referenceCounter.hasInstanceAvailableForThread()) { createInstance(realmClass, referenceCounter, version); } referenceCounter.incrementThreadCount(1); //noinspection unchecked E realmInstance = (E) referenceCounter.getRealmInstance(); if (firstRealmInstanceInProcess) { // If flexible sync initial subscriptions are configured, we need to make // sure they are in the COMPLETE state before proceeding // TODO Ideally this would be part of `downloadInitialRemoteChanges` called before // but his requires a larger refactor, so for now just run the logic here. ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialFlexibleSyncData( Realm.createInstance(realmInstance.sharedRealm), configuration ); if (!configuration.isReadOnly()) { realmInstance.refresh(); } } return realmInstance; } private <E extends BaseRealm> ReferenceCounter getRefCounter(Class<E> realmClass, OsSharedRealm.VersionID version) { RealmCacheType cacheType = RealmCacheType.valueOf(realmClass); Pair<RealmCacheType, OsSharedRealm.VersionID> key = new Pair<>(cacheType, version); ReferenceCounter refCounter = refAndCountMap.get(key); if (refCounter == null) { if (version.equals(OsSharedRealm.VersionID.LIVE)) { refCounter = new ThreadConfinedReferenceCounter(); } else { refCounter = new GlobalReferenceCounter(); } refAndCountMap.put(key, refCounter); } return refCounter; } private <E extends BaseRealm> void createInstance(Class<E> realmClass, ReferenceCounter referenceCounter, OsSharedRealm.VersionID version) { // Creates a new local Realm instance BaseRealm realm; if (realmClass == Realm.class) { // RealmMigrationNeededException might be thrown here. realm = Realm.createInstance(this, version); // Only create mappings after the Realm was opened, so schema mismatch is correctly // thrown by ObjectStore when checking the schema. realm.getSchema().createKeyPathMapping(); } else if (realmClass == DynamicRealm.class) { realm = DynamicRealm.createInstance(this, version); } else { throw new IllegalArgumentException(WRONG_REALM_CLASS_MESSAGE); } referenceCounter.onRealmCreated(realm); } /** * Releases a given {@link Realm} or {@link DynamicRealm} from cache. The instance will be closed by this method * if there is no more local reference to this Realm instance in current Thread. * * @param realm Realm instance to be released from cache. */ synchronized void release(BaseRealm realm) { String canonicalPath = realm.getPath(); ReferenceCounter referenceCounter = getRefCounter(realm.getClass(), (realm.isFrozen()) ? realm.sharedRealm.getVersionID() : OsSharedRealm.VersionID.LIVE); int refCount = referenceCounter.getThreadLocalCount(); if (refCount <= 0) { RealmLog.warn("%s has been closed already. refCount is %s", canonicalPath, refCount); return; } // Decreases the local counter. refCount -= 1; if (refCount == 0) { referenceCounter.clearThreadLocalCache(); // No more local reference to this Realm in current thread, close the instance. realm.doClose(); // No more instance of typed Realm and dynamic Realm. if (getTotalLiveRealmGlobalRefCount() == 0) { // We keep the cache in the caches list even when its global counter reaches 0. It will be reused when // next time a Realm instance with the same path is opened. By not removing it, the lock on // cachesList is not needed here. configuration = null; // Close all frozen Realms. This can introduce race conditions on other // threads if the lifecyle of using Realm data is not correctly controlled. for (ReferenceCounter counter : refAndCountMap.values()) { if (counter instanceof GlobalReferenceCounter) { BaseRealm cachedRealm = counter.getRealmInstance(); // Since we don't remove ReferenceCounters, we need to check if the Realm is still open if (cachedRealm != null) { // Gracefully close frozen Realms in a similar way to what a user would normally do. while (!cachedRealm.isClosed()) { cachedRealm.close(); } } } } ObjectServerFacade.getFacade(realm.getConfiguration().isSyncConfiguration()).realmClosed(realm.getConfiguration()); } } else { referenceCounter.setThreadCount(refCount); } } /** * Makes sure that the new configuration doesn't clash with any cached configurations for the * Realm. * * @throws IllegalArgumentException if the new configuration isn't valid. */ private void validateConfiguration(RealmConfiguration newConfiguration) { if (configuration.equals(newConfiguration)) { // Same configuration objects. return; } // Checks that encryption keys aren't different. key is not in RealmConfiguration's toString. if (!Arrays.equals(configuration.getEncryptionKey(), newConfiguration.getEncryptionKey())) { throw new IllegalArgumentException(DIFFERENT_KEY_MESSAGE); } else { // A common problem is that people are forgetting to override `equals` in their custom migration class. // Tries to detect this problem specifically so we can throw a better error message. RealmMigration newMigration = newConfiguration.getMigration(); RealmMigration oldMigration = configuration.getMigration(); if (oldMigration != null && newMigration != null && oldMigration.getClass().equals(newMigration.getClass()) && !newMigration.equals(oldMigration)) { throw new IllegalArgumentException("Configurations cannot be different if used to open the same file. " + "The most likely cause is that equals() and hashCode() are not overridden in the " + "migration class: " + newConfiguration.getMigration().getClass().getCanonicalName()); } throw new IllegalArgumentException("Configurations cannot be different if used to open the same file. " + "\nCached configuration: \n" + configuration + "\n\nNew configuration: \n" + newConfiguration); } } /** * Runs the callback function with the total reference count of {@link Realm} and {@link DynamicRealm} who refer to * the given {@link RealmConfiguration}. * * @param configuration the {@link RealmConfiguration} of {@link Realm} or {@link DynamicRealm}. * @param callback the callback will be executed with the global reference count. */ static void invokeWithGlobalRefCount(RealmConfiguration configuration, Callback callback) { // NOTE: Although getCache is locked on the cacheMap, this whole method needs to be lock with it as // well. Since we need to ensure there is no Realm instance can be opened when this method is called (for // deleteRealm). // Recursive lock cannot be avoided here. synchronized (cachesList) { RealmCache cache = getCache(configuration.getPath(), false); if (cache == null) { callback.onResult(0); return; } cache.doInvokeWithGlobalRefCount(callback); } } private synchronized void doInvokeWithGlobalRefCount(Callback callback) { callback.onResult(getTotalGlobalRefCount()); } /** * Runs the callback function with synchronization on {@link RealmCache}. * * @param callback the callback will be executed. */ synchronized void invokeWithLock(Callback0 callback) { callback.onCall(); } /** * Copies Realm database file from Android asset directory to the directory given in the {@link RealmConfiguration}. * Copy is performed only at the first time when there is no Realm database file. * * WARNING: This method is not thread-safe so external synchronization is required before using it. * * @param configuration configuration object for Realm instance. * @throws RealmFileException if copying the file fails. */ private static void copyAssetFileIfNeeded(final RealmConfiguration configuration) { final File realmFileFromAsset = configuration.hasAssetFile() ? new File(configuration.getRealmDirectory(), configuration.getRealmFileName()) : null; String syncServerCertificateFilePath = ObjectServerFacade.getFacade( configuration.isSyncConfiguration()).getSyncServerCertificateFilePath(configuration ); final boolean certFileExists = !Util.isEmptyString(syncServerCertificateFilePath); if (realmFileFromAsset!= null || certFileExists) { OsObjectStore.callWithLock(configuration, new Runnable() { @Override public void run() { if (realmFileFromAsset != null) { copyFileIfNeeded(configuration.getAssetFilePath(), realmFileFromAsset); } // Copy Sync Server certificate path if available if (certFileExists) { final String syncServerCertificateAssetName = ObjectServerFacade.getFacade( configuration.isSyncConfiguration() ).getSyncServerCertificateAssetName(configuration); File certificateFile = new File(syncServerCertificateFilePath); copyFileIfNeeded(syncServerCertificateAssetName, certificateFile); } } }); } } private static void copyFileIfNeeded(String assetFileName, File file) { if (file.exists()) { return; } IOException exceptionWhenClose = null; InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = BaseRealm.applicationContext.getAssets().open(assetFileName); if (inputStream == null) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, "Invalid input stream to the asset file: " + assetFileName); } outputStream = new FileOutputStream(file); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buf)) > -1) { outputStream.write(buf, 0, bytesRead); } } catch (IOException e) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, "Could not resolve the path to the asset file: " + assetFileName, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { exceptionWhenClose = e; } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // Ignores this one if there was an exception when close inputStream. if (exceptionWhenClose == null) { exceptionWhenClose = e; } } } } // No other exception has been thrown, only the exception when close. So, throw it. if (exceptionWhenClose != null) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, exceptionWhenClose); } } static int getLocalThreadCount(RealmConfiguration configuration) { RealmCache cache = getCache(configuration.getPath(), false); if (cache == null) { return 0; } // Access local ref count only, no need to be synchronized. int totalRefCount = 0; for (ReferenceCounter referenceCounter : cache.refAndCountMap.values()) { totalRefCount += referenceCounter.getThreadLocalCount(); } return totalRefCount; } public RealmConfiguration getConfiguration() { return configuration; } /** * @return the total global ref count. */ private int getTotalGlobalRefCount() { int totalRefCount = 0; for (ReferenceCounter referenceCounter : refAndCountMap.values()) { totalRefCount += referenceCounter.getGlobalCount(); } return totalRefCount; } /** * Returns the total number of threads containg a reference to a live instance of the Realm. */ private int getTotalLiveRealmGlobalRefCount() { int totalRefCount = 0; for (ReferenceCounter referenceCounter : refAndCountMap.values()) { if (referenceCounter instanceof ThreadConfinedReferenceCounter) { totalRefCount += referenceCounter.getGlobalCount(); } } return totalRefCount; } /** * If a Realm instance is GCed but `Realm.close()` is not called before, we still want to track the cache for * debugging. Adding them to the list to keep the strong ref of the cache to prevent the cache gets GCed. */ void leak() { if (!isLeaked.getAndSet(true)) { leakedCaches.add(this); } } }
realm/realm-java
realm/realm-library/src/main/java/io/realm/RealmCache.java
7,494
// Should never happen.
line_comment
nl
/* * Copyright 2015 Realm 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 io.realm; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import io.realm.exceptions.RealmFileException; import io.realm.internal.Capabilities; import io.realm.internal.ObjectServerFacade; import io.realm.internal.OsObjectStore; import io.realm.internal.OsRealmConfig; import io.realm.internal.OsSharedRealm; import io.realm.internal.RealmNotifier; import io.realm.internal.Util; import io.realm.internal.android.AndroidCapabilities; import io.realm.internal.android.AndroidRealmNotifier; import io.realm.internal.async.RealmAsyncTaskImpl; import io.realm.internal.util.Pair; import io.realm.log.RealmLog; /** * To cache {@link Realm}, {@link DynamicRealm} instances and related resources. * Every thread will share the same {@link Realm} and {@link DynamicRealm} instances which are referred to the same * {@link RealmConfiguration}. * One {@link RealmCache} is created for each {@link RealmConfiguration}, and it caches all the {@link Realm} and * {@link DynamicRealm} instances which are created from the same {@link RealmConfiguration}. */ final class RealmCache { interface Callback { void onResult(int count); } interface Callback0 { void onCall(); } private abstract static class ReferenceCounter { // How many references to this Realm instance in this thread. protected final ThreadLocal<Integer> localCount = new ThreadLocal<>(); // How many threads have instances refer to this configuration. protected AtomicInteger globalCount = new AtomicInteger(0); // Returns `true` if an instance of the Realm is available on the caller thread. abstract boolean hasInstanceAvailableForThread(); // Increment how many times an instance has been handed out for the current thread. public void incrementThreadCount(int increment) { Integer currentCount = localCount.get(); localCount.set(currentCount != null ? currentCount + increment : increment); } // Returns the Realm instance for the caller thread abstract BaseRealm getRealmInstance(); // Cache the Realm instance. Should only be called when `hasInstanceAvailableForThread` returns false. abstract void onRealmCreated(BaseRealm realm); // Clears the the cache for a given thread when all Realms on that thread are closed. abstract void clearThreadLocalCache(); // Returns the number of instances handed out for the caller thread. abstract int getThreadLocalCount(); // Updates the number of references handed out for a given thread public void setThreadCount(int refCount) { localCount.set(refCount); } // Returns the number of gloal instances handed out. This is roughly equivalent // to the number of threads currently using the Realm as each thread also does // reference counting of Realm instances. public int getGlobalCount() { return globalCount.get(); } } // Reference counter for Realms that are accessible across all threads private static class GlobalReferenceCounter extends ReferenceCounter { private BaseRealm cachedRealm; @Override boolean hasInstanceAvailableForThread() { return cachedRealm != null; } @Override BaseRealm getRealmInstance() { return cachedRealm; } @Override void onRealmCreated(BaseRealm realm) { // The Realm instance has been created without exceptions. Cache and reference count can be updated now. cachedRealm = realm; localCount.set(0); // This is the first instance in current thread, increase the global count. globalCount.incrementAndGet(); } @Override public void clearThreadLocalCache() { String canonicalPath = cachedRealm.getPath(); // The last instance in this thread. // Clears local ref & counter. localCount.set(null); cachedRealm = null; // Clears global counter. if (globalCount.decrementAndGet() < 0) { // Should never<SUF> throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " not be negative."); } } @Override int getThreadLocalCount() { // For frozen Realms the Realm can be accessed from all threads, so the concept // of a thread local count doesn't make sense. Just return the global count instead. return globalCount.get(); } } // Reference counter for Realms that are thread confined private static class ThreadConfinedReferenceCounter extends ReferenceCounter { // The Realm instance in this thread. private final ThreadLocal<BaseRealm> localRealm = new ThreadLocal<>(); @Override public boolean hasInstanceAvailableForThread() { return localRealm.get() != null; } @Override public BaseRealm getRealmInstance() { return localRealm.get(); } @Override public void onRealmCreated(BaseRealm realm) { // The Realm instance has been created without exceptions. Cache and reference count can be updated now. localRealm.set(realm); localCount.set(0); // This is the first instance in current thread, increase the global count. globalCount.incrementAndGet(); } @Override public void clearThreadLocalCache() { String canonicalPath = localRealm.get().getPath(); // The last instance in this thread. // Clears local ref & counter. localCount.set(null); localRealm.set(null); // Clears global counter. if (globalCount.decrementAndGet() < 0) { // Should never happen. throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " can not be negative."); } } @Override public int getThreadLocalCount() { Integer refCount = localCount.get(); return (refCount != null) ? refCount : 0; } } private enum RealmCacheType { TYPED_REALM, DYNAMIC_REALM; static RealmCacheType valueOf(Class<? extends BaseRealm> clazz) { if (clazz == Realm.class) { return TYPED_REALM; } else if (clazz == DynamicRealm.class) { return DYNAMIC_REALM; } throw new IllegalArgumentException(WRONG_REALM_CLASS_MESSAGE); } } private static class CreateRealmRunnable<T extends BaseRealm> implements Runnable { private final RealmConfiguration configuration; private final BaseRealm.InstanceCallback<T> callback; private final Class<T> realmClass; private final CountDownLatch canReleaseBackgroundInstanceLatch = new CountDownLatch(1); private final RealmNotifier notifier; // The Future this runnable belongs to. private Future future; CreateRealmRunnable(RealmNotifier notifier, RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { this.configuration = configuration; this.realmClass = realmClass; this.callback = callback; this.notifier = notifier; } public void setFuture(Future future) { this.future = future; } @Override public void run() { T instance = null; try { // First call that will run all schema validation, migrations or initial transactions. instance = createRealmOrGetFromCache(configuration, realmClass); boolean results = notifier.post(new Runnable() { @Override public void run() { // If the RealmAsyncTask.cancel() is called before, we just return without creating the Realm // instance on the caller thread. // Thread.isInterrupted() cannot be used for checking here since CountDownLatch.await() will // will clear interrupted status. // Using the future to check which this runnable belongs to is to ensure if it is canceled from // the caller thread before, the callback will never be delivered. if (future == null || future.isCancelled()) { canReleaseBackgroundInstanceLatch.countDown(); return; } T instanceToReturn = null; Throwable throwable = null; try { // This will run on the caller thread, but since the first `createRealmOrGetFromCache` // should have completed at this point, all expensive initializer functions have already // run. instanceToReturn = createRealmOrGetFromCache(configuration, realmClass); } catch (Throwable e) { throwable = e; } finally { canReleaseBackgroundInstanceLatch.countDown(); } if (instanceToReturn != null) { callback.onSuccess(instanceToReturn); } else { // throwable is non-null //noinspection ConstantConditions callback.onError(throwable); } } }); if (!results) { canReleaseBackgroundInstanceLatch.countDown(); } // There is a small chance that the posted runnable cannot be executed because of the thread terminated // before the runnable gets fetched from the event queue. if (!canReleaseBackgroundInstanceLatch.await(2, TimeUnit.SECONDS)) { RealmLog.warn("Timeout for creating Realm instance in foreground thread in `CreateRealmRunnable` "); } } catch (InterruptedException e) { RealmLog.warn(e, "`CreateRealmRunnable` has been interrupted."); } catch (final Throwable e) { // DownloadingRealmInterruptedException is treated specially. // It async open is canceled, this could interrupt the download, but the user should // not care in this case, so just ignore it. if (!ObjectServerFacade.getSyncFacadeIfPossible().wasDownloadInterrupted(e)) { RealmLog.error(e, "`CreateRealmRunnable` failed."); notifier.post(new Runnable() { @Override public void run() { callback.onError(e); } }); } } finally { if (instance != null) { instance.close(); } } } } private static final String ASYNC_NOT_ALLOWED_MSG = "Realm instances cannot be loaded asynchronously on a non-looper thread."; private static final String ASYNC_CALLBACK_NULL_MSG = "The callback cannot be null."; // Separated references and counters for typed Realm and dynamic Realm. private final Map<Pair<RealmCacheType, OsSharedRealm.VersionID>, ReferenceCounter> refAndCountMap = new HashMap<>(); // Path to the Realm file to identify this cache. private final String realmPath; // This will be only valid if getTotalGlobalRefCount() > 0. // NOTE: We do reset this when globalCount reaches 0, but if exception thrown in doCreateRealmOrGetFromCache at the // first time when globalCount == 0, this could have a non-null value but it will be reset when the next // doCreateRealmOrGetFromCache is called with globalCount == 0. private RealmConfiguration configuration; // Realm path will be used to identify different RealmCaches. Different Realm configurations with same path // are not allowed and an exception will be thrown when trying to add it to the cache list. // A weak ref is used to hold the RealmCache instance. The weak ref entry will be cleared if and only if there // is no Realm instance holding a strong ref to it and there is no Realm instance associated it is BEING created. private static final List<WeakReference<RealmCache>> cachesList = new ArrayList<WeakReference<RealmCache>>(); // See leak() // isLeaked flag is used to avoid adding strong ref multiple times without iterating the list. private final AtomicBoolean isLeaked = new AtomicBoolean(false); // Keep strong ref to the leaked RealmCache @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private static final Collection<RealmCache> leakedCaches = new ConcurrentLinkedQueue<RealmCache>(); // Keeps track if a Realm needs to download its initial remote data private final Set<String> pendingRealmFileCreation = new HashSet<>(); private static final String DIFFERENT_KEY_MESSAGE = "Wrong key used to decrypt Realm."; private static final String WRONG_REALM_CLASS_MESSAGE = "The type of Realm class must be Realm or DynamicRealm."; private RealmCache(String path) { realmPath = path; } private static RealmCache getCache(String realmPath, boolean createIfNotExist) { RealmCache cacheToReturn = null; synchronized (cachesList) { Iterator<WeakReference<RealmCache>> it = cachesList.iterator(); while (it.hasNext()) { RealmCache cache = it.next().get(); if (cache == null) { // Clear the entry if there is no one holding the RealmCache. it.remove(); } else if (cache.realmPath.equals(realmPath)) { cacheToReturn = cache; } } if (cacheToReturn == null && createIfNotExist) { cacheToReturn = new RealmCache(realmPath); cachesList.add(new WeakReference<RealmCache>(cacheToReturn)); } } return cacheToReturn; } static <T extends BaseRealm> RealmAsyncTask createRealmOrGetFromCacheAsync( RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCacheAsync(configuration, callback, realmClass); } private synchronized <T extends BaseRealm> RealmAsyncTask doCreateRealmOrGetFromCacheAsync( RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { Capabilities capabilities = new AndroidCapabilities(); capabilities.checkCanDeliverNotification(ASYNC_NOT_ALLOWED_MSG); //noinspection ConstantConditions if (callback == null) { throw new IllegalArgumentException(ASYNC_CALLBACK_NULL_MSG); } // If there is no Realm file it means that we need to sync the initial remote data in the worker thread. if (configuration.isSyncConfiguration() && !configuration.realmExists()) { pendingRealmFileCreation.add(configuration.getPath()); } // Always create a Realm instance in the background thread even when there are instances existing on current // thread. This to ensure that onSuccess will always be called in the following event loop but not current one. CreateRealmRunnable<T> createRealmRunnable = new CreateRealmRunnable<T>( new AndroidRealmNotifier(null, capabilities), configuration, callback, realmClass); Future<?> future = BaseRealm.asyncTaskExecutor.submitTransaction(createRealmRunnable); createRealmRunnable.setFuture(future); // For Realms using Async Open on the server, we need to create the session right away // in order to interact with it in a imperative way, e.g. by attaching download progress // listeners ObjectServerFacade.getSyncFacadeIfPossible().createNativeSyncSession(configuration); return new RealmAsyncTaskImpl(future, BaseRealm.asyncTaskExecutor); } /** * Creates a new Realm instance or get an existing instance for current thread. * * @param configuration {@link RealmConfiguration} will be used to create or get the instance. * @param realmClass class of {@link Realm} or {@link DynamicRealm} to be created in or gotten from the cache. * @return the {@link Realm} or {@link DynamicRealm} instance. */ static <E extends BaseRealm> E createRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCache(configuration, realmClass, OsSharedRealm.VersionID.LIVE); } static <E extends BaseRealm> E createRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCache(configuration, realmClass, version); } private synchronized <E extends BaseRealm> E doCreateRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { ReferenceCounter referenceCounter = getRefCounter(realmClass, version); boolean firstRealmInstanceInProcess = (getTotalGlobalRefCount() == 0); if (firstRealmInstanceInProcess) { copyAssetFileIfNeeded(configuration); // If waitForInitialRemoteData() was enabled, we need to make sure that all data is downloaded // before proceeding. We need to open the Realm instance first to start any potential underlying // SyncSession so this will work. boolean realmFileIsBeingCreated = !configuration.realmExists(); if (configuration.isSyncConfiguration() && (realmFileIsBeingCreated || pendingRealmFileCreation.contains(configuration.getPath()))) { // Manually create the Java session wrapper session as this might otherwise // not be created OsRealmConfig osConfig = new OsRealmConfig.Builder(configuration).build(); ObjectServerFacade.getSyncFacadeIfPossible().wrapObjectStoreSessionIfRequired(osConfig); // Fully synchronized Realms are supported by AsyncOpen ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialRemoteChanges(configuration); // Initial remote data has been synced at this point pendingRealmFileCreation.remove(configuration.getPath()); } // We are holding the lock, and we can set the valid configuration since there is no global ref to it. this.configuration = configuration; } else { // Throws exception if validation failed. validateConfiguration(configuration); } if (!referenceCounter.hasInstanceAvailableForThread()) { createInstance(realmClass, referenceCounter, version); } referenceCounter.incrementThreadCount(1); //noinspection unchecked E realmInstance = (E) referenceCounter.getRealmInstance(); if (firstRealmInstanceInProcess) { // If flexible sync initial subscriptions are configured, we need to make // sure they are in the COMPLETE state before proceeding // TODO Ideally this would be part of `downloadInitialRemoteChanges` called before // but his requires a larger refactor, so for now just run the logic here. ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialFlexibleSyncData( Realm.createInstance(realmInstance.sharedRealm), configuration ); if (!configuration.isReadOnly()) { realmInstance.refresh(); } } return realmInstance; } private <E extends BaseRealm> ReferenceCounter getRefCounter(Class<E> realmClass, OsSharedRealm.VersionID version) { RealmCacheType cacheType = RealmCacheType.valueOf(realmClass); Pair<RealmCacheType, OsSharedRealm.VersionID> key = new Pair<>(cacheType, version); ReferenceCounter refCounter = refAndCountMap.get(key); if (refCounter == null) { if (version.equals(OsSharedRealm.VersionID.LIVE)) { refCounter = new ThreadConfinedReferenceCounter(); } else { refCounter = new GlobalReferenceCounter(); } refAndCountMap.put(key, refCounter); } return refCounter; } private <E extends BaseRealm> void createInstance(Class<E> realmClass, ReferenceCounter referenceCounter, OsSharedRealm.VersionID version) { // Creates a new local Realm instance BaseRealm realm; if (realmClass == Realm.class) { // RealmMigrationNeededException might be thrown here. realm = Realm.createInstance(this, version); // Only create mappings after the Realm was opened, so schema mismatch is correctly // thrown by ObjectStore when checking the schema. realm.getSchema().createKeyPathMapping(); } else if (realmClass == DynamicRealm.class) { realm = DynamicRealm.createInstance(this, version); } else { throw new IllegalArgumentException(WRONG_REALM_CLASS_MESSAGE); } referenceCounter.onRealmCreated(realm); } /** * Releases a given {@link Realm} or {@link DynamicRealm} from cache. The instance will be closed by this method * if there is no more local reference to this Realm instance in current Thread. * * @param realm Realm instance to be released from cache. */ synchronized void release(BaseRealm realm) { String canonicalPath = realm.getPath(); ReferenceCounter referenceCounter = getRefCounter(realm.getClass(), (realm.isFrozen()) ? realm.sharedRealm.getVersionID() : OsSharedRealm.VersionID.LIVE); int refCount = referenceCounter.getThreadLocalCount(); if (refCount <= 0) { RealmLog.warn("%s has been closed already. refCount is %s", canonicalPath, refCount); return; } // Decreases the local counter. refCount -= 1; if (refCount == 0) { referenceCounter.clearThreadLocalCache(); // No more local reference to this Realm in current thread, close the instance. realm.doClose(); // No more instance of typed Realm and dynamic Realm. if (getTotalLiveRealmGlobalRefCount() == 0) { // We keep the cache in the caches list even when its global counter reaches 0. It will be reused when // next time a Realm instance with the same path is opened. By not removing it, the lock on // cachesList is not needed here. configuration = null; // Close all frozen Realms. This can introduce race conditions on other // threads if the lifecyle of using Realm data is not correctly controlled. for (ReferenceCounter counter : refAndCountMap.values()) { if (counter instanceof GlobalReferenceCounter) { BaseRealm cachedRealm = counter.getRealmInstance(); // Since we don't remove ReferenceCounters, we need to check if the Realm is still open if (cachedRealm != null) { // Gracefully close frozen Realms in a similar way to what a user would normally do. while (!cachedRealm.isClosed()) { cachedRealm.close(); } } } } ObjectServerFacade.getFacade(realm.getConfiguration().isSyncConfiguration()).realmClosed(realm.getConfiguration()); } } else { referenceCounter.setThreadCount(refCount); } } /** * Makes sure that the new configuration doesn't clash with any cached configurations for the * Realm. * * @throws IllegalArgumentException if the new configuration isn't valid. */ private void validateConfiguration(RealmConfiguration newConfiguration) { if (configuration.equals(newConfiguration)) { // Same configuration objects. return; } // Checks that encryption keys aren't different. key is not in RealmConfiguration's toString. if (!Arrays.equals(configuration.getEncryptionKey(), newConfiguration.getEncryptionKey())) { throw new IllegalArgumentException(DIFFERENT_KEY_MESSAGE); } else { // A common problem is that people are forgetting to override `equals` in their custom migration class. // Tries to detect this problem specifically so we can throw a better error message. RealmMigration newMigration = newConfiguration.getMigration(); RealmMigration oldMigration = configuration.getMigration(); if (oldMigration != null && newMigration != null && oldMigration.getClass().equals(newMigration.getClass()) && !newMigration.equals(oldMigration)) { throw new IllegalArgumentException("Configurations cannot be different if used to open the same file. " + "The most likely cause is that equals() and hashCode() are not overridden in the " + "migration class: " + newConfiguration.getMigration().getClass().getCanonicalName()); } throw new IllegalArgumentException("Configurations cannot be different if used to open the same file. " + "\nCached configuration: \n" + configuration + "\n\nNew configuration: \n" + newConfiguration); } } /** * Runs the callback function with the total reference count of {@link Realm} and {@link DynamicRealm} who refer to * the given {@link RealmConfiguration}. * * @param configuration the {@link RealmConfiguration} of {@link Realm} or {@link DynamicRealm}. * @param callback the callback will be executed with the global reference count. */ static void invokeWithGlobalRefCount(RealmConfiguration configuration, Callback callback) { // NOTE: Although getCache is locked on the cacheMap, this whole method needs to be lock with it as // well. Since we need to ensure there is no Realm instance can be opened when this method is called (for // deleteRealm). // Recursive lock cannot be avoided here. synchronized (cachesList) { RealmCache cache = getCache(configuration.getPath(), false); if (cache == null) { callback.onResult(0); return; } cache.doInvokeWithGlobalRefCount(callback); } } private synchronized void doInvokeWithGlobalRefCount(Callback callback) { callback.onResult(getTotalGlobalRefCount()); } /** * Runs the callback function with synchronization on {@link RealmCache}. * * @param callback the callback will be executed. */ synchronized void invokeWithLock(Callback0 callback) { callback.onCall(); } /** * Copies Realm database file from Android asset directory to the directory given in the {@link RealmConfiguration}. * Copy is performed only at the first time when there is no Realm database file. * * WARNING: This method is not thread-safe so external synchronization is required before using it. * * @param configuration configuration object for Realm instance. * @throws RealmFileException if copying the file fails. */ private static void copyAssetFileIfNeeded(final RealmConfiguration configuration) { final File realmFileFromAsset = configuration.hasAssetFile() ? new File(configuration.getRealmDirectory(), configuration.getRealmFileName()) : null; String syncServerCertificateFilePath = ObjectServerFacade.getFacade( configuration.isSyncConfiguration()).getSyncServerCertificateFilePath(configuration ); final boolean certFileExists = !Util.isEmptyString(syncServerCertificateFilePath); if (realmFileFromAsset!= null || certFileExists) { OsObjectStore.callWithLock(configuration, new Runnable() { @Override public void run() { if (realmFileFromAsset != null) { copyFileIfNeeded(configuration.getAssetFilePath(), realmFileFromAsset); } // Copy Sync Server certificate path if available if (certFileExists) { final String syncServerCertificateAssetName = ObjectServerFacade.getFacade( configuration.isSyncConfiguration() ).getSyncServerCertificateAssetName(configuration); File certificateFile = new File(syncServerCertificateFilePath); copyFileIfNeeded(syncServerCertificateAssetName, certificateFile); } } }); } } private static void copyFileIfNeeded(String assetFileName, File file) { if (file.exists()) { return; } IOException exceptionWhenClose = null; InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = BaseRealm.applicationContext.getAssets().open(assetFileName); if (inputStream == null) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, "Invalid input stream to the asset file: " + assetFileName); } outputStream = new FileOutputStream(file); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buf)) > -1) { outputStream.write(buf, 0, bytesRead); } } catch (IOException e) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, "Could not resolve the path to the asset file: " + assetFileName, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { exceptionWhenClose = e; } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // Ignores this one if there was an exception when close inputStream. if (exceptionWhenClose == null) { exceptionWhenClose = e; } } } } // No other exception has been thrown, only the exception when close. So, throw it. if (exceptionWhenClose != null) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, exceptionWhenClose); } } static int getLocalThreadCount(RealmConfiguration configuration) { RealmCache cache = getCache(configuration.getPath(), false); if (cache == null) { return 0; } // Access local ref count only, no need to be synchronized. int totalRefCount = 0; for (ReferenceCounter referenceCounter : cache.refAndCountMap.values()) { totalRefCount += referenceCounter.getThreadLocalCount(); } return totalRefCount; } public RealmConfiguration getConfiguration() { return configuration; } /** * @return the total global ref count. */ private int getTotalGlobalRefCount() { int totalRefCount = 0; for (ReferenceCounter referenceCounter : refAndCountMap.values()) { totalRefCount += referenceCounter.getGlobalCount(); } return totalRefCount; } /** * Returns the total number of threads containg a reference to a live instance of the Realm. */ private int getTotalLiveRealmGlobalRefCount() { int totalRefCount = 0; for (ReferenceCounter referenceCounter : refAndCountMap.values()) { if (referenceCounter instanceof ThreadConfinedReferenceCounter) { totalRefCount += referenceCounter.getGlobalCount(); } } return totalRefCount; } /** * If a Realm instance is GCed but `Realm.close()` is not called before, we still want to track the cache for * debugging. Adding them to the list to keep the strong ref of the cache to prevent the cache gets GCed. */ void leak() { if (!isLeaked.getAndSet(true)) { leakedCaches.add(this); } } }
201421_30
/* * Copyright 2015 Realm 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 io.realm; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import io.realm.exceptions.RealmFileException; import io.realm.internal.Capabilities; import io.realm.internal.ObjectServerFacade; import io.realm.internal.OsObjectStore; import io.realm.internal.OsRealmConfig; import io.realm.internal.OsSharedRealm; import io.realm.internal.RealmNotifier; import io.realm.internal.Util; import io.realm.internal.android.AndroidCapabilities; import io.realm.internal.android.AndroidRealmNotifier; import io.realm.internal.async.RealmAsyncTaskImpl; import io.realm.internal.util.Pair; import io.realm.log.RealmLog; /** * To cache {@link Realm}, {@link DynamicRealm} instances and related resources. * Every thread will share the same {@link Realm} and {@link DynamicRealm} instances which are referred to the same * {@link RealmConfiguration}. * One {@link RealmCache} is created for each {@link RealmConfiguration}, and it caches all the {@link Realm} and * {@link DynamicRealm} instances which are created from the same {@link RealmConfiguration}. */ final class RealmCache { interface Callback { void onResult(int count); } interface Callback0 { void onCall(); } private abstract static class ReferenceCounter { // How many references to this Realm instance in this thread. protected final ThreadLocal<Integer> localCount = new ThreadLocal<>(); // How many threads have instances refer to this configuration. protected AtomicInteger globalCount = new AtomicInteger(0); // Returns `true` if an instance of the Realm is available on the caller thread. abstract boolean hasInstanceAvailableForThread(); // Increment how many times an instance has been handed out for the current thread. public void incrementThreadCount(int increment) { Integer currentCount = localCount.get(); localCount.set(currentCount != null ? currentCount + increment : increment); } // Returns the Realm instance for the caller thread abstract BaseRealm getRealmInstance(); // Cache the Realm instance. Should only be called when `hasInstanceAvailableForThread` returns false. abstract void onRealmCreated(BaseRealm realm); // Clears the the cache for a given thread when all Realms on that thread are closed. abstract void clearThreadLocalCache(); // Returns the number of instances handed out for the caller thread. abstract int getThreadLocalCount(); // Updates the number of references handed out for a given thread public void setThreadCount(int refCount) { localCount.set(refCount); } // Returns the number of gloal instances handed out. This is roughly equivalent // to the number of threads currently using the Realm as each thread also does // reference counting of Realm instances. public int getGlobalCount() { return globalCount.get(); } } // Reference counter for Realms that are accessible across all threads private static class GlobalReferenceCounter extends ReferenceCounter { private BaseRealm cachedRealm; @Override boolean hasInstanceAvailableForThread() { return cachedRealm != null; } @Override BaseRealm getRealmInstance() { return cachedRealm; } @Override void onRealmCreated(BaseRealm realm) { // The Realm instance has been created without exceptions. Cache and reference count can be updated now. cachedRealm = realm; localCount.set(0); // This is the first instance in current thread, increase the global count. globalCount.incrementAndGet(); } @Override public void clearThreadLocalCache() { String canonicalPath = cachedRealm.getPath(); // The last instance in this thread. // Clears local ref & counter. localCount.set(null); cachedRealm = null; // Clears global counter. if (globalCount.decrementAndGet() < 0) { // Should never happen. throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " not be negative."); } } @Override int getThreadLocalCount() { // For frozen Realms the Realm can be accessed from all threads, so the concept // of a thread local count doesn't make sense. Just return the global count instead. return globalCount.get(); } } // Reference counter for Realms that are thread confined private static class ThreadConfinedReferenceCounter extends ReferenceCounter { // The Realm instance in this thread. private final ThreadLocal<BaseRealm> localRealm = new ThreadLocal<>(); @Override public boolean hasInstanceAvailableForThread() { return localRealm.get() != null; } @Override public BaseRealm getRealmInstance() { return localRealm.get(); } @Override public void onRealmCreated(BaseRealm realm) { // The Realm instance has been created without exceptions. Cache and reference count can be updated now. localRealm.set(realm); localCount.set(0); // This is the first instance in current thread, increase the global count. globalCount.incrementAndGet(); } @Override public void clearThreadLocalCache() { String canonicalPath = localRealm.get().getPath(); // The last instance in this thread. // Clears local ref & counter. localCount.set(null); localRealm.set(null); // Clears global counter. if (globalCount.decrementAndGet() < 0) { // Should never happen. throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " can not be negative."); } } @Override public int getThreadLocalCount() { Integer refCount = localCount.get(); return (refCount != null) ? refCount : 0; } } private enum RealmCacheType { TYPED_REALM, DYNAMIC_REALM; static RealmCacheType valueOf(Class<? extends BaseRealm> clazz) { if (clazz == Realm.class) { return TYPED_REALM; } else if (clazz == DynamicRealm.class) { return DYNAMIC_REALM; } throw new IllegalArgumentException(WRONG_REALM_CLASS_MESSAGE); } } private static class CreateRealmRunnable<T extends BaseRealm> implements Runnable { private final RealmConfiguration configuration; private final BaseRealm.InstanceCallback<T> callback; private final Class<T> realmClass; private final CountDownLatch canReleaseBackgroundInstanceLatch = new CountDownLatch(1); private final RealmNotifier notifier; // The Future this runnable belongs to. private Future future; CreateRealmRunnable(RealmNotifier notifier, RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { this.configuration = configuration; this.realmClass = realmClass; this.callback = callback; this.notifier = notifier; } public void setFuture(Future future) { this.future = future; } @Override public void run() { T instance = null; try { // First call that will run all schema validation, migrations or initial transactions. instance = createRealmOrGetFromCache(configuration, realmClass); boolean results = notifier.post(new Runnable() { @Override public void run() { // If the RealmAsyncTask.cancel() is called before, we just return without creating the Realm // instance on the caller thread. // Thread.isInterrupted() cannot be used for checking here since CountDownLatch.await() will // will clear interrupted status. // Using the future to check which this runnable belongs to is to ensure if it is canceled from // the caller thread before, the callback will never be delivered. if (future == null || future.isCancelled()) { canReleaseBackgroundInstanceLatch.countDown(); return; } T instanceToReturn = null; Throwable throwable = null; try { // This will run on the caller thread, but since the first `createRealmOrGetFromCache` // should have completed at this point, all expensive initializer functions have already // run. instanceToReturn = createRealmOrGetFromCache(configuration, realmClass); } catch (Throwable e) { throwable = e; } finally { canReleaseBackgroundInstanceLatch.countDown(); } if (instanceToReturn != null) { callback.onSuccess(instanceToReturn); } else { // throwable is non-null //noinspection ConstantConditions callback.onError(throwable); } } }); if (!results) { canReleaseBackgroundInstanceLatch.countDown(); } // There is a small chance that the posted runnable cannot be executed because of the thread terminated // before the runnable gets fetched from the event queue. if (!canReleaseBackgroundInstanceLatch.await(2, TimeUnit.SECONDS)) { RealmLog.warn("Timeout for creating Realm instance in foreground thread in `CreateRealmRunnable` "); } } catch (InterruptedException e) { RealmLog.warn(e, "`CreateRealmRunnable` has been interrupted."); } catch (final Throwable e) { // DownloadingRealmInterruptedException is treated specially. // It async open is canceled, this could interrupt the download, but the user should // not care in this case, so just ignore it. if (!ObjectServerFacade.getSyncFacadeIfPossible().wasDownloadInterrupted(e)) { RealmLog.error(e, "`CreateRealmRunnable` failed."); notifier.post(new Runnable() { @Override public void run() { callback.onError(e); } }); } } finally { if (instance != null) { instance.close(); } } } } private static final String ASYNC_NOT_ALLOWED_MSG = "Realm instances cannot be loaded asynchronously on a non-looper thread."; private static final String ASYNC_CALLBACK_NULL_MSG = "The callback cannot be null."; // Separated references and counters for typed Realm and dynamic Realm. private final Map<Pair<RealmCacheType, OsSharedRealm.VersionID>, ReferenceCounter> refAndCountMap = new HashMap<>(); // Path to the Realm file to identify this cache. private final String realmPath; // This will be only valid if getTotalGlobalRefCount() > 0. // NOTE: We do reset this when globalCount reaches 0, but if exception thrown in doCreateRealmOrGetFromCache at the // first time when globalCount == 0, this could have a non-null value but it will be reset when the next // doCreateRealmOrGetFromCache is called with globalCount == 0. private RealmConfiguration configuration; // Realm path will be used to identify different RealmCaches. Different Realm configurations with same path // are not allowed and an exception will be thrown when trying to add it to the cache list. // A weak ref is used to hold the RealmCache instance. The weak ref entry will be cleared if and only if there // is no Realm instance holding a strong ref to it and there is no Realm instance associated it is BEING created. private static final List<WeakReference<RealmCache>> cachesList = new ArrayList<WeakReference<RealmCache>>(); // See leak() // isLeaked flag is used to avoid adding strong ref multiple times without iterating the list. private final AtomicBoolean isLeaked = new AtomicBoolean(false); // Keep strong ref to the leaked RealmCache @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private static final Collection<RealmCache> leakedCaches = new ConcurrentLinkedQueue<RealmCache>(); // Keeps track if a Realm needs to download its initial remote data private final Set<String> pendingRealmFileCreation = new HashSet<>(); private static final String DIFFERENT_KEY_MESSAGE = "Wrong key used to decrypt Realm."; private static final String WRONG_REALM_CLASS_MESSAGE = "The type of Realm class must be Realm or DynamicRealm."; private RealmCache(String path) { realmPath = path; } private static RealmCache getCache(String realmPath, boolean createIfNotExist) { RealmCache cacheToReturn = null; synchronized (cachesList) { Iterator<WeakReference<RealmCache>> it = cachesList.iterator(); while (it.hasNext()) { RealmCache cache = it.next().get(); if (cache == null) { // Clear the entry if there is no one holding the RealmCache. it.remove(); } else if (cache.realmPath.equals(realmPath)) { cacheToReturn = cache; } } if (cacheToReturn == null && createIfNotExist) { cacheToReturn = new RealmCache(realmPath); cachesList.add(new WeakReference<RealmCache>(cacheToReturn)); } } return cacheToReturn; } static <T extends BaseRealm> RealmAsyncTask createRealmOrGetFromCacheAsync( RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCacheAsync(configuration, callback, realmClass); } private synchronized <T extends BaseRealm> RealmAsyncTask doCreateRealmOrGetFromCacheAsync( RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { Capabilities capabilities = new AndroidCapabilities(); capabilities.checkCanDeliverNotification(ASYNC_NOT_ALLOWED_MSG); //noinspection ConstantConditions if (callback == null) { throw new IllegalArgumentException(ASYNC_CALLBACK_NULL_MSG); } // If there is no Realm file it means that we need to sync the initial remote data in the worker thread. if (configuration.isSyncConfiguration() && !configuration.realmExists()) { pendingRealmFileCreation.add(configuration.getPath()); } // Always create a Realm instance in the background thread even when there are instances existing on current // thread. This to ensure that onSuccess will always be called in the following event loop but not current one. CreateRealmRunnable<T> createRealmRunnable = new CreateRealmRunnable<T>( new AndroidRealmNotifier(null, capabilities), configuration, callback, realmClass); Future<?> future = BaseRealm.asyncTaskExecutor.submitTransaction(createRealmRunnable); createRealmRunnable.setFuture(future); // For Realms using Async Open on the server, we need to create the session right away // in order to interact with it in a imperative way, e.g. by attaching download progress // listeners ObjectServerFacade.getSyncFacadeIfPossible().createNativeSyncSession(configuration); return new RealmAsyncTaskImpl(future, BaseRealm.asyncTaskExecutor); } /** * Creates a new Realm instance or get an existing instance for current thread. * * @param configuration {@link RealmConfiguration} will be used to create or get the instance. * @param realmClass class of {@link Realm} or {@link DynamicRealm} to be created in or gotten from the cache. * @return the {@link Realm} or {@link DynamicRealm} instance. */ static <E extends BaseRealm> E createRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCache(configuration, realmClass, OsSharedRealm.VersionID.LIVE); } static <E extends BaseRealm> E createRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCache(configuration, realmClass, version); } private synchronized <E extends BaseRealm> E doCreateRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { ReferenceCounter referenceCounter = getRefCounter(realmClass, version); boolean firstRealmInstanceInProcess = (getTotalGlobalRefCount() == 0); if (firstRealmInstanceInProcess) { copyAssetFileIfNeeded(configuration); // If waitForInitialRemoteData() was enabled, we need to make sure that all data is downloaded // before proceeding. We need to open the Realm instance first to start any potential underlying // SyncSession so this will work. boolean realmFileIsBeingCreated = !configuration.realmExists(); if (configuration.isSyncConfiguration() && (realmFileIsBeingCreated || pendingRealmFileCreation.contains(configuration.getPath()))) { // Manually create the Java session wrapper session as this might otherwise // not be created OsRealmConfig osConfig = new OsRealmConfig.Builder(configuration).build(); ObjectServerFacade.getSyncFacadeIfPossible().wrapObjectStoreSessionIfRequired(osConfig); // Fully synchronized Realms are supported by AsyncOpen ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialRemoteChanges(configuration); // Initial remote data has been synced at this point pendingRealmFileCreation.remove(configuration.getPath()); } // We are holding the lock, and we can set the valid configuration since there is no global ref to it. this.configuration = configuration; } else { // Throws exception if validation failed. validateConfiguration(configuration); } if (!referenceCounter.hasInstanceAvailableForThread()) { createInstance(realmClass, referenceCounter, version); } referenceCounter.incrementThreadCount(1); //noinspection unchecked E realmInstance = (E) referenceCounter.getRealmInstance(); if (firstRealmInstanceInProcess) { // If flexible sync initial subscriptions are configured, we need to make // sure they are in the COMPLETE state before proceeding // TODO Ideally this would be part of `downloadInitialRemoteChanges` called before // but his requires a larger refactor, so for now just run the logic here. ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialFlexibleSyncData( Realm.createInstance(realmInstance.sharedRealm), configuration ); if (!configuration.isReadOnly()) { realmInstance.refresh(); } } return realmInstance; } private <E extends BaseRealm> ReferenceCounter getRefCounter(Class<E> realmClass, OsSharedRealm.VersionID version) { RealmCacheType cacheType = RealmCacheType.valueOf(realmClass); Pair<RealmCacheType, OsSharedRealm.VersionID> key = new Pair<>(cacheType, version); ReferenceCounter refCounter = refAndCountMap.get(key); if (refCounter == null) { if (version.equals(OsSharedRealm.VersionID.LIVE)) { refCounter = new ThreadConfinedReferenceCounter(); } else { refCounter = new GlobalReferenceCounter(); } refAndCountMap.put(key, refCounter); } return refCounter; } private <E extends BaseRealm> void createInstance(Class<E> realmClass, ReferenceCounter referenceCounter, OsSharedRealm.VersionID version) { // Creates a new local Realm instance BaseRealm realm; if (realmClass == Realm.class) { // RealmMigrationNeededException might be thrown here. realm = Realm.createInstance(this, version); // Only create mappings after the Realm was opened, so schema mismatch is correctly // thrown by ObjectStore when checking the schema. realm.getSchema().createKeyPathMapping(); } else if (realmClass == DynamicRealm.class) { realm = DynamicRealm.createInstance(this, version); } else { throw new IllegalArgumentException(WRONG_REALM_CLASS_MESSAGE); } referenceCounter.onRealmCreated(realm); } /** * Releases a given {@link Realm} or {@link DynamicRealm} from cache. The instance will be closed by this method * if there is no more local reference to this Realm instance in current Thread. * * @param realm Realm instance to be released from cache. */ synchronized void release(BaseRealm realm) { String canonicalPath = realm.getPath(); ReferenceCounter referenceCounter = getRefCounter(realm.getClass(), (realm.isFrozen()) ? realm.sharedRealm.getVersionID() : OsSharedRealm.VersionID.LIVE); int refCount = referenceCounter.getThreadLocalCount(); if (refCount <= 0) { RealmLog.warn("%s has been closed already. refCount is %s", canonicalPath, refCount); return; } // Decreases the local counter. refCount -= 1; if (refCount == 0) { referenceCounter.clearThreadLocalCache(); // No more local reference to this Realm in current thread, close the instance. realm.doClose(); // No more instance of typed Realm and dynamic Realm. if (getTotalLiveRealmGlobalRefCount() == 0) { // We keep the cache in the caches list even when its global counter reaches 0. It will be reused when // next time a Realm instance with the same path is opened. By not removing it, the lock on // cachesList is not needed here. configuration = null; // Close all frozen Realms. This can introduce race conditions on other // threads if the lifecyle of using Realm data is not correctly controlled. for (ReferenceCounter counter : refAndCountMap.values()) { if (counter instanceof GlobalReferenceCounter) { BaseRealm cachedRealm = counter.getRealmInstance(); // Since we don't remove ReferenceCounters, we need to check if the Realm is still open if (cachedRealm != null) { // Gracefully close frozen Realms in a similar way to what a user would normally do. while (!cachedRealm.isClosed()) { cachedRealm.close(); } } } } ObjectServerFacade.getFacade(realm.getConfiguration().isSyncConfiguration()).realmClosed(realm.getConfiguration()); } } else { referenceCounter.setThreadCount(refCount); } } /** * Makes sure that the new configuration doesn't clash with any cached configurations for the * Realm. * * @throws IllegalArgumentException if the new configuration isn't valid. */ private void validateConfiguration(RealmConfiguration newConfiguration) { if (configuration.equals(newConfiguration)) { // Same configuration objects. return; } // Checks that encryption keys aren't different. key is not in RealmConfiguration's toString. if (!Arrays.equals(configuration.getEncryptionKey(), newConfiguration.getEncryptionKey())) { throw new IllegalArgumentException(DIFFERENT_KEY_MESSAGE); } else { // A common problem is that people are forgetting to override `equals` in their custom migration class. // Tries to detect this problem specifically so we can throw a better error message. RealmMigration newMigration = newConfiguration.getMigration(); RealmMigration oldMigration = configuration.getMigration(); if (oldMigration != null && newMigration != null && oldMigration.getClass().equals(newMigration.getClass()) && !newMigration.equals(oldMigration)) { throw new IllegalArgumentException("Configurations cannot be different if used to open the same file. " + "The most likely cause is that equals() and hashCode() are not overridden in the " + "migration class: " + newConfiguration.getMigration().getClass().getCanonicalName()); } throw new IllegalArgumentException("Configurations cannot be different if used to open the same file. " + "\nCached configuration: \n" + configuration + "\n\nNew configuration: \n" + newConfiguration); } } /** * Runs the callback function with the total reference count of {@link Realm} and {@link DynamicRealm} who refer to * the given {@link RealmConfiguration}. * * @param configuration the {@link RealmConfiguration} of {@link Realm} or {@link DynamicRealm}. * @param callback the callback will be executed with the global reference count. */ static void invokeWithGlobalRefCount(RealmConfiguration configuration, Callback callback) { // NOTE: Although getCache is locked on the cacheMap, this whole method needs to be lock with it as // well. Since we need to ensure there is no Realm instance can be opened when this method is called (for // deleteRealm). // Recursive lock cannot be avoided here. synchronized (cachesList) { RealmCache cache = getCache(configuration.getPath(), false); if (cache == null) { callback.onResult(0); return; } cache.doInvokeWithGlobalRefCount(callback); } } private synchronized void doInvokeWithGlobalRefCount(Callback callback) { callback.onResult(getTotalGlobalRefCount()); } /** * Runs the callback function with synchronization on {@link RealmCache}. * * @param callback the callback will be executed. */ synchronized void invokeWithLock(Callback0 callback) { callback.onCall(); } /** * Copies Realm database file from Android asset directory to the directory given in the {@link RealmConfiguration}. * Copy is performed only at the first time when there is no Realm database file. * * WARNING: This method is not thread-safe so external synchronization is required before using it. * * @param configuration configuration object for Realm instance. * @throws RealmFileException if copying the file fails. */ private static void copyAssetFileIfNeeded(final RealmConfiguration configuration) { final File realmFileFromAsset = configuration.hasAssetFile() ? new File(configuration.getRealmDirectory(), configuration.getRealmFileName()) : null; String syncServerCertificateFilePath = ObjectServerFacade.getFacade( configuration.isSyncConfiguration()).getSyncServerCertificateFilePath(configuration ); final boolean certFileExists = !Util.isEmptyString(syncServerCertificateFilePath); if (realmFileFromAsset!= null || certFileExists) { OsObjectStore.callWithLock(configuration, new Runnable() { @Override public void run() { if (realmFileFromAsset != null) { copyFileIfNeeded(configuration.getAssetFilePath(), realmFileFromAsset); } // Copy Sync Server certificate path if available if (certFileExists) { final String syncServerCertificateAssetName = ObjectServerFacade.getFacade( configuration.isSyncConfiguration() ).getSyncServerCertificateAssetName(configuration); File certificateFile = new File(syncServerCertificateFilePath); copyFileIfNeeded(syncServerCertificateAssetName, certificateFile); } } }); } } private static void copyFileIfNeeded(String assetFileName, File file) { if (file.exists()) { return; } IOException exceptionWhenClose = null; InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = BaseRealm.applicationContext.getAssets().open(assetFileName); if (inputStream == null) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, "Invalid input stream to the asset file: " + assetFileName); } outputStream = new FileOutputStream(file); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buf)) > -1) { outputStream.write(buf, 0, bytesRead); } } catch (IOException e) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, "Could not resolve the path to the asset file: " + assetFileName, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { exceptionWhenClose = e; } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // Ignores this one if there was an exception when close inputStream. if (exceptionWhenClose == null) { exceptionWhenClose = e; } } } } // No other exception has been thrown, only the exception when close. So, throw it. if (exceptionWhenClose != null) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, exceptionWhenClose); } } static int getLocalThreadCount(RealmConfiguration configuration) { RealmCache cache = getCache(configuration.getPath(), false); if (cache == null) { return 0; } // Access local ref count only, no need to be synchronized. int totalRefCount = 0; for (ReferenceCounter referenceCounter : cache.refAndCountMap.values()) { totalRefCount += referenceCounter.getThreadLocalCount(); } return totalRefCount; } public RealmConfiguration getConfiguration() { return configuration; } /** * @return the total global ref count. */ private int getTotalGlobalRefCount() { int totalRefCount = 0; for (ReferenceCounter referenceCounter : refAndCountMap.values()) { totalRefCount += referenceCounter.getGlobalCount(); } return totalRefCount; } /** * Returns the total number of threads containg a reference to a live instance of the Realm. */ private int getTotalLiveRealmGlobalRefCount() { int totalRefCount = 0; for (ReferenceCounter referenceCounter : refAndCountMap.values()) { if (referenceCounter instanceof ThreadConfinedReferenceCounter) { totalRefCount += referenceCounter.getGlobalCount(); } } return totalRefCount; } /** * If a Realm instance is GCed but `Realm.close()` is not called before, we still want to track the cache for * debugging. Adding them to the list to keep the strong ref of the cache to prevent the cache gets GCed. */ void leak() { if (!isLeaked.getAndSet(true)) { leakedCaches.add(this); } } }
realm/realm-java
realm/realm-library/src/main/java/io/realm/RealmCache.java
7,494
// Should never happen.
line_comment
nl
/* * Copyright 2015 Realm 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 io.realm; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import io.realm.exceptions.RealmFileException; import io.realm.internal.Capabilities; import io.realm.internal.ObjectServerFacade; import io.realm.internal.OsObjectStore; import io.realm.internal.OsRealmConfig; import io.realm.internal.OsSharedRealm; import io.realm.internal.RealmNotifier; import io.realm.internal.Util; import io.realm.internal.android.AndroidCapabilities; import io.realm.internal.android.AndroidRealmNotifier; import io.realm.internal.async.RealmAsyncTaskImpl; import io.realm.internal.util.Pair; import io.realm.log.RealmLog; /** * To cache {@link Realm}, {@link DynamicRealm} instances and related resources. * Every thread will share the same {@link Realm} and {@link DynamicRealm} instances which are referred to the same * {@link RealmConfiguration}. * One {@link RealmCache} is created for each {@link RealmConfiguration}, and it caches all the {@link Realm} and * {@link DynamicRealm} instances which are created from the same {@link RealmConfiguration}. */ final class RealmCache { interface Callback { void onResult(int count); } interface Callback0 { void onCall(); } private abstract static class ReferenceCounter { // How many references to this Realm instance in this thread. protected final ThreadLocal<Integer> localCount = new ThreadLocal<>(); // How many threads have instances refer to this configuration. protected AtomicInteger globalCount = new AtomicInteger(0); // Returns `true` if an instance of the Realm is available on the caller thread. abstract boolean hasInstanceAvailableForThread(); // Increment how many times an instance has been handed out for the current thread. public void incrementThreadCount(int increment) { Integer currentCount = localCount.get(); localCount.set(currentCount != null ? currentCount + increment : increment); } // Returns the Realm instance for the caller thread abstract BaseRealm getRealmInstance(); // Cache the Realm instance. Should only be called when `hasInstanceAvailableForThread` returns false. abstract void onRealmCreated(BaseRealm realm); // Clears the the cache for a given thread when all Realms on that thread are closed. abstract void clearThreadLocalCache(); // Returns the number of instances handed out for the caller thread. abstract int getThreadLocalCount(); // Updates the number of references handed out for a given thread public void setThreadCount(int refCount) { localCount.set(refCount); } // Returns the number of gloal instances handed out. This is roughly equivalent // to the number of threads currently using the Realm as each thread also does // reference counting of Realm instances. public int getGlobalCount() { return globalCount.get(); } } // Reference counter for Realms that are accessible across all threads private static class GlobalReferenceCounter extends ReferenceCounter { private BaseRealm cachedRealm; @Override boolean hasInstanceAvailableForThread() { return cachedRealm != null; } @Override BaseRealm getRealmInstance() { return cachedRealm; } @Override void onRealmCreated(BaseRealm realm) { // The Realm instance has been created without exceptions. Cache and reference count can be updated now. cachedRealm = realm; localCount.set(0); // This is the first instance in current thread, increase the global count. globalCount.incrementAndGet(); } @Override public void clearThreadLocalCache() { String canonicalPath = cachedRealm.getPath(); // The last instance in this thread. // Clears local ref & counter. localCount.set(null); cachedRealm = null; // Clears global counter. if (globalCount.decrementAndGet() < 0) { // Should never happen. throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " not be negative."); } } @Override int getThreadLocalCount() { // For frozen Realms the Realm can be accessed from all threads, so the concept // of a thread local count doesn't make sense. Just return the global count instead. return globalCount.get(); } } // Reference counter for Realms that are thread confined private static class ThreadConfinedReferenceCounter extends ReferenceCounter { // The Realm instance in this thread. private final ThreadLocal<BaseRealm> localRealm = new ThreadLocal<>(); @Override public boolean hasInstanceAvailableForThread() { return localRealm.get() != null; } @Override public BaseRealm getRealmInstance() { return localRealm.get(); } @Override public void onRealmCreated(BaseRealm realm) { // The Realm instance has been created without exceptions. Cache and reference count can be updated now. localRealm.set(realm); localCount.set(0); // This is the first instance in current thread, increase the global count. globalCount.incrementAndGet(); } @Override public void clearThreadLocalCache() { String canonicalPath = localRealm.get().getPath(); // The last instance in this thread. // Clears local ref & counter. localCount.set(null); localRealm.set(null); // Clears global counter. if (globalCount.decrementAndGet() < 0) { // Should never<SUF> throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " can not be negative."); } } @Override public int getThreadLocalCount() { Integer refCount = localCount.get(); return (refCount != null) ? refCount : 0; } } private enum RealmCacheType { TYPED_REALM, DYNAMIC_REALM; static RealmCacheType valueOf(Class<? extends BaseRealm> clazz) { if (clazz == Realm.class) { return TYPED_REALM; } else if (clazz == DynamicRealm.class) { return DYNAMIC_REALM; } throw new IllegalArgumentException(WRONG_REALM_CLASS_MESSAGE); } } private static class CreateRealmRunnable<T extends BaseRealm> implements Runnable { private final RealmConfiguration configuration; private final BaseRealm.InstanceCallback<T> callback; private final Class<T> realmClass; private final CountDownLatch canReleaseBackgroundInstanceLatch = new CountDownLatch(1); private final RealmNotifier notifier; // The Future this runnable belongs to. private Future future; CreateRealmRunnable(RealmNotifier notifier, RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { this.configuration = configuration; this.realmClass = realmClass; this.callback = callback; this.notifier = notifier; } public void setFuture(Future future) { this.future = future; } @Override public void run() { T instance = null; try { // First call that will run all schema validation, migrations or initial transactions. instance = createRealmOrGetFromCache(configuration, realmClass); boolean results = notifier.post(new Runnable() { @Override public void run() { // If the RealmAsyncTask.cancel() is called before, we just return without creating the Realm // instance on the caller thread. // Thread.isInterrupted() cannot be used for checking here since CountDownLatch.await() will // will clear interrupted status. // Using the future to check which this runnable belongs to is to ensure if it is canceled from // the caller thread before, the callback will never be delivered. if (future == null || future.isCancelled()) { canReleaseBackgroundInstanceLatch.countDown(); return; } T instanceToReturn = null; Throwable throwable = null; try { // This will run on the caller thread, but since the first `createRealmOrGetFromCache` // should have completed at this point, all expensive initializer functions have already // run. instanceToReturn = createRealmOrGetFromCache(configuration, realmClass); } catch (Throwable e) { throwable = e; } finally { canReleaseBackgroundInstanceLatch.countDown(); } if (instanceToReturn != null) { callback.onSuccess(instanceToReturn); } else { // throwable is non-null //noinspection ConstantConditions callback.onError(throwable); } } }); if (!results) { canReleaseBackgroundInstanceLatch.countDown(); } // There is a small chance that the posted runnable cannot be executed because of the thread terminated // before the runnable gets fetched from the event queue. if (!canReleaseBackgroundInstanceLatch.await(2, TimeUnit.SECONDS)) { RealmLog.warn("Timeout for creating Realm instance in foreground thread in `CreateRealmRunnable` "); } } catch (InterruptedException e) { RealmLog.warn(e, "`CreateRealmRunnable` has been interrupted."); } catch (final Throwable e) { // DownloadingRealmInterruptedException is treated specially. // It async open is canceled, this could interrupt the download, but the user should // not care in this case, so just ignore it. if (!ObjectServerFacade.getSyncFacadeIfPossible().wasDownloadInterrupted(e)) { RealmLog.error(e, "`CreateRealmRunnable` failed."); notifier.post(new Runnable() { @Override public void run() { callback.onError(e); } }); } } finally { if (instance != null) { instance.close(); } } } } private static final String ASYNC_NOT_ALLOWED_MSG = "Realm instances cannot be loaded asynchronously on a non-looper thread."; private static final String ASYNC_CALLBACK_NULL_MSG = "The callback cannot be null."; // Separated references and counters for typed Realm and dynamic Realm. private final Map<Pair<RealmCacheType, OsSharedRealm.VersionID>, ReferenceCounter> refAndCountMap = new HashMap<>(); // Path to the Realm file to identify this cache. private final String realmPath; // This will be only valid if getTotalGlobalRefCount() > 0. // NOTE: We do reset this when globalCount reaches 0, but if exception thrown in doCreateRealmOrGetFromCache at the // first time when globalCount == 0, this could have a non-null value but it will be reset when the next // doCreateRealmOrGetFromCache is called with globalCount == 0. private RealmConfiguration configuration; // Realm path will be used to identify different RealmCaches. Different Realm configurations with same path // are not allowed and an exception will be thrown when trying to add it to the cache list. // A weak ref is used to hold the RealmCache instance. The weak ref entry will be cleared if and only if there // is no Realm instance holding a strong ref to it and there is no Realm instance associated it is BEING created. private static final List<WeakReference<RealmCache>> cachesList = new ArrayList<WeakReference<RealmCache>>(); // See leak() // isLeaked flag is used to avoid adding strong ref multiple times without iterating the list. private final AtomicBoolean isLeaked = new AtomicBoolean(false); // Keep strong ref to the leaked RealmCache @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private static final Collection<RealmCache> leakedCaches = new ConcurrentLinkedQueue<RealmCache>(); // Keeps track if a Realm needs to download its initial remote data private final Set<String> pendingRealmFileCreation = new HashSet<>(); private static final String DIFFERENT_KEY_MESSAGE = "Wrong key used to decrypt Realm."; private static final String WRONG_REALM_CLASS_MESSAGE = "The type of Realm class must be Realm or DynamicRealm."; private RealmCache(String path) { realmPath = path; } private static RealmCache getCache(String realmPath, boolean createIfNotExist) { RealmCache cacheToReturn = null; synchronized (cachesList) { Iterator<WeakReference<RealmCache>> it = cachesList.iterator(); while (it.hasNext()) { RealmCache cache = it.next().get(); if (cache == null) { // Clear the entry if there is no one holding the RealmCache. it.remove(); } else if (cache.realmPath.equals(realmPath)) { cacheToReturn = cache; } } if (cacheToReturn == null && createIfNotExist) { cacheToReturn = new RealmCache(realmPath); cachesList.add(new WeakReference<RealmCache>(cacheToReturn)); } } return cacheToReturn; } static <T extends BaseRealm> RealmAsyncTask createRealmOrGetFromCacheAsync( RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCacheAsync(configuration, callback, realmClass); } private synchronized <T extends BaseRealm> RealmAsyncTask doCreateRealmOrGetFromCacheAsync( RealmConfiguration configuration, BaseRealm.InstanceCallback<T> callback, Class<T> realmClass) { Capabilities capabilities = new AndroidCapabilities(); capabilities.checkCanDeliverNotification(ASYNC_NOT_ALLOWED_MSG); //noinspection ConstantConditions if (callback == null) { throw new IllegalArgumentException(ASYNC_CALLBACK_NULL_MSG); } // If there is no Realm file it means that we need to sync the initial remote data in the worker thread. if (configuration.isSyncConfiguration() && !configuration.realmExists()) { pendingRealmFileCreation.add(configuration.getPath()); } // Always create a Realm instance in the background thread even when there are instances existing on current // thread. This to ensure that onSuccess will always be called in the following event loop but not current one. CreateRealmRunnable<T> createRealmRunnable = new CreateRealmRunnable<T>( new AndroidRealmNotifier(null, capabilities), configuration, callback, realmClass); Future<?> future = BaseRealm.asyncTaskExecutor.submitTransaction(createRealmRunnable); createRealmRunnable.setFuture(future); // For Realms using Async Open on the server, we need to create the session right away // in order to interact with it in a imperative way, e.g. by attaching download progress // listeners ObjectServerFacade.getSyncFacadeIfPossible().createNativeSyncSession(configuration); return new RealmAsyncTaskImpl(future, BaseRealm.asyncTaskExecutor); } /** * Creates a new Realm instance or get an existing instance for current thread. * * @param configuration {@link RealmConfiguration} will be used to create or get the instance. * @param realmClass class of {@link Realm} or {@link DynamicRealm} to be created in or gotten from the cache. * @return the {@link Realm} or {@link DynamicRealm} instance. */ static <E extends BaseRealm> E createRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCache(configuration, realmClass, OsSharedRealm.VersionID.LIVE); } static <E extends BaseRealm> E createRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { RealmCache cache = getCache(configuration.getPath(), true); return cache.doCreateRealmOrGetFromCache(configuration, realmClass, version); } private synchronized <E extends BaseRealm> E doCreateRealmOrGetFromCache(RealmConfiguration configuration, Class<E> realmClass, OsSharedRealm.VersionID version) { ReferenceCounter referenceCounter = getRefCounter(realmClass, version); boolean firstRealmInstanceInProcess = (getTotalGlobalRefCount() == 0); if (firstRealmInstanceInProcess) { copyAssetFileIfNeeded(configuration); // If waitForInitialRemoteData() was enabled, we need to make sure that all data is downloaded // before proceeding. We need to open the Realm instance first to start any potential underlying // SyncSession so this will work. boolean realmFileIsBeingCreated = !configuration.realmExists(); if (configuration.isSyncConfiguration() && (realmFileIsBeingCreated || pendingRealmFileCreation.contains(configuration.getPath()))) { // Manually create the Java session wrapper session as this might otherwise // not be created OsRealmConfig osConfig = new OsRealmConfig.Builder(configuration).build(); ObjectServerFacade.getSyncFacadeIfPossible().wrapObjectStoreSessionIfRequired(osConfig); // Fully synchronized Realms are supported by AsyncOpen ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialRemoteChanges(configuration); // Initial remote data has been synced at this point pendingRealmFileCreation.remove(configuration.getPath()); } // We are holding the lock, and we can set the valid configuration since there is no global ref to it. this.configuration = configuration; } else { // Throws exception if validation failed. validateConfiguration(configuration); } if (!referenceCounter.hasInstanceAvailableForThread()) { createInstance(realmClass, referenceCounter, version); } referenceCounter.incrementThreadCount(1); //noinspection unchecked E realmInstance = (E) referenceCounter.getRealmInstance(); if (firstRealmInstanceInProcess) { // If flexible sync initial subscriptions are configured, we need to make // sure they are in the COMPLETE state before proceeding // TODO Ideally this would be part of `downloadInitialRemoteChanges` called before // but his requires a larger refactor, so for now just run the logic here. ObjectServerFacade.getSyncFacadeIfPossible().downloadInitialFlexibleSyncData( Realm.createInstance(realmInstance.sharedRealm), configuration ); if (!configuration.isReadOnly()) { realmInstance.refresh(); } } return realmInstance; } private <E extends BaseRealm> ReferenceCounter getRefCounter(Class<E> realmClass, OsSharedRealm.VersionID version) { RealmCacheType cacheType = RealmCacheType.valueOf(realmClass); Pair<RealmCacheType, OsSharedRealm.VersionID> key = new Pair<>(cacheType, version); ReferenceCounter refCounter = refAndCountMap.get(key); if (refCounter == null) { if (version.equals(OsSharedRealm.VersionID.LIVE)) { refCounter = new ThreadConfinedReferenceCounter(); } else { refCounter = new GlobalReferenceCounter(); } refAndCountMap.put(key, refCounter); } return refCounter; } private <E extends BaseRealm> void createInstance(Class<E> realmClass, ReferenceCounter referenceCounter, OsSharedRealm.VersionID version) { // Creates a new local Realm instance BaseRealm realm; if (realmClass == Realm.class) { // RealmMigrationNeededException might be thrown here. realm = Realm.createInstance(this, version); // Only create mappings after the Realm was opened, so schema mismatch is correctly // thrown by ObjectStore when checking the schema. realm.getSchema().createKeyPathMapping(); } else if (realmClass == DynamicRealm.class) { realm = DynamicRealm.createInstance(this, version); } else { throw new IllegalArgumentException(WRONG_REALM_CLASS_MESSAGE); } referenceCounter.onRealmCreated(realm); } /** * Releases a given {@link Realm} or {@link DynamicRealm} from cache. The instance will be closed by this method * if there is no more local reference to this Realm instance in current Thread. * * @param realm Realm instance to be released from cache. */ synchronized void release(BaseRealm realm) { String canonicalPath = realm.getPath(); ReferenceCounter referenceCounter = getRefCounter(realm.getClass(), (realm.isFrozen()) ? realm.sharedRealm.getVersionID() : OsSharedRealm.VersionID.LIVE); int refCount = referenceCounter.getThreadLocalCount(); if (refCount <= 0) { RealmLog.warn("%s has been closed already. refCount is %s", canonicalPath, refCount); return; } // Decreases the local counter. refCount -= 1; if (refCount == 0) { referenceCounter.clearThreadLocalCache(); // No more local reference to this Realm in current thread, close the instance. realm.doClose(); // No more instance of typed Realm and dynamic Realm. if (getTotalLiveRealmGlobalRefCount() == 0) { // We keep the cache in the caches list even when its global counter reaches 0. It will be reused when // next time a Realm instance with the same path is opened. By not removing it, the lock on // cachesList is not needed here. configuration = null; // Close all frozen Realms. This can introduce race conditions on other // threads if the lifecyle of using Realm data is not correctly controlled. for (ReferenceCounter counter : refAndCountMap.values()) { if (counter instanceof GlobalReferenceCounter) { BaseRealm cachedRealm = counter.getRealmInstance(); // Since we don't remove ReferenceCounters, we need to check if the Realm is still open if (cachedRealm != null) { // Gracefully close frozen Realms in a similar way to what a user would normally do. while (!cachedRealm.isClosed()) { cachedRealm.close(); } } } } ObjectServerFacade.getFacade(realm.getConfiguration().isSyncConfiguration()).realmClosed(realm.getConfiguration()); } } else { referenceCounter.setThreadCount(refCount); } } /** * Makes sure that the new configuration doesn't clash with any cached configurations for the * Realm. * * @throws IllegalArgumentException if the new configuration isn't valid. */ private void validateConfiguration(RealmConfiguration newConfiguration) { if (configuration.equals(newConfiguration)) { // Same configuration objects. return; } // Checks that encryption keys aren't different. key is not in RealmConfiguration's toString. if (!Arrays.equals(configuration.getEncryptionKey(), newConfiguration.getEncryptionKey())) { throw new IllegalArgumentException(DIFFERENT_KEY_MESSAGE); } else { // A common problem is that people are forgetting to override `equals` in their custom migration class. // Tries to detect this problem specifically so we can throw a better error message. RealmMigration newMigration = newConfiguration.getMigration(); RealmMigration oldMigration = configuration.getMigration(); if (oldMigration != null && newMigration != null && oldMigration.getClass().equals(newMigration.getClass()) && !newMigration.equals(oldMigration)) { throw new IllegalArgumentException("Configurations cannot be different if used to open the same file. " + "The most likely cause is that equals() and hashCode() are not overridden in the " + "migration class: " + newConfiguration.getMigration().getClass().getCanonicalName()); } throw new IllegalArgumentException("Configurations cannot be different if used to open the same file. " + "\nCached configuration: \n" + configuration + "\n\nNew configuration: \n" + newConfiguration); } } /** * Runs the callback function with the total reference count of {@link Realm} and {@link DynamicRealm} who refer to * the given {@link RealmConfiguration}. * * @param configuration the {@link RealmConfiguration} of {@link Realm} or {@link DynamicRealm}. * @param callback the callback will be executed with the global reference count. */ static void invokeWithGlobalRefCount(RealmConfiguration configuration, Callback callback) { // NOTE: Although getCache is locked on the cacheMap, this whole method needs to be lock with it as // well. Since we need to ensure there is no Realm instance can be opened when this method is called (for // deleteRealm). // Recursive lock cannot be avoided here. synchronized (cachesList) { RealmCache cache = getCache(configuration.getPath(), false); if (cache == null) { callback.onResult(0); return; } cache.doInvokeWithGlobalRefCount(callback); } } private synchronized void doInvokeWithGlobalRefCount(Callback callback) { callback.onResult(getTotalGlobalRefCount()); } /** * Runs the callback function with synchronization on {@link RealmCache}. * * @param callback the callback will be executed. */ synchronized void invokeWithLock(Callback0 callback) { callback.onCall(); } /** * Copies Realm database file from Android asset directory to the directory given in the {@link RealmConfiguration}. * Copy is performed only at the first time when there is no Realm database file. * * WARNING: This method is not thread-safe so external synchronization is required before using it. * * @param configuration configuration object for Realm instance. * @throws RealmFileException if copying the file fails. */ private static void copyAssetFileIfNeeded(final RealmConfiguration configuration) { final File realmFileFromAsset = configuration.hasAssetFile() ? new File(configuration.getRealmDirectory(), configuration.getRealmFileName()) : null; String syncServerCertificateFilePath = ObjectServerFacade.getFacade( configuration.isSyncConfiguration()).getSyncServerCertificateFilePath(configuration ); final boolean certFileExists = !Util.isEmptyString(syncServerCertificateFilePath); if (realmFileFromAsset!= null || certFileExists) { OsObjectStore.callWithLock(configuration, new Runnable() { @Override public void run() { if (realmFileFromAsset != null) { copyFileIfNeeded(configuration.getAssetFilePath(), realmFileFromAsset); } // Copy Sync Server certificate path if available if (certFileExists) { final String syncServerCertificateAssetName = ObjectServerFacade.getFacade( configuration.isSyncConfiguration() ).getSyncServerCertificateAssetName(configuration); File certificateFile = new File(syncServerCertificateFilePath); copyFileIfNeeded(syncServerCertificateAssetName, certificateFile); } } }); } } private static void copyFileIfNeeded(String assetFileName, File file) { if (file.exists()) { return; } IOException exceptionWhenClose = null; InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = BaseRealm.applicationContext.getAssets().open(assetFileName); if (inputStream == null) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, "Invalid input stream to the asset file: " + assetFileName); } outputStream = new FileOutputStream(file); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buf)) > -1) { outputStream.write(buf, 0, bytesRead); } } catch (IOException e) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, "Could not resolve the path to the asset file: " + assetFileName, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { exceptionWhenClose = e; } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { // Ignores this one if there was an exception when close inputStream. if (exceptionWhenClose == null) { exceptionWhenClose = e; } } } } // No other exception has been thrown, only the exception when close. So, throw it. if (exceptionWhenClose != null) { throw new RealmFileException(RealmFileException.Kind.ACCESS_ERROR, exceptionWhenClose); } } static int getLocalThreadCount(RealmConfiguration configuration) { RealmCache cache = getCache(configuration.getPath(), false); if (cache == null) { return 0; } // Access local ref count only, no need to be synchronized. int totalRefCount = 0; for (ReferenceCounter referenceCounter : cache.refAndCountMap.values()) { totalRefCount += referenceCounter.getThreadLocalCount(); } return totalRefCount; } public RealmConfiguration getConfiguration() { return configuration; } /** * @return the total global ref count. */ private int getTotalGlobalRefCount() { int totalRefCount = 0; for (ReferenceCounter referenceCounter : refAndCountMap.values()) { totalRefCount += referenceCounter.getGlobalCount(); } return totalRefCount; } /** * Returns the total number of threads containg a reference to a live instance of the Realm. */ private int getTotalLiveRealmGlobalRefCount() { int totalRefCount = 0; for (ReferenceCounter referenceCounter : refAndCountMap.values()) { if (referenceCounter instanceof ThreadConfinedReferenceCounter) { totalRefCount += referenceCounter.getGlobalCount(); } } return totalRefCount; } /** * If a Realm instance is GCed but `Realm.close()` is not called before, we still want to track the cache for * debugging. Adding them to the list to keep the strong ref of the cache to prevent the cache gets GCed. */ void leak() { if (!isLeaked.getAndSet(true)) { leakedCaches.add(this); } } }
201424_9
package decaf.dataflow; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.HashSet; import decaf.machdesc.Asm; import decaf.machdesc.Register; import decaf.tac.Label; import decaf.tac.Tac; import decaf.tac.Temp; public class BasicBlock { public int bbNum; public enum EndKind { BY_BRANCH, BY_BEQZ, BY_BNEZ, BY_RETURN } public EndKind endKind; public int inDegree; public Tac tacList; public Label label; public Temp var; public Register varReg; public int[] next; public boolean cancelled; public boolean mark; public Set<Temp> def; public Set<Temp> liveUse; public Set<Temp> liveIn; public Set<Temp> liveOut; public Set<Temp> saves; private List<Asm> asms; public BasicBlock() { def = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveUse = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveIn = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveOut = new TreeSet<Temp>(Temp.ID_COMPARATOR); next = new int[2]; asms = new ArrayList<Asm>(); } public void computeDefAndLiveUse() { for (Tac tac = tacList; tac != null; tac = tac.next) { switch (tac.opc) { case ADD: case SUB: case MUL: case DIV: case MOD: case LAND: case LOR: case GTR: case GEQ: case EQU: case NEQ: case LEQ: case LES: /* use op1 and op2, def op0 */ if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } if (tac.op2.lastVisitedBB != bbNum) { liveUse.add (tac.op2); tac.op2.lastVisitedBB = bbNum; } if (tac.op0.lastVisitedBB != bbNum) { def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case NEG: case LNOT: case ASSIGN: case INDIRECT_CALL: case LOAD: /* use op1, def op0 */ if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } if (tac.op0 != null && tac.op0.lastVisitedBB != bbNum) { // in INDIRECT_CALL with return type VOID, // tac.op0 is null def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case LOAD_VTBL: case DIRECT_CALL: case RETURN: case LOAD_STR_CONST: case LOAD_IMM4: /* def op0 */ if (tac.op0 != null && tac.op0.lastVisitedBB != bbNum) { // in DIRECT_CALL with return type VOID, // tac.op0 is null def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case STORE: /* use op0 and op1*/ if (tac.op0.lastVisitedBB != bbNum) { liveUse.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } break; case PARM: /* use op0 */ if (tac.op0.lastVisitedBB != bbNum) { liveUse.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; default: /* BRANCH MEMO MARK PARM*/ break; } } if (var != null && var.lastVisitedBB != bbNum) { liveUse.add (var); var.lastVisitedBB = bbNum; } liveIn.addAll (liveUse); } public void analyzeLiveness() { if (tacList == null) return; Tac tac = tacList; for (; tac.next != null; tac = tac.next); tac.liveOut = new HashSet<Temp> (liveOut); if (var != null) tac.liveOut.add (var); for (; tac != tacList; tac = tac.prev) { tac.prev.liveOut = new HashSet<Temp> (tac.liveOut); switch (tac.opc) { case ADD: case SUB: case MUL: case DIV: case MOD: case LAND: case LOR: case GTR: case GEQ: case EQU: case NEQ: case LEQ: case LES: /* use op1 and op2, def op0 */ tac.prev.liveOut.remove (tac.op0); tac.prev.liveOut.add (tac.op1); tac.prev.liveOut.add (tac.op2); break; case NEG: case LNOT: case ASSIGN: case INDIRECT_CALL: case LOAD: /* use op1, def op0 */ tac.prev.liveOut.remove (tac.op0); tac.prev.liveOut.add (tac.op1); break; case LOAD_VTBL: case DIRECT_CALL: case RETURN: case LOAD_STR_CONST: case LOAD_IMM4: /* def op0 */ tac.prev.liveOut.remove (tac.op0); break; case STORE: /* use op0 and op1*/ tac.prev.liveOut.add (tac.op0); tac.prev.liveOut.add (tac.op1); break; case BEQZ: case BNEZ: case PARM: /* use op0 */ tac.prev.liveOut.add (tac.op0); break; default: /* BRANCH MEMO MARK PARM*/ break; } } } public void printTo(PrintWriter pw) { pw.println("BASIC BLOCK " + bbNum + " : "); for (Tac t = tacList; t != null; t = t.next) { pw.println(" " + t); } switch (endKind) { case BY_BRANCH: pw.println("END BY BRANCH, goto " + next[0]); break; case BY_BEQZ: pw.println("END BY BEQZ, if " + var.name + " = "); pw.println(" 0 : goto " + next[0] + "; 1 : goto " + next[1]); break; case BY_BNEZ: pw.println("END BY BGTZ, if " + var.name + " = "); pw.println(" 1 : goto " + next[0] + "; 0 : goto " + next[1]); break; case BY_RETURN: if (var != null) { pw.println("END BY RETURN, result = " + var.name); } else { pw.println("END BY RETURN, void result"); } break; } } public void printLivenessTo(PrintWriter pw) { pw.println("BASIC BLOCK " + bbNum + " : "); pw.println(" Def = " + toString(def)); pw.println(" liveUse = " + toString(liveUse)); pw.println(" liveIn = " + toString(liveIn)); pw.println(" liveOut = " + toString(liveOut)); for (Tac t = tacList; t != null; t = t.next) { pw.println(" " + t + " " + toString(t.liveOut)); } switch (endKind) { case BY_BRANCH: pw.println("END BY BRANCH, goto " + next[0]); break; case BY_BEQZ: pw.println("END BY BEQZ, if " + var.name + " = "); pw.println(" 0 : goto " + next[0] + "; 1 : goto " + next[1]); break; case BY_BNEZ: pw.println("END BY BGTZ, if " + var.name + " = "); pw.println(" 1 : goto " + next[0] + "; 0 : goto " + next[1]); break; case BY_RETURN: if (var != null) { pw.println("END BY RETURN, result = " + var.name); } else { pw.println("END BY RETURN, void result"); } break; } } public String toString(Set<Temp> set) { StringBuilder sb = new StringBuilder("[ "); for (Temp t : set) { sb.append(t.name + " "); } sb.append(']'); return sb.toString(); } public void insertBefore(Tac insert, Tac base) { if (base == tacList) { tacList = insert; } else { base.prev.next = insert; } insert.prev = base.prev; base.prev = insert; insert.next = base; } public void insertAfter(Tac insert, Tac base) { if (tacList == null) { tacList = insert; insert.next = null; return; } if (base.next != null) { base.next.prev = insert; } insert.prev = base; insert.next = base.next; base.next = insert; } public void appendAsm(Asm asm) { asms.add(asm); } public List<Asm> getAsms() { return asms; } }
PKUanonym/REKCARC-TSC-UHT
大三上/编译原理/hw/2016_黄家晖_PA/627604533_5_decaf_PA4/src/decaf/dataflow/BasicBlock.java
2,619
/* use op1, def op0 */
block_comment
nl
package decaf.dataflow; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.HashSet; import decaf.machdesc.Asm; import decaf.machdesc.Register; import decaf.tac.Label; import decaf.tac.Tac; import decaf.tac.Temp; public class BasicBlock { public int bbNum; public enum EndKind { BY_BRANCH, BY_BEQZ, BY_BNEZ, BY_RETURN } public EndKind endKind; public int inDegree; public Tac tacList; public Label label; public Temp var; public Register varReg; public int[] next; public boolean cancelled; public boolean mark; public Set<Temp> def; public Set<Temp> liveUse; public Set<Temp> liveIn; public Set<Temp> liveOut; public Set<Temp> saves; private List<Asm> asms; public BasicBlock() { def = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveUse = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveIn = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveOut = new TreeSet<Temp>(Temp.ID_COMPARATOR); next = new int[2]; asms = new ArrayList<Asm>(); } public void computeDefAndLiveUse() { for (Tac tac = tacList; tac != null; tac = tac.next) { switch (tac.opc) { case ADD: case SUB: case MUL: case DIV: case MOD: case LAND: case LOR: case GTR: case GEQ: case EQU: case NEQ: case LEQ: case LES: /* use op1 and op2, def op0 */ if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } if (tac.op2.lastVisitedBB != bbNum) { liveUse.add (tac.op2); tac.op2.lastVisitedBB = bbNum; } if (tac.op0.lastVisitedBB != bbNum) { def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case NEG: case LNOT: case ASSIGN: case INDIRECT_CALL: case LOAD: /* use op1, def op0 */ if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } if (tac.op0 != null && tac.op0.lastVisitedBB != bbNum) { // in INDIRECT_CALL with return type VOID, // tac.op0 is null def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case LOAD_VTBL: case DIRECT_CALL: case RETURN: case LOAD_STR_CONST: case LOAD_IMM4: /* def op0 */ if (tac.op0 != null && tac.op0.lastVisitedBB != bbNum) { // in DIRECT_CALL with return type VOID, // tac.op0 is null def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case STORE: /* use op0 and op1*/ if (tac.op0.lastVisitedBB != bbNum) { liveUse.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } break; case PARM: /* use op0 */ if (tac.op0.lastVisitedBB != bbNum) { liveUse.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; default: /* BRANCH MEMO MARK PARM*/ break; } } if (var != null && var.lastVisitedBB != bbNum) { liveUse.add (var); var.lastVisitedBB = bbNum; } liveIn.addAll (liveUse); } public void analyzeLiveness() { if (tacList == null) return; Tac tac = tacList; for (; tac.next != null; tac = tac.next); tac.liveOut = new HashSet<Temp> (liveOut); if (var != null) tac.liveOut.add (var); for (; tac != tacList; tac = tac.prev) { tac.prev.liveOut = new HashSet<Temp> (tac.liveOut); switch (tac.opc) { case ADD: case SUB: case MUL: case DIV: case MOD: case LAND: case LOR: case GTR: case GEQ: case EQU: case NEQ: case LEQ: case LES: /* use op1 and op2, def op0 */ tac.prev.liveOut.remove (tac.op0); tac.prev.liveOut.add (tac.op1); tac.prev.liveOut.add (tac.op2); break; case NEG: case LNOT: case ASSIGN: case INDIRECT_CALL: case LOAD: /* use op1, def<SUF>*/ tac.prev.liveOut.remove (tac.op0); tac.prev.liveOut.add (tac.op1); break; case LOAD_VTBL: case DIRECT_CALL: case RETURN: case LOAD_STR_CONST: case LOAD_IMM4: /* def op0 */ tac.prev.liveOut.remove (tac.op0); break; case STORE: /* use op0 and op1*/ tac.prev.liveOut.add (tac.op0); tac.prev.liveOut.add (tac.op1); break; case BEQZ: case BNEZ: case PARM: /* use op0 */ tac.prev.liveOut.add (tac.op0); break; default: /* BRANCH MEMO MARK PARM*/ break; } } } public void printTo(PrintWriter pw) { pw.println("BASIC BLOCK " + bbNum + " : "); for (Tac t = tacList; t != null; t = t.next) { pw.println(" " + t); } switch (endKind) { case BY_BRANCH: pw.println("END BY BRANCH, goto " + next[0]); break; case BY_BEQZ: pw.println("END BY BEQZ, if " + var.name + " = "); pw.println(" 0 : goto " + next[0] + "; 1 : goto " + next[1]); break; case BY_BNEZ: pw.println("END BY BGTZ, if " + var.name + " = "); pw.println(" 1 : goto " + next[0] + "; 0 : goto " + next[1]); break; case BY_RETURN: if (var != null) { pw.println("END BY RETURN, result = " + var.name); } else { pw.println("END BY RETURN, void result"); } break; } } public void printLivenessTo(PrintWriter pw) { pw.println("BASIC BLOCK " + bbNum + " : "); pw.println(" Def = " + toString(def)); pw.println(" liveUse = " + toString(liveUse)); pw.println(" liveIn = " + toString(liveIn)); pw.println(" liveOut = " + toString(liveOut)); for (Tac t = tacList; t != null; t = t.next) { pw.println(" " + t + " " + toString(t.liveOut)); } switch (endKind) { case BY_BRANCH: pw.println("END BY BRANCH, goto " + next[0]); break; case BY_BEQZ: pw.println("END BY BEQZ, if " + var.name + " = "); pw.println(" 0 : goto " + next[0] + "; 1 : goto " + next[1]); break; case BY_BNEZ: pw.println("END BY BGTZ, if " + var.name + " = "); pw.println(" 1 : goto " + next[0] + "; 0 : goto " + next[1]); break; case BY_RETURN: if (var != null) { pw.println("END BY RETURN, result = " + var.name); } else { pw.println("END BY RETURN, void result"); } break; } } public String toString(Set<Temp> set) { StringBuilder sb = new StringBuilder("[ "); for (Temp t : set) { sb.append(t.name + " "); } sb.append(']'); return sb.toString(); } public void insertBefore(Tac insert, Tac base) { if (base == tacList) { tacList = insert; } else { base.prev.next = insert; } insert.prev = base.prev; base.prev = insert; insert.next = base; } public void insertAfter(Tac insert, Tac base) { if (tacList == null) { tacList = insert; insert.next = null; return; } if (base.next != null) { base.next.prev = insert; } insert.prev = base; insert.next = base.next; base.next = insert; } public void appendAsm(Asm asm) { asms.add(asm); } public List<Asm> getAsms() { return asms; } }
201440_13
/** * OWL CLASS * * DESCRIPTION: * The Owl class is an object that declares the x- and y-coordinates of * an Owl object and the name of the Owl. * * SOURCES: * */ package Objects; public class Owl { // Public static final members of Owl class: public static final String BOB = "BOB"; // dimensions of image file are 158 x 159 public static final String ALICE = "ALICE"; // dimensions of image file are 158 x 159 public static final String CHLOE = "CHLOE"; // dimensions of image file are 87 x 88 public static final String DAVID = "DAVID"; // dimensions of image file are 106 x 107 // Private members of the Owl class: private int xCoord; // x-coordinate of Owl private int yCoord; // y-coordinate of Owl private String name; // name of Owl /** * DEFAULT CONSTRUCTOR: The constructor calls overloaded constructor * with x- and y-coordinates of 0 and the name BOB. * @param none */ public Owl() { this(0, 0, BOB); // call overridden Owl(int, int, name) } /** * OVERLOADED CONSTRUCTOR: Instantiates an Owl object and initializes the x- * and y-coordinates and name members. * @param xCoord * @param yCoord * @param name */ public Owl(int xCoord, int yCoord, String name) { this.xCoord = xCoord; // initialize xCoord value this.yCoord = yCoord; // initialize yCoord value this.name = name; // initialize name value } /** * SETTER: Sets the xCoord of the Owl. * @param xCoord */ public void setXCoord(int xCoord) { this.xCoord = xCoord; // set xCoord value of Owl } /** * SETTER: Sets the yCoord of the Owl. * @param yCoord */ public void setYCoord(int yCoord) { this.yCoord = yCoord; // set yCoord value of Owl } /** * SETTER: Sets the name of the Owl. * @param name */ public void setOwlName(String name) { this.name = name; // set name value of Owl } /** * GETTER: Returns the xCoord of the Owl. * @return xCoord */ public int getXCoord() { return xCoord; // return xCoord value of Owl } /** * GETTER: Returns the yCoord of the Owl. * @return yCoord */ public int getYCoord() { return yCoord; // return yCoord value of Owl } /** * GETTER: Returns the name of the Owl. * @return name */ public String getOwlName() { return name; // return name value of Owl } }
sethmenghi/boolean-forest
src/Objects/Owl.java
779
// initialize xCoord value
line_comment
nl
/** * OWL CLASS * * DESCRIPTION: * The Owl class is an object that declares the x- and y-coordinates of * an Owl object and the name of the Owl. * * SOURCES: * */ package Objects; public class Owl { // Public static final members of Owl class: public static final String BOB = "BOB"; // dimensions of image file are 158 x 159 public static final String ALICE = "ALICE"; // dimensions of image file are 158 x 159 public static final String CHLOE = "CHLOE"; // dimensions of image file are 87 x 88 public static final String DAVID = "DAVID"; // dimensions of image file are 106 x 107 // Private members of the Owl class: private int xCoord; // x-coordinate of Owl private int yCoord; // y-coordinate of Owl private String name; // name of Owl /** * DEFAULT CONSTRUCTOR: The constructor calls overloaded constructor * with x- and y-coordinates of 0 and the name BOB. * @param none */ public Owl() { this(0, 0, BOB); // call overridden Owl(int, int, name) } /** * OVERLOADED CONSTRUCTOR: Instantiates an Owl object and initializes the x- * and y-coordinates and name members. * @param xCoord * @param yCoord * @param name */ public Owl(int xCoord, int yCoord, String name) { this.xCoord = xCoord; // initialize xCoord<SUF> this.yCoord = yCoord; // initialize yCoord value this.name = name; // initialize name value } /** * SETTER: Sets the xCoord of the Owl. * @param xCoord */ public void setXCoord(int xCoord) { this.xCoord = xCoord; // set xCoord value of Owl } /** * SETTER: Sets the yCoord of the Owl. * @param yCoord */ public void setYCoord(int yCoord) { this.yCoord = yCoord; // set yCoord value of Owl } /** * SETTER: Sets the name of the Owl. * @param name */ public void setOwlName(String name) { this.name = name; // set name value of Owl } /** * GETTER: Returns the xCoord of the Owl. * @return xCoord */ public int getXCoord() { return xCoord; // return xCoord value of Owl } /** * GETTER: Returns the yCoord of the Owl. * @return yCoord */ public int getYCoord() { return yCoord; // return yCoord value of Owl } /** * GETTER: Returns the name of the Owl. * @return name */ public String getOwlName() { return name; // return name value of Owl } }
201440_14
/** * OWL CLASS * * DESCRIPTION: * The Owl class is an object that declares the x- and y-coordinates of * an Owl object and the name of the Owl. * * SOURCES: * */ package Objects; public class Owl { // Public static final members of Owl class: public static final String BOB = "BOB"; // dimensions of image file are 158 x 159 public static final String ALICE = "ALICE"; // dimensions of image file are 158 x 159 public static final String CHLOE = "CHLOE"; // dimensions of image file are 87 x 88 public static final String DAVID = "DAVID"; // dimensions of image file are 106 x 107 // Private members of the Owl class: private int xCoord; // x-coordinate of Owl private int yCoord; // y-coordinate of Owl private String name; // name of Owl /** * DEFAULT CONSTRUCTOR: The constructor calls overloaded constructor * with x- and y-coordinates of 0 and the name BOB. * @param none */ public Owl() { this(0, 0, BOB); // call overridden Owl(int, int, name) } /** * OVERLOADED CONSTRUCTOR: Instantiates an Owl object and initializes the x- * and y-coordinates and name members. * @param xCoord * @param yCoord * @param name */ public Owl(int xCoord, int yCoord, String name) { this.xCoord = xCoord; // initialize xCoord value this.yCoord = yCoord; // initialize yCoord value this.name = name; // initialize name value } /** * SETTER: Sets the xCoord of the Owl. * @param xCoord */ public void setXCoord(int xCoord) { this.xCoord = xCoord; // set xCoord value of Owl } /** * SETTER: Sets the yCoord of the Owl. * @param yCoord */ public void setYCoord(int yCoord) { this.yCoord = yCoord; // set yCoord value of Owl } /** * SETTER: Sets the name of the Owl. * @param name */ public void setOwlName(String name) { this.name = name; // set name value of Owl } /** * GETTER: Returns the xCoord of the Owl. * @return xCoord */ public int getXCoord() { return xCoord; // return xCoord value of Owl } /** * GETTER: Returns the yCoord of the Owl. * @return yCoord */ public int getYCoord() { return yCoord; // return yCoord value of Owl } /** * GETTER: Returns the name of the Owl. * @return name */ public String getOwlName() { return name; // return name value of Owl } }
sethmenghi/boolean-forest
src/Objects/Owl.java
779
// initialize yCoord value
line_comment
nl
/** * OWL CLASS * * DESCRIPTION: * The Owl class is an object that declares the x- and y-coordinates of * an Owl object and the name of the Owl. * * SOURCES: * */ package Objects; public class Owl { // Public static final members of Owl class: public static final String BOB = "BOB"; // dimensions of image file are 158 x 159 public static final String ALICE = "ALICE"; // dimensions of image file are 158 x 159 public static final String CHLOE = "CHLOE"; // dimensions of image file are 87 x 88 public static final String DAVID = "DAVID"; // dimensions of image file are 106 x 107 // Private members of the Owl class: private int xCoord; // x-coordinate of Owl private int yCoord; // y-coordinate of Owl private String name; // name of Owl /** * DEFAULT CONSTRUCTOR: The constructor calls overloaded constructor * with x- and y-coordinates of 0 and the name BOB. * @param none */ public Owl() { this(0, 0, BOB); // call overridden Owl(int, int, name) } /** * OVERLOADED CONSTRUCTOR: Instantiates an Owl object and initializes the x- * and y-coordinates and name members. * @param xCoord * @param yCoord * @param name */ public Owl(int xCoord, int yCoord, String name) { this.xCoord = xCoord; // initialize xCoord value this.yCoord = yCoord; // initialize yCoord<SUF> this.name = name; // initialize name value } /** * SETTER: Sets the xCoord of the Owl. * @param xCoord */ public void setXCoord(int xCoord) { this.xCoord = xCoord; // set xCoord value of Owl } /** * SETTER: Sets the yCoord of the Owl. * @param yCoord */ public void setYCoord(int yCoord) { this.yCoord = yCoord; // set yCoord value of Owl } /** * SETTER: Sets the name of the Owl. * @param name */ public void setOwlName(String name) { this.name = name; // set name value of Owl } /** * GETTER: Returns the xCoord of the Owl. * @return xCoord */ public int getXCoord() { return xCoord; // return xCoord value of Owl } /** * GETTER: Returns the yCoord of the Owl. * @return yCoord */ public int getYCoord() { return yCoord; // return yCoord value of Owl } /** * GETTER: Returns the name of the Owl. * @return name */ public String getOwlName() { return name; // return name value of Owl } }
201457_55
//-------------------------------------------------------------------------- // Copyright (C) 2004,2006 Andrew Ross // Copyright (C) 2004-2014 Alan W. Irwin // // This file is part of PLplot. // // PLplot 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; version 2 of the License. // // PLplot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with PLplot; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA //-------------------------------------------------------------------------- // //-------------------------------------------------------------------------- // Implementation of PLplot example 20 in Java. //-------------------------------------------------------------------------- // // Current user defined command line options are not supported in // the Java bindings // package plplot.examples; import plplot.core.*; import static plplot.core.plplotjavacConstants.*; import java.io.*; import java.util.*; class x20 { // Class data PLStream pls = new PLStream(); static int XDIM = 260; static int YDIM = 220; static boolean dbg = false; static boolean nosombrero = false; static boolean nointeractive = false; static String f_name = null; //static PLOptionTable options[]; // PLOptionTable options[] = { // { // "dbg", /* extra debugging plot */ // NULL, // NULL, // &dbg, // PL_OPT_BOOL, // "-dbg", // "Extra debugging plot" }, // { // "nosombrero", /* Turns on test of xor function */ // NULL, // NULL, // &nosombrero, // PL_OPT_BOOL, // "-nosombrero", // "No sombrero plot" }, // { // "nointeractive", /* Turns on test of xor function */ // NULL, // NULL, // &nointeractive, // PL_OPT_BOOL, // "-nointeractive", // "No interactive selection" }, // { // "save", /* For saving in postscript */ // NULL, // NULL, // &f_name, // PL_OPT_STRING, // "-save filename", // "Save sombrero plot in color postscript `filename'" }, // { // NULL, /* option */ // NULL, /* handler */ // NULL, /* client data */ // NULL, /* address of variable to set */ // 0, /* mode flag */ // NULL, /* short syntax */ // NULL } /* long syntax */ // }; x20( String[] args ) { double x[] = new double[XDIM]; double y[] = new double[YDIM]; double z[][] = new double[XDIM][YDIM]; double r[][]; double xi[] = new double[1]; double yi[] = new double[1]; double xe[] = new double[1]; double ye[] = new double[1]; int i, j, width, height, num_col; int n[] = new int[1]; double img_f[][]; double img_min; double img_max; double maxmin[] = new double[2]; double x0, y0, dy, stretch; double deltax, deltay, xg[][], yg[][]; // plplot initialization // Parse and process command line arguments. //pls.MergeOpts(options, "x20c options", NULL); pls.parseopts( args, PL_PARSE_FULL | PL_PARSE_NOPROGRAM ); // Initialize PLplot. pls.init(); // view image border pixels if ( dbg ) { pls.env( 1., XDIM, 1., YDIM, 1, 1 ); // no plot box // build a one pixel square border, for diagnostics for ( i = 0; i < XDIM; i++ ) z[i][YDIM - 1] = 1.; // right for ( i = 0; i < XDIM; i++ ) z[i][0] = 1.; // left for ( i = 0; i < YDIM; i++ ) z[0][i] = 1.; // top for ( i = 0; i < YDIM; i++ ) z[XDIM - 1][i] = 1.; // botton pls.lab( "...around a blue square.", " ", "A red border should appear..." ); pls.image( z, 1., XDIM, 1., YDIM, 0., 0., 1., XDIM, 1., YDIM ); } // sombrero-like demo if ( !nosombrero ) { r = new double[XDIM][YDIM]; pls.col0( 2 ); // draw a yellow plot box, useful for diagnostics! :( pls.env( 0., 2. * Math.PI, 0, 3. * Math.PI, 1, -1 ); for ( i = 0; i < XDIM; i++ ) x[i] = i * 2. * Math.PI / ( XDIM - 1 ); for ( i = 0; i < YDIM; i++ ) y[i] = i * 3. * Math.PI / ( YDIM - 1 ); for ( i = 0; i < XDIM; i++ ) for ( j = 0; j < YDIM; j++ ) { r[i][j] = Math.sqrt( x[i] * x[i] + y[j] * y[j] ) + 1e-3; z[i][j] = Math.sin( r[i][j] ) / ( r[i][j] ); } pls.lab( "No, an amplitude clipped \"sombrero\"", "", "Saturn?" ); pls.ptex( 2., 2., 3., 4., 0., "Transparent image" ); pls.image( z, 0., 2. * Math.PI, 0., 3. * Math.PI, 0.05, 1., 0., 2. * Math.PI, 0., 3. * Math.PI ); // save the plot if ( f_name != null ) save_plot( f_name ); } // read Chloe image if ( ( img_f = read_img( "Chloe.pgm", n ) ) == null ) { if ( ( img_f = read_img( "../Chloe.pgm", n ) ) == null ) { System.out.println( "File error - aborting" ); pls.end(); System.exit( 1 ); } } num_col = n[0]; width = img_f.length; height = img_f[0].length; // set gray colormap gray_cmap( num_col ); // display Chloe pls.env( 1., width, 1., height, 1, -1 ); if ( !nointeractive ) pls.lab( "Set and drag Button 1 to (re)set selection, Button 2 to finish.", " ", "Chloe..." ); else pls.lab( "", " ", "Chloe..." ); pls.image( img_f, 1., width, 1., height, 0., 0., 1., width, 1., height ); // selection/expansion demo if ( !nointeractive ) { xi[0] = 25.; xe[0] = 130.; yi[0] = 235.; ye[0] = 125.; if ( get_clip( xi, xe, yi, ye ) ) // get selection rectangle { pls.end(); System.exit( 0 ); } // // I'm unable to continue, clearing the plot and advancing to the next // one, without hiting the enter key, or pressing the button... help! // // Forcing the xwin driver to leave locate mode and destroying the // xhairs (in GetCursorCmd()) solves some problems, but I still have // to press the enter key or press Button-2 to go to next plot, even // if a pladv() is not present! Using plbop() solves the problem, but // it shouldn't be needed! // // pls.bop(); // // spause(false), adv(0), spause(true), also works, // but the above question remains. // With this approach, the previous pause state is lost, // as there is no API call to get its current state. // pls.spause( false ); pls.adv( 0 ); // display selection only pls.image( img_f, 1., width, 1., height, 0., 0., xi[0], xe[0], ye[0], yi[0] ); pls.spause( true ); // zoom in selection pls.env( xi[0], xe[0], ye[0], yi[0], 1, -1 ); pls.image( img_f, 1., width, 1., height, 0., 0., xi[0], xe[0], ye[0], yi[0] ); } // Base the dynamic range on the image contents. f2mnmx( img_f, width, height, maxmin ); img_max = maxmin[0]; img_min = maxmin[1]; // For java we use 2-d arrays to replace the pltr function // even for the NULL case. xg = new double[width + 1][height + 1]; yg = new double[width + 1][height + 1]; // In order to mimic the NULL case, the following must be true. // xg[i] = i*deltax; yg[j] = j*deltay, where deltax = (double) width / (double) ( width - 1 ); deltay = (double) height / (double) ( height - 1 ); for ( i = 0; i <= width; i++ ) { for ( j = 0; j <= height; j++ ) { xg[i][j] = i * deltax; yg[i][j] = j * deltay; } } // Draw a saturated version of the original image. Only use // the middle 50% of the image's full dynamic range. pls.col0( 2 ); pls.env( 0, width, 0, height, 1, -1 ); pls.lab( "", "", "Reduced dynamic range image example" ); pls.imagefr( img_f, 0., width, 0., height, 0., 0., img_min + img_max * 0.25, img_max - img_max * 0.25, xg, yg ); // Draw a distorted version of the original image, showing its full dynamic range. pls.env( 0, width, 0, height, 1, -1 ); pls.lab( "", "", "Distorted image example" ); x0 = 0.5 * width; y0 = 0.5 * height; dy = 0.5 * height; stretch = 0.5; // In C / C++ the following would work, with plimagefr directly calling // mypltr. For compatibilty with other language bindings the same effect // can be achieved by generating the transformed grid first and then // using pltr2. // plimagefr(img_f, width, height, 0., width, 0., height, 0., 0., img_min, img_max, mypltr, (PLPointer) &stretch); for ( i = 0; i <= width; i++ ) { for ( j = 0; j <= height; j++ ) { xg[i][j] = x0 + ( x0 - i ) * ( 1.0 - stretch * Math.cos( ( j - y0 ) / dy * Math.PI * 0.5 ) ); yg[i][j] = j; } } pls.imagefr( img_f, 0., width, 0., height, 0., 0., img_min, img_max, xg, yg ); pls.end(); } // read image from file in binary ppm format double [][] read_img( String fname, int [] num_col ) { BufferedReader in; DataInputStream in2; double[][] img; String line; StringTokenizer st; int i, j, w, h; // naive grayscale binary ppm reading. If you know how to, improve it try { in = new BufferedReader( new FileReader( fname ) ); in2 = new DataInputStream( new DataInputStream( new BufferedInputStream( new FileInputStream( fname ) ) ) ); } catch ( FileNotFoundException e ) { System.out.println( "File " + fname + " not found" ); return null; } try { line = in.readLine(); if ( line.compareTo( "P5\n" ) == 0 ) // I only understand this! { System.out.println( line ); System.out.println( "unknown file format " + fname ); return null; } in2.skip( line.getBytes().length + 1 ); do { line = in.readLine(); in2.skip( line.getBytes().length + 1 ); } while ( line.charAt( 0 ) == '#' ); st = new StringTokenizer( line ); w = Integer.parseInt( st.nextToken() ); h = Integer.parseInt( st.nextToken() ); line = in.readLine(); in2.skip( line.getBytes().length + 1 ); st = new StringTokenizer( line ); num_col[0] = Integer.parseInt( st.nextToken() ); img = new double[w][h]; for ( j = 0; j < h; j++ ) { for ( i = 0; i < w; i++ ) { img[i][h - j - 1] = in2.readUnsignedByte(); } } } catch ( IOException e ) { System.out.println( "Error reading " + fname ); return null; } return img; } // save plot void save_plot( String fname ) { PLStream pls2 = new PLStream(); // create a new one pls2.sdev( "psc" ); // new device type. Use a known existing driver pls2.sfnam( fname ); // file name pls2.cpstrm( pls, false ); // copy old stream parameters to new stream pls2.replot(); // do the save } // get selection square interactively boolean get_clip( double[] xi, double[] xe, double[] yi, double[] ye ) { PLGraphicsIn gin = new PLGraphicsIn(); double xxi = xi[0], yyi = yi[0], xxe = xe[0], yye = ye[0], t; boolean start = false; boolean[] st = new boolean[1]; pls.xormod( true, st ); // enter xor mode to draw a selection rectangle if ( st[0] ) // driver has xormod capability, continue { double sx[] = new double[5]; double sy[] = new double[5]; while ( true ) { pls.xormod( false, st ); pls.getCursor( gin ); pls.xormod( true, st ); if ( gin.getButton() == 1 ) { xxi = gin.getWX(); yyi = gin.getWY(); if ( start ) pls.line( sx, sy ); // clear previous rectangle start = false; sx[0] = xxi; sy[0] = yyi; sx[4] = xxi; sy[4] = yyi; } if ( ( gin.getState() & 0x100 ) != 0 ) { xxe = gin.getWX(); yye = gin.getWY(); if ( start ) pls.line( sx, sy ); // clear previous rectangle start = true; sx[2] = xxe; sy[2] = yye; sx[1] = xxe; sy[1] = yyi; sx[3] = xxi; sy[3] = yye; pls.line( sx, sy ); // draw new rectangle } if ( gin.getButton() == 3 || gin.getKeysym() == 0x0D || gin.getKeysym() == 'Q' ) { if ( start ) pls.line( sx, sy ); // clear previous rectangle break; } } pls.xormod( false, st ); // leave xor mod if ( xxe < xxi ) { t = xxi; xxi = xxe; xxe = t; } if ( yyi < yye ) { t = yyi; yyi = yye; yye = t; } xe[0] = xxe; xi[0] = xxi; ye[0] = yye; yi[0] = yyi; return ( gin.getKeysym() == 'Q' ); } return false; } // set gray colormap void gray_cmap( int num_col ) { double r[] = new double[2]; double g[] = new double[2]; double b[] = new double[2]; double pos[] = new double[2]; r[0] = g[0] = b[0] = 0.0; r[1] = g[1] = b[1] = 1.0; pos[0] = 0.0; pos[1] = 1.0; pls.scmap1n( num_col ); pls.scmap1l( true, pos, r, g, b ); } // Calculate the minimum and maximum of a 2-d array void f2mnmx( double [][] f, int nx, int ny, double[] fmaxmin ) { int i, j; fmaxmin[0] = f[0][0]; fmaxmin[1] = fmaxmin[0]; for ( i = 0; i < nx; i++ ) { for ( j = 0; j < ny; j++ ) { fmaxmin[0] = Math.max( fmaxmin[0], f[i][j] ); fmaxmin[1] = Math.min( fmaxmin[1], f[i][j] ); } } } public static void main( String[] args ) { new x20( args ); } } //-------------------------------------------------------------------------- // End of x20.cc //--------------------------------------------------------------------------
PLplot/PLplot
examples/java/x20.java
4,920
// zoom in selection
line_comment
nl
//-------------------------------------------------------------------------- // Copyright (C) 2004,2006 Andrew Ross // Copyright (C) 2004-2014 Alan W. Irwin // // This file is part of PLplot. // // PLplot 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; version 2 of the License. // // PLplot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with PLplot; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA //-------------------------------------------------------------------------- // //-------------------------------------------------------------------------- // Implementation of PLplot example 20 in Java. //-------------------------------------------------------------------------- // // Current user defined command line options are not supported in // the Java bindings // package plplot.examples; import plplot.core.*; import static plplot.core.plplotjavacConstants.*; import java.io.*; import java.util.*; class x20 { // Class data PLStream pls = new PLStream(); static int XDIM = 260; static int YDIM = 220; static boolean dbg = false; static boolean nosombrero = false; static boolean nointeractive = false; static String f_name = null; //static PLOptionTable options[]; // PLOptionTable options[] = { // { // "dbg", /* extra debugging plot */ // NULL, // NULL, // &dbg, // PL_OPT_BOOL, // "-dbg", // "Extra debugging plot" }, // { // "nosombrero", /* Turns on test of xor function */ // NULL, // NULL, // &nosombrero, // PL_OPT_BOOL, // "-nosombrero", // "No sombrero plot" }, // { // "nointeractive", /* Turns on test of xor function */ // NULL, // NULL, // &nointeractive, // PL_OPT_BOOL, // "-nointeractive", // "No interactive selection" }, // { // "save", /* For saving in postscript */ // NULL, // NULL, // &f_name, // PL_OPT_STRING, // "-save filename", // "Save sombrero plot in color postscript `filename'" }, // { // NULL, /* option */ // NULL, /* handler */ // NULL, /* client data */ // NULL, /* address of variable to set */ // 0, /* mode flag */ // NULL, /* short syntax */ // NULL } /* long syntax */ // }; x20( String[] args ) { double x[] = new double[XDIM]; double y[] = new double[YDIM]; double z[][] = new double[XDIM][YDIM]; double r[][]; double xi[] = new double[1]; double yi[] = new double[1]; double xe[] = new double[1]; double ye[] = new double[1]; int i, j, width, height, num_col; int n[] = new int[1]; double img_f[][]; double img_min; double img_max; double maxmin[] = new double[2]; double x0, y0, dy, stretch; double deltax, deltay, xg[][], yg[][]; // plplot initialization // Parse and process command line arguments. //pls.MergeOpts(options, "x20c options", NULL); pls.parseopts( args, PL_PARSE_FULL | PL_PARSE_NOPROGRAM ); // Initialize PLplot. pls.init(); // view image border pixels if ( dbg ) { pls.env( 1., XDIM, 1., YDIM, 1, 1 ); // no plot box // build a one pixel square border, for diagnostics for ( i = 0; i < XDIM; i++ ) z[i][YDIM - 1] = 1.; // right for ( i = 0; i < XDIM; i++ ) z[i][0] = 1.; // left for ( i = 0; i < YDIM; i++ ) z[0][i] = 1.; // top for ( i = 0; i < YDIM; i++ ) z[XDIM - 1][i] = 1.; // botton pls.lab( "...around a blue square.", " ", "A red border should appear..." ); pls.image( z, 1., XDIM, 1., YDIM, 0., 0., 1., XDIM, 1., YDIM ); } // sombrero-like demo if ( !nosombrero ) { r = new double[XDIM][YDIM]; pls.col0( 2 ); // draw a yellow plot box, useful for diagnostics! :( pls.env( 0., 2. * Math.PI, 0, 3. * Math.PI, 1, -1 ); for ( i = 0; i < XDIM; i++ ) x[i] = i * 2. * Math.PI / ( XDIM - 1 ); for ( i = 0; i < YDIM; i++ ) y[i] = i * 3. * Math.PI / ( YDIM - 1 ); for ( i = 0; i < XDIM; i++ ) for ( j = 0; j < YDIM; j++ ) { r[i][j] = Math.sqrt( x[i] * x[i] + y[j] * y[j] ) + 1e-3; z[i][j] = Math.sin( r[i][j] ) / ( r[i][j] ); } pls.lab( "No, an amplitude clipped \"sombrero\"", "", "Saturn?" ); pls.ptex( 2., 2., 3., 4., 0., "Transparent image" ); pls.image( z, 0., 2. * Math.PI, 0., 3. * Math.PI, 0.05, 1., 0., 2. * Math.PI, 0., 3. * Math.PI ); // save the plot if ( f_name != null ) save_plot( f_name ); } // read Chloe image if ( ( img_f = read_img( "Chloe.pgm", n ) ) == null ) { if ( ( img_f = read_img( "../Chloe.pgm", n ) ) == null ) { System.out.println( "File error - aborting" ); pls.end(); System.exit( 1 ); } } num_col = n[0]; width = img_f.length; height = img_f[0].length; // set gray colormap gray_cmap( num_col ); // display Chloe pls.env( 1., width, 1., height, 1, -1 ); if ( !nointeractive ) pls.lab( "Set and drag Button 1 to (re)set selection, Button 2 to finish.", " ", "Chloe..." ); else pls.lab( "", " ", "Chloe..." ); pls.image( img_f, 1., width, 1., height, 0., 0., 1., width, 1., height ); // selection/expansion demo if ( !nointeractive ) { xi[0] = 25.; xe[0] = 130.; yi[0] = 235.; ye[0] = 125.; if ( get_clip( xi, xe, yi, ye ) ) // get selection rectangle { pls.end(); System.exit( 0 ); } // // I'm unable to continue, clearing the plot and advancing to the next // one, without hiting the enter key, or pressing the button... help! // // Forcing the xwin driver to leave locate mode and destroying the // xhairs (in GetCursorCmd()) solves some problems, but I still have // to press the enter key or press Button-2 to go to next plot, even // if a pladv() is not present! Using plbop() solves the problem, but // it shouldn't be needed! // // pls.bop(); // // spause(false), adv(0), spause(true), also works, // but the above question remains. // With this approach, the previous pause state is lost, // as there is no API call to get its current state. // pls.spause( false ); pls.adv( 0 ); // display selection only pls.image( img_f, 1., width, 1., height, 0., 0., xi[0], xe[0], ye[0], yi[0] ); pls.spause( true ); // zoom in<SUF> pls.env( xi[0], xe[0], ye[0], yi[0], 1, -1 ); pls.image( img_f, 1., width, 1., height, 0., 0., xi[0], xe[0], ye[0], yi[0] ); } // Base the dynamic range on the image contents. f2mnmx( img_f, width, height, maxmin ); img_max = maxmin[0]; img_min = maxmin[1]; // For java we use 2-d arrays to replace the pltr function // even for the NULL case. xg = new double[width + 1][height + 1]; yg = new double[width + 1][height + 1]; // In order to mimic the NULL case, the following must be true. // xg[i] = i*deltax; yg[j] = j*deltay, where deltax = (double) width / (double) ( width - 1 ); deltay = (double) height / (double) ( height - 1 ); for ( i = 0; i <= width; i++ ) { for ( j = 0; j <= height; j++ ) { xg[i][j] = i * deltax; yg[i][j] = j * deltay; } } // Draw a saturated version of the original image. Only use // the middle 50% of the image's full dynamic range. pls.col0( 2 ); pls.env( 0, width, 0, height, 1, -1 ); pls.lab( "", "", "Reduced dynamic range image example" ); pls.imagefr( img_f, 0., width, 0., height, 0., 0., img_min + img_max * 0.25, img_max - img_max * 0.25, xg, yg ); // Draw a distorted version of the original image, showing its full dynamic range. pls.env( 0, width, 0, height, 1, -1 ); pls.lab( "", "", "Distorted image example" ); x0 = 0.5 * width; y0 = 0.5 * height; dy = 0.5 * height; stretch = 0.5; // In C / C++ the following would work, with plimagefr directly calling // mypltr. For compatibilty with other language bindings the same effect // can be achieved by generating the transformed grid first and then // using pltr2. // plimagefr(img_f, width, height, 0., width, 0., height, 0., 0., img_min, img_max, mypltr, (PLPointer) &stretch); for ( i = 0; i <= width; i++ ) { for ( j = 0; j <= height; j++ ) { xg[i][j] = x0 + ( x0 - i ) * ( 1.0 - stretch * Math.cos( ( j - y0 ) / dy * Math.PI * 0.5 ) ); yg[i][j] = j; } } pls.imagefr( img_f, 0., width, 0., height, 0., 0., img_min, img_max, xg, yg ); pls.end(); } // read image from file in binary ppm format double [][] read_img( String fname, int [] num_col ) { BufferedReader in; DataInputStream in2; double[][] img; String line; StringTokenizer st; int i, j, w, h; // naive grayscale binary ppm reading. If you know how to, improve it try { in = new BufferedReader( new FileReader( fname ) ); in2 = new DataInputStream( new DataInputStream( new BufferedInputStream( new FileInputStream( fname ) ) ) ); } catch ( FileNotFoundException e ) { System.out.println( "File " + fname + " not found" ); return null; } try { line = in.readLine(); if ( line.compareTo( "P5\n" ) == 0 ) // I only understand this! { System.out.println( line ); System.out.println( "unknown file format " + fname ); return null; } in2.skip( line.getBytes().length + 1 ); do { line = in.readLine(); in2.skip( line.getBytes().length + 1 ); } while ( line.charAt( 0 ) == '#' ); st = new StringTokenizer( line ); w = Integer.parseInt( st.nextToken() ); h = Integer.parseInt( st.nextToken() ); line = in.readLine(); in2.skip( line.getBytes().length + 1 ); st = new StringTokenizer( line ); num_col[0] = Integer.parseInt( st.nextToken() ); img = new double[w][h]; for ( j = 0; j < h; j++ ) { for ( i = 0; i < w; i++ ) { img[i][h - j - 1] = in2.readUnsignedByte(); } } } catch ( IOException e ) { System.out.println( "Error reading " + fname ); return null; } return img; } // save plot void save_plot( String fname ) { PLStream pls2 = new PLStream(); // create a new one pls2.sdev( "psc" ); // new device type. Use a known existing driver pls2.sfnam( fname ); // file name pls2.cpstrm( pls, false ); // copy old stream parameters to new stream pls2.replot(); // do the save } // get selection square interactively boolean get_clip( double[] xi, double[] xe, double[] yi, double[] ye ) { PLGraphicsIn gin = new PLGraphicsIn(); double xxi = xi[0], yyi = yi[0], xxe = xe[0], yye = ye[0], t; boolean start = false; boolean[] st = new boolean[1]; pls.xormod( true, st ); // enter xor mode to draw a selection rectangle if ( st[0] ) // driver has xormod capability, continue { double sx[] = new double[5]; double sy[] = new double[5]; while ( true ) { pls.xormod( false, st ); pls.getCursor( gin ); pls.xormod( true, st ); if ( gin.getButton() == 1 ) { xxi = gin.getWX(); yyi = gin.getWY(); if ( start ) pls.line( sx, sy ); // clear previous rectangle start = false; sx[0] = xxi; sy[0] = yyi; sx[4] = xxi; sy[4] = yyi; } if ( ( gin.getState() & 0x100 ) != 0 ) { xxe = gin.getWX(); yye = gin.getWY(); if ( start ) pls.line( sx, sy ); // clear previous rectangle start = true; sx[2] = xxe; sy[2] = yye; sx[1] = xxe; sy[1] = yyi; sx[3] = xxi; sy[3] = yye; pls.line( sx, sy ); // draw new rectangle } if ( gin.getButton() == 3 || gin.getKeysym() == 0x0D || gin.getKeysym() == 'Q' ) { if ( start ) pls.line( sx, sy ); // clear previous rectangle break; } } pls.xormod( false, st ); // leave xor mod if ( xxe < xxi ) { t = xxi; xxi = xxe; xxe = t; } if ( yyi < yye ) { t = yyi; yyi = yye; yye = t; } xe[0] = xxe; xi[0] = xxi; ye[0] = yye; yi[0] = yyi; return ( gin.getKeysym() == 'Q' ); } return false; } // set gray colormap void gray_cmap( int num_col ) { double r[] = new double[2]; double g[] = new double[2]; double b[] = new double[2]; double pos[] = new double[2]; r[0] = g[0] = b[0] = 0.0; r[1] = g[1] = b[1] = 1.0; pos[0] = 0.0; pos[1] = 1.0; pls.scmap1n( num_col ); pls.scmap1l( true, pos, r, g, b ); } // Calculate the minimum and maximum of a 2-d array void f2mnmx( double [][] f, int nx, int ny, double[] fmaxmin ) { int i, j; fmaxmin[0] = f[0][0]; fmaxmin[1] = fmaxmin[0]; for ( i = 0; i < nx; i++ ) { for ( j = 0; j < ny; j++ ) { fmaxmin[0] = Math.max( fmaxmin[0], f[i][j] ); fmaxmin[1] = Math.min( fmaxmin[1], f[i][j] ); } } } public static void main( String[] args ) { new x20( args ); } } //-------------------------------------------------------------------------- // End of x20.cc //--------------------------------------------------------------------------
201647_7
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import Utility.Book; import Utility.Patron; import Utility.Librery; import java.util.Scanner; public class App { public static void main(String[] args) { //book title,authors and isbn10 in the form of array String [] book_title = { "The Hunger Games" , "Harry Potter and the Philosopher's Stone" , "Twilight" , "To Kill a Mockingbird" , "The Great Gatsby" , "The Fault in Our Stars" , "The Hobbit or There and Back Again" , "The Catcher in the Rye" , "Angels & Demons " , "Pride and Prejudice" , "The Kite Runner " , "Divergent" , "Nineteen Eighty-Four" , "Animal Farm: A Fairy Story" , "Het Achterhuis: Dagboekbrieven 14 juni 1942 - 1 augustus 1944" , "Män som hatar kvinnor" , "Catching Fire" , "Harry Potter and the Prisoner of Azkaban" , " The Fellowship of the Ring" , "Mockingjay" }; String [] authors = { "Suzanne Collins" , "J.K. Rowling, Mary GrandPré" , "Stephenie Meyer" , "Harper Lee" , "F. Scott Fitzgerald" , "John Green" , "J.R.R. Tolkien" , "J.D. Salinger" , "Dan Brown" , "Jane Austen" , "Khaled Hosseini" , "Veronica Roth" , "George Orwell, Erich Fromm, Celâl Üster" , "George Orwell" , "Anne Frank, Eleanor Roosevelt, B.M. Mooyaart-Doubleday" , "Stieg Larsson, Reg Keeland" , "Suzanne Collins" , "J.K. Rowling, Mary GrandPré, Rufus Beck" , "J.R.R. Tolkien" , "Suzanne Collins" }; String [] isbn10 = { "439023483" , "439554934" , "316015849" , "61120081" , "743273567" , "525478817" , "618260307" , "316769177" , "1416524797" , "679783261" , "1594480001" , "62024035" , "451524934" , "452284244" , "553296981" , "307269752" , "439023491" , "043965548X" , "618346252" , "439023513" }; //lists to Book object LinkedList<Book> bookDetails = new LinkedList<Book>(); for(int i=0;i < book_title.length;i++){ Book book = new Book(); book.setTitle( book_title[i]); book.setAuthor(authors[i]); book.setIsbn( isbn10[i]); bookDetails.add(book); } //adding Books to librery Librery librery = new Librery(); for(int i =0; i < bookDetails.size();i++){ librery.addBook(bookDetails.get(i));} System.out.println(" Welcome to RK LIBRERY \n Explore the world of books, knowledge, and imagination!"); Scanner selector = new Scanner(System.in); String flag = "run"; while (!(flag.equals("exit"))){ System.out.println("\n \nAre you librerian[L] or reader[R] or want exit[exit]?"); String selection = selector.nextLine(); flag = selection; if(selection.equals("R")){ /*reader code */ System.out.println("Are you a member of this librery? [Y] or [N]"); String isMember = selector.nextLine(); if(isMember.equals("N")){ System.out.println("Take membership for this librery ."); /*new membership code */ Patron newPatron = new Patron(); System.out.println("Enter Your name :"); String new_name = selector.nextLine(); newPatron.setName(new_name); int new_id = librery.patronList.size() + 1; newPatron.setId(new_id); librery.AddPatron(newPatron); System.out.println("\nCongrats " + newPatron.getName() + "\nyou are a member of librery! you can lend books"); System.out.println("\nNote this id card for future use"); System.out.println(" RK LIBRERY \nName :" + new_name + "\nId : " + newPatron.getId()); }else if(isMember.equals("Y")){ /*check membership */ System.out.println("Give Your name and id"); String name_string = selector.nextLine(); int id_number = selector.nextInt(); if(id_number <= librery.patronList.size()){ //verified patron code int verified_id = librery.checkPatron(name_string,id_number); if(verified_id > 0){ Patron verified = librery.patronList.get(verified_id - 1); System.out.println("\nYou are verified!\n"); System.out.println("Select option \n 1 : for lending book\n 2 : for return book"); int memberAction = selector.nextInt(); if(memberAction == 1){ //book lending System.out.println("\nSelect the book:"); librery.showBookShelf(); int selected_book_id = selector.nextInt(); selector.nextLine(); if(selected_book_id <= librery.bookShelf.size()){ Book selected_book = librery.bookShelf.get(selected_book_id - 1); System.out.println("\n \nYou picked the book!"); selected_book.display(); librery.lendBook(selected_book,verified); verified.borrowBook(selected_book); System.out.println("\nThe book " + selected_book.getTitle() + " is lended to " + verified.getName()); System.out.println("Happy reading!"); }else{ System.out.println("Enter a valied Number ");} }else if(memberAction == 2){ //book return code System.out.println("\n \nWhich book you want to return?"); int count = 1; for(Book book:verified.borrowedBooks){ System.out.println(count + " : for " +book.getTitle()); count++; } int returnBookIndex = selector.nextInt(); selector.nextLine(); Book returningBook = verified.borrowedBooks.get(returnBookIndex - 1); verified.returnBook(returningBook); librery.acceptBook(returningBook); System.out.println("The book "+ returningBook.getTitle() + " is accepted from " + verified.getName() ); System.out.println("I hope you enjoyed the book!"); } }else{ System.out.println("Enter valied Information or get menbership"); } } } }else if (selection.equals("L")){ //librerian code System.out.println("Select options: \n 1 : Add book \n 2 : View Bookshelf"); String LibrerianChoice = selector.nextLine(); if(LibrerianChoice.equals("1")){ //add book code System.out.println("Book title :"); String new_title = selector.nextLine(); System.out.println("Author :"); String new_author = selector.nextLine(); System.out.println("Isbn10 :"); String new_isbn = selector.nextLine(); Book new_book = new Book(); new_book.setTitle(new_title); new_book.setAuthor(new_author); new_book.setIsbn(new_isbn); librery.addBook(new_book); System.out.println(new_book.getTitle() + "is added succusfully"); }else if(LibrerianChoice.equals("2")){ librery.showBookShelf(); } } }//while loop ends here selector.close(); } }
ravibalebilalu/librery_management
App.java
2,126
//while loop ends here
line_comment
nl
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import Utility.Book; import Utility.Patron; import Utility.Librery; import java.util.Scanner; public class App { public static void main(String[] args) { //book title,authors and isbn10 in the form of array String [] book_title = { "The Hunger Games" , "Harry Potter and the Philosopher's Stone" , "Twilight" , "To Kill a Mockingbird" , "The Great Gatsby" , "The Fault in Our Stars" , "The Hobbit or There and Back Again" , "The Catcher in the Rye" , "Angels & Demons " , "Pride and Prejudice" , "The Kite Runner " , "Divergent" , "Nineteen Eighty-Four" , "Animal Farm: A Fairy Story" , "Het Achterhuis: Dagboekbrieven 14 juni 1942 - 1 augustus 1944" , "Män som hatar kvinnor" , "Catching Fire" , "Harry Potter and the Prisoner of Azkaban" , " The Fellowship of the Ring" , "Mockingjay" }; String [] authors = { "Suzanne Collins" , "J.K. Rowling, Mary GrandPré" , "Stephenie Meyer" , "Harper Lee" , "F. Scott Fitzgerald" , "John Green" , "J.R.R. Tolkien" , "J.D. Salinger" , "Dan Brown" , "Jane Austen" , "Khaled Hosseini" , "Veronica Roth" , "George Orwell, Erich Fromm, Celâl Üster" , "George Orwell" , "Anne Frank, Eleanor Roosevelt, B.M. Mooyaart-Doubleday" , "Stieg Larsson, Reg Keeland" , "Suzanne Collins" , "J.K. Rowling, Mary GrandPré, Rufus Beck" , "J.R.R. Tolkien" , "Suzanne Collins" }; String [] isbn10 = { "439023483" , "439554934" , "316015849" , "61120081" , "743273567" , "525478817" , "618260307" , "316769177" , "1416524797" , "679783261" , "1594480001" , "62024035" , "451524934" , "452284244" , "553296981" , "307269752" , "439023491" , "043965548X" , "618346252" , "439023513" }; //lists to Book object LinkedList<Book> bookDetails = new LinkedList<Book>(); for(int i=0;i < book_title.length;i++){ Book book = new Book(); book.setTitle( book_title[i]); book.setAuthor(authors[i]); book.setIsbn( isbn10[i]); bookDetails.add(book); } //adding Books to librery Librery librery = new Librery(); for(int i =0; i < bookDetails.size();i++){ librery.addBook(bookDetails.get(i));} System.out.println(" Welcome to RK LIBRERY \n Explore the world of books, knowledge, and imagination!"); Scanner selector = new Scanner(System.in); String flag = "run"; while (!(flag.equals("exit"))){ System.out.println("\n \nAre you librerian[L] or reader[R] or want exit[exit]?"); String selection = selector.nextLine(); flag = selection; if(selection.equals("R")){ /*reader code */ System.out.println("Are you a member of this librery? [Y] or [N]"); String isMember = selector.nextLine(); if(isMember.equals("N")){ System.out.println("Take membership for this librery ."); /*new membership code */ Patron newPatron = new Patron(); System.out.println("Enter Your name :"); String new_name = selector.nextLine(); newPatron.setName(new_name); int new_id = librery.patronList.size() + 1; newPatron.setId(new_id); librery.AddPatron(newPatron); System.out.println("\nCongrats " + newPatron.getName() + "\nyou are a member of librery! you can lend books"); System.out.println("\nNote this id card for future use"); System.out.println(" RK LIBRERY \nName :" + new_name + "\nId : " + newPatron.getId()); }else if(isMember.equals("Y")){ /*check membership */ System.out.println("Give Your name and id"); String name_string = selector.nextLine(); int id_number = selector.nextInt(); if(id_number <= librery.patronList.size()){ //verified patron code int verified_id = librery.checkPatron(name_string,id_number); if(verified_id > 0){ Patron verified = librery.patronList.get(verified_id - 1); System.out.println("\nYou are verified!\n"); System.out.println("Select option \n 1 : for lending book\n 2 : for return book"); int memberAction = selector.nextInt(); if(memberAction == 1){ //book lending System.out.println("\nSelect the book:"); librery.showBookShelf(); int selected_book_id = selector.nextInt(); selector.nextLine(); if(selected_book_id <= librery.bookShelf.size()){ Book selected_book = librery.bookShelf.get(selected_book_id - 1); System.out.println("\n \nYou picked the book!"); selected_book.display(); librery.lendBook(selected_book,verified); verified.borrowBook(selected_book); System.out.println("\nThe book " + selected_book.getTitle() + " is lended to " + verified.getName()); System.out.println("Happy reading!"); }else{ System.out.println("Enter a valied Number ");} }else if(memberAction == 2){ //book return code System.out.println("\n \nWhich book you want to return?"); int count = 1; for(Book book:verified.borrowedBooks){ System.out.println(count + " : for " +book.getTitle()); count++; } int returnBookIndex = selector.nextInt(); selector.nextLine(); Book returningBook = verified.borrowedBooks.get(returnBookIndex - 1); verified.returnBook(returningBook); librery.acceptBook(returningBook); System.out.println("The book "+ returningBook.getTitle() + " is accepted from " + verified.getName() ); System.out.println("I hope you enjoyed the book!"); } }else{ System.out.println("Enter valied Information or get menbership"); } } } }else if (selection.equals("L")){ //librerian code System.out.println("Select options: \n 1 : Add book \n 2 : View Bookshelf"); String LibrerianChoice = selector.nextLine(); if(LibrerianChoice.equals("1")){ //add book code System.out.println("Book title :"); String new_title = selector.nextLine(); System.out.println("Author :"); String new_author = selector.nextLine(); System.out.println("Isbn10 :"); String new_isbn = selector.nextLine(); Book new_book = new Book(); new_book.setTitle(new_title); new_book.setAuthor(new_author); new_book.setIsbn(new_isbn); librery.addBook(new_book); System.out.println(new_book.getTitle() + "is added succusfully"); }else if(LibrerianChoice.equals("2")){ librery.showBookShelf(); } } }//while loop<SUF> selector.close(); } }
201663_30
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2017-Present 8x8, 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 org.jitsi.jicofo.jibri; import edu.umd.cs.findbugs.annotations.*; import org.jetbrains.annotations.Nullable; import org.jitsi.jicofo.*; import org.jitsi.jicofo.xmpp.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import org.jetbrains.annotations.*; import org.jitsi.utils.logging2.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import java.util.concurrent.*; import static org.apache.commons.lang3.StringUtils.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas * * This is not meant to be `public`, but has to be exposed because of compatibility with kotlin (JibriStats.kt takes * a parameter type that exposes JibriSession and it can not be restricted to java's "package private"). */ public class JibriSession { /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(Status status) { return Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. * TODO: Fix the inconsistent synchronization */ @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for events from the {@link JibriDetector}. */ private final JibriDetectorEventHandler jibriEventHandler = new JibriDetectorEventHandler(); /** * Current Jibri recording status. */ private Status jibriStatus = Status.UNDEFINED; private final Logger logger; /** * The listener which will be notified about status changes of this session. */ private final StateListener stateListener; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link AbstractXMPPConnection} instance used to send/listen for XMPP packets. */ private final AbstractXMPPConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private final Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; @NotNull private final JibriStats stats = JibriStats.getGlobalStats(); /** * Creates new {@link JibriSession} instance. * @param stateListener the listener to be notified about this session state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( StateListener stateListener, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, AbstractXMPPConnection connection, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.stateListener = stateListener; this.roomName = roomName; this.initiator = initiator; this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; jibriDetector.addHandler(jibriEventHandler); logger = new LoggerImpl(getClass().getName(), logLevelDelegate.getLevel()); } /** * Used internally to call * {@link StateListener#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged(Status newStatus, FailureReason failureReason) { if (failureReason != null) { stats.sessionFailed(getJibriType()); } stateListener.onSessionStateChanged(this, newStatus, failureReason); } /** * @return The {@link Type} of this session. */ public Type getJibriType() { if (isSIP) { return Type.SIP_CALL; } else if (isBlank(streamID)) { return Type.RECORDING; } else { return Type.LIVE_STREAMING; } } /** * @return {@code true} if this sessions is active or {@code false} * otherwise. */ public boolean isActive() { return Status.ON.equals(jibriStatus); } /** * @return {@code true} if this session is pending or {@code false} * otherwise. */ public boolean isPending() { return Status.UNDEFINED.equals(jibriStatus) || Status.PENDING.equals(jibriStatus); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { stats.sessionFailed(getJibriType()); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException.AllBusy(); } throw new StartException.NotAvailable(); } try { logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); if (!(e instanceof StartException.OneBusy)) { jibriDetector.memberHadTransientError(jibriJid); } if (!maxRetriesExceeded()) { retryRequestWithAnotherJibri(); } else { throw new StartException.InternalServerError(); } } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(Action.STOP); stopRequest.setSessionId(this.sessionId); logger.info("Trying to stop: " + stopRequest.toXML()); // When we send stop, we won't get an OFF presence back (just // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> logger.error( "Error sending stop iq: " + exception.toString()), 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; jibriDetector.removeHandler(jibriEventHandler); } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status Status status = iq.getStatus(); if (!Status.UNDEFINED.equals(status)) { logger.info("Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate(iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error("Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. */ private void sendJibriStartIq(final Jid jibriJid) throws SmackException.NotConnectedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = UtilKt.sendIqAndGetResponse(xmpp, startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException.UnexpectedResponse(); } JibriIq jibriIq = (JibriIq) reply; if (isBusyResponse(jibriIq)) { logger.info("Jibri " + jibriIq.getFrom() + " was busy"); throw new StartException.OneBusy(); } if (!isPendingResponse(jibriIq)) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException.UnexpectedResponse(); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will clear recording state after a timeout of * {@link JibriConfig#getPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = TaskPools.getScheduledPool().schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info("Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info("Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.warn("Failed to fall back to another Jibri, this session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Task scheduled after we have received RESULT response from Jibri and entered PENDING state. Will abort the * recording if we do not transit to ON state, after a timeout of {@link JibriConfig#getPendingTimeout()}. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface StateListener { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, Status newStatus, FailureReason failureReason); } static public abstract class StartException extends Exception { public StartException(String message) { super(message); } static public class AllBusy extends StartException { public AllBusy() { super("All jibri instances are busy"); } } static public class InternalServerError extends StartException { public InternalServerError() { super("Internal server error"); } } static public class NotAvailable extends StartException { public NotAvailable() { super("No Jibris available"); } } static public class UnexpectedResponse extends StartException { public UnexpectedResponse() { super("Unexpected response"); } } static public class OneBusy extends StartException { public OneBusy() { super("This Jibri instance was busy"); } } } /** * A Jibri session type. */ public enum Type { /** * SIP Jibri call. */ SIP_CALL, /** * Jibri live streaming session. */ LIVE_STREAMING, /** * Jibri recording session. */ RECORDING } private class JibriDetectorEventHandler implements JibriDetector.EventHandler { @Override public void instanceOffline(Jid jid) { if (jid.equals(currentJibriJid)) { logger.warn(nickname() + " went offline: " + jid + " for room: " + roomName); handleJibriStatusUpdate( jid, Status.OFF, FailureReason.ERROR, true); } } } /** * Returns true if the given IQ represens a busy response from Jibri */ private boolean isBusyResponse(JibriIq iq) { return Status.OFF.equals(iq.getStatus()) && iq.isFailure() && FailureReason.BUSY.equals(iq.getFailureReason()); } private boolean isPendingResponse(JibriIq iq) { return Status.PENDING.equals(iq.getStatus()); } }
saal-core/blync-jicofo
src/main/java/org/jitsi/jicofo/jibri/JibriSession.java
7,131
// When we send stop, we won't get an OFF presence back (just
line_comment
nl
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2017-Present 8x8, 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 org.jitsi.jicofo.jibri; import edu.umd.cs.findbugs.annotations.*; import org.jetbrains.annotations.Nullable; import org.jitsi.jicofo.*; import org.jitsi.jicofo.xmpp.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import org.jetbrains.annotations.*; import org.jitsi.utils.logging2.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import java.util.concurrent.*; import static org.apache.commons.lang3.StringUtils.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas * * This is not meant to be `public`, but has to be exposed because of compatibility with kotlin (JibriStats.kt takes * a parameter type that exposes JibriSession and it can not be restricted to java's "package private"). */ public class JibriSession { /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(Status status) { return Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. * TODO: Fix the inconsistent synchronization */ @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for events from the {@link JibriDetector}. */ private final JibriDetectorEventHandler jibriEventHandler = new JibriDetectorEventHandler(); /** * Current Jibri recording status. */ private Status jibriStatus = Status.UNDEFINED; private final Logger logger; /** * The listener which will be notified about status changes of this session. */ private final StateListener stateListener; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link AbstractXMPPConnection} instance used to send/listen for XMPP packets. */ private final AbstractXMPPConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private final Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; @NotNull private final JibriStats stats = JibriStats.getGlobalStats(); /** * Creates new {@link JibriSession} instance. * @param stateListener the listener to be notified about this session state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( StateListener stateListener, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, AbstractXMPPConnection connection, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.stateListener = stateListener; this.roomName = roomName; this.initiator = initiator; this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; jibriDetector.addHandler(jibriEventHandler); logger = new LoggerImpl(getClass().getName(), logLevelDelegate.getLevel()); } /** * Used internally to call * {@link StateListener#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged(Status newStatus, FailureReason failureReason) { if (failureReason != null) { stats.sessionFailed(getJibriType()); } stateListener.onSessionStateChanged(this, newStatus, failureReason); } /** * @return The {@link Type} of this session. */ public Type getJibriType() { if (isSIP) { return Type.SIP_CALL; } else if (isBlank(streamID)) { return Type.RECORDING; } else { return Type.LIVE_STREAMING; } } /** * @return {@code true} if this sessions is active or {@code false} * otherwise. */ public boolean isActive() { return Status.ON.equals(jibriStatus); } /** * @return {@code true} if this session is pending or {@code false} * otherwise. */ public boolean isPending() { return Status.UNDEFINED.equals(jibriStatus) || Status.PENDING.equals(jibriStatus); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { stats.sessionFailed(getJibriType()); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException.AllBusy(); } throw new StartException.NotAvailable(); } try { logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); if (!(e instanceof StartException.OneBusy)) { jibriDetector.memberHadTransientError(jibriJid); } if (!maxRetriesExceeded()) { retryRequestWithAnotherJibri(); } else { throw new StartException.InternalServerError(); } } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(Action.STOP); stopRequest.setSessionId(this.sessionId); logger.info("Trying to stop: " + stopRequest.toXML()); // When we<SUF> // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> logger.error( "Error sending stop iq: " + exception.toString()), 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; jibriDetector.removeHandler(jibriEventHandler); } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status Status status = iq.getStatus(); if (!Status.UNDEFINED.equals(status)) { logger.info("Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate(iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error("Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. */ private void sendJibriStartIq(final Jid jibriJid) throws SmackException.NotConnectedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = UtilKt.sendIqAndGetResponse(xmpp, startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException.UnexpectedResponse(); } JibriIq jibriIq = (JibriIq) reply; if (isBusyResponse(jibriIq)) { logger.info("Jibri " + jibriIq.getFrom() + " was busy"); throw new StartException.OneBusy(); } if (!isPendingResponse(jibriIq)) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException.UnexpectedResponse(); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will clear recording state after a timeout of * {@link JibriConfig#getPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = TaskPools.getScheduledPool().schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info("Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info("Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.warn("Failed to fall back to another Jibri, this session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Task scheduled after we have received RESULT response from Jibri and entered PENDING state. Will abort the * recording if we do not transit to ON state, after a timeout of {@link JibriConfig#getPendingTimeout()}. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface StateListener { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, Status newStatus, FailureReason failureReason); } static public abstract class StartException extends Exception { public StartException(String message) { super(message); } static public class AllBusy extends StartException { public AllBusy() { super("All jibri instances are busy"); } } static public class InternalServerError extends StartException { public InternalServerError() { super("Internal server error"); } } static public class NotAvailable extends StartException { public NotAvailable() { super("No Jibris available"); } } static public class UnexpectedResponse extends StartException { public UnexpectedResponse() { super("Unexpected response"); } } static public class OneBusy extends StartException { public OneBusy() { super("This Jibri instance was busy"); } } } /** * A Jibri session type. */ public enum Type { /** * SIP Jibri call. */ SIP_CALL, /** * Jibri live streaming session. */ LIVE_STREAMING, /** * Jibri recording session. */ RECORDING } private class JibriDetectorEventHandler implements JibriDetector.EventHandler { @Override public void instanceOffline(Jid jid) { if (jid.equals(currentJibriJid)) { logger.warn(nickname() + " went offline: " + jid + " for room: " + roomName); handleJibriStatusUpdate( jid, Status.OFF, FailureReason.ERROR, true); } } } /** * Returns true if the given IQ represens a busy response from Jibri */ private boolean isBusyResponse(JibriIq iq) { return Status.OFF.equals(iq.getStatus()) && iq.isFailure() && FailureReason.BUSY.equals(iq.getFailureReason()); } private boolean isPendingResponse(JibriIq iq) { return Status.PENDING.equals(iq.getStatus()); } }
201670_32
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty 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 org.jitsi.jicofo.recording.jibri; import org.jitsi.jicofo.util.*; import org.jitsi.utils.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import org.osgi.framework.*; import java.util.*; import java.util.concurrent.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); /** * Provides the {@link EventAdmin} instance for emitting events. */ private final EventAdminProvider eventAdminProvider; /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; /** * Creates new {@link JibriSession} instance. * @param bundleContext the OSGI context. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( BundleContext bundleContext, JibriSession.Owner owner, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.eventAdminProvider = new EventAdminProvider(bundleContext); this.owner = owner; this.roomName = roomName; this.initiator = initiator; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Used internally to call * {@link Owner#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged( Status newStatus, FailureReason failureReason) { if (failureReason != null) { emitSessionFailedEvent(); } owner.onSessionStateChanged(this, newStatus, failureReason); } /** * Asynchronously emits {@link JibriSessionEvent#FAILED_TO_START} event over * the {@link EventAdmin} bus. */ private void emitSessionFailedEvent() { JibriSessionEvent.Type jibriType; if (isSIP) { jibriType = JibriSessionEvent.Type.SIP_CALL; } else if (StringUtils.isNullOrEmpty(streamID)) { jibriType = JibriSessionEvent.Type.RECORDING; } else { jibriType = JibriSessionEvent.Type.LIVE_STREAMING; } eventAdminProvider .get() .postEvent( JibriSessionEvent.newFailedToStartEvent(jibriType)); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { emitSessionFailedEvent(); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException(StartException.ALL_BUSY); } throw new StartException(StartException.NOT_AVAILABLE); } try { jibriEventHandler.start(FocusBundleActivator.bundleContext); logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); throw new StartException(StartException.INTERNAL_SERVER_ERROR); } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); logger.info("Trying to stop: " + stopRequest.toXML()); // When we send stop, we won't get an OFF presence back (just // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> { logger.error( "Error sending stop iq: " + exception.toString()); }, 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @param request * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) * @param iq */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate( iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error( "Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. * @throws OperationFailedException if XMPP connection failed * @throws StartException if something went wrong */ private void sendJibriStartIq(final Jid jibriJid) throws OperationFailedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = xmpp.sendPacketAndGetReply(startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException(StartException.UNEXPECTED_RESPONSE); } JibriIq jibriIq = (JibriIq) reply; // According to the "protocol" only PENDING status is allowed in // response to the start request. if (!Status.PENDING.equals(jibriIq.getStatus())) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException(StartException.UNEXPECTED_RESPONSE); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info( "Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry " + "wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info( "Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.info( "Failed to fall back to another Jibri, this " + "session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we " + "should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate( jibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } static public class StartException extends Exception { final static String ALL_BUSY = "All Jibri instances are busy"; final static String INTERNAL_SERVER_ERROR = "Internal server error"; final static String NOT_AVAILABLE = "No Jibris available"; final static String UNEXPECTED_RESPONSE = "Unexpected response"; private final String reason; StartException(String reason) { super(reason); this.reason = reason; } String getReason() { return reason; } } }
Neustradamus/jicofo
src/main/java/org/jitsi/jicofo/recording/jibri/JibriSession.java
7,291
// When we send stop, we won't get an OFF presence back (just
line_comment
nl
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty 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 org.jitsi.jicofo.recording.jibri; import org.jitsi.jicofo.util.*; import org.jitsi.utils.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import org.osgi.framework.*; import java.util.*; import java.util.concurrent.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); /** * Provides the {@link EventAdmin} instance for emitting events. */ private final EventAdminProvider eventAdminProvider; /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; /** * Creates new {@link JibriSession} instance. * @param bundleContext the OSGI context. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( BundleContext bundleContext, JibriSession.Owner owner, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.eventAdminProvider = new EventAdminProvider(bundleContext); this.owner = owner; this.roomName = roomName; this.initiator = initiator; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Used internally to call * {@link Owner#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged( Status newStatus, FailureReason failureReason) { if (failureReason != null) { emitSessionFailedEvent(); } owner.onSessionStateChanged(this, newStatus, failureReason); } /** * Asynchronously emits {@link JibriSessionEvent#FAILED_TO_START} event over * the {@link EventAdmin} bus. */ private void emitSessionFailedEvent() { JibriSessionEvent.Type jibriType; if (isSIP) { jibriType = JibriSessionEvent.Type.SIP_CALL; } else if (StringUtils.isNullOrEmpty(streamID)) { jibriType = JibriSessionEvent.Type.RECORDING; } else { jibriType = JibriSessionEvent.Type.LIVE_STREAMING; } eventAdminProvider .get() .postEvent( JibriSessionEvent.newFailedToStartEvent(jibriType)); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { emitSessionFailedEvent(); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException(StartException.ALL_BUSY); } throw new StartException(StartException.NOT_AVAILABLE); } try { jibriEventHandler.start(FocusBundleActivator.bundleContext); logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); throw new StartException(StartException.INTERNAL_SERVER_ERROR); } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); logger.info("Trying to stop: " + stopRequest.toXML()); // When we<SUF> // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> { logger.error( "Error sending stop iq: " + exception.toString()); }, 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @param request * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) * @param iq */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate( iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error( "Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. * @throws OperationFailedException if XMPP connection failed * @throws StartException if something went wrong */ private void sendJibriStartIq(final Jid jibriJid) throws OperationFailedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = xmpp.sendPacketAndGetReply(startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException(StartException.UNEXPECTED_RESPONSE); } JibriIq jibriIq = (JibriIq) reply; // According to the "protocol" only PENDING status is allowed in // response to the start request. if (!Status.PENDING.equals(jibriIq.getStatus())) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException(StartException.UNEXPECTED_RESPONSE); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info( "Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry " + "wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info( "Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.info( "Failed to fall back to another Jibri, this " + "session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we " + "should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate( jibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } static public class StartException extends Exception { final static String ALL_BUSY = "All Jibri instances are busy"; final static String INTERNAL_SERVER_ERROR = "Internal server error"; final static String NOT_AVAILABLE = "No Jibris available"; final static String UNEXPECTED_RESPONSE = "Unexpected response"; private final String reason; StartException(String reason) { super(reason); this.reason = reason; } String getReason() { return reason; } } }
201671_1
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Examens, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Onderwijsovereenkomst, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ BPVOvereenkomst, /** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */ Overig; /** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
topicusonderwijs/tribe-krd-quarkus
src/main/java/nl/topicus/eduarte/model/entities/rapportage/DocumentTemplateCategorie.java
752
/** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */
block_comment
nl
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde<SUF>*/ Examens, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Onderwijsovereenkomst, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ BPVOvereenkomst, /** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */ Overig; /** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
201671_2
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Examens, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Onderwijsovereenkomst, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ BPVOvereenkomst, /** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */ Overig; /** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
topicusonderwijs/tribe-krd-quarkus
src/main/java/nl/topicus/eduarte/model/entities/rapportage/DocumentTemplateCategorie.java
752
/** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */
block_comment
nl
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Examens, /** * Een enum waarde<SUF>*/ Onderwijsovereenkomst, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ BPVOvereenkomst, /** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */ Overig; /** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
201671_3
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Examens, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Onderwijsovereenkomst, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ BPVOvereenkomst, /** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */ Overig; /** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
topicusonderwijs/tribe-krd-quarkus
src/main/java/nl/topicus/eduarte/model/entities/rapportage/DocumentTemplateCategorie.java
752
/** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */
block_comment
nl
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Examens, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Onderwijsovereenkomst, /** * Een enum waarde<SUF>*/ BPVOvereenkomst, /** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */ Overig; /** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
201671_4
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Examens, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Onderwijsovereenkomst, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ BPVOvereenkomst, /** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */ Overig; /** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
topicusonderwijs/tribe-krd-quarkus
src/main/java/nl/topicus/eduarte/model/entities/rapportage/DocumentTemplateCategorie.java
752
/** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */
block_comment
nl
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Examens, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Onderwijsovereenkomst, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ BPVOvereenkomst, /** * Een enum waarde<SUF>*/ Overig; /** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
201671_5
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Examens, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Onderwijsovereenkomst, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ BPVOvereenkomst, /** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */ Overig; /** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
topicusonderwijs/tribe-krd-quarkus
src/main/java/nl/topicus/eduarte/model/entities/rapportage/DocumentTemplateCategorie.java
752
/** * Alternatief voor values(), dit geeft niet de * {@link DocumentTemplateCategorie#Examens} en * {@link DocumentTemplateCategorie#Onderwijsovereenkomst} en * {@link DocumentTemplateCategorie#BPVOvereenkomst} waarde mee. */
block_comment
nl
/* * Copyright 2022 Topicus Onderwijs Eduarte B.V.. * * 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 * * https://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 nl.topicus.eduarte.model.entities.rapportage; import java.util.ArrayList; import java.util.List; public enum DocumentTemplateCategorie { Intake, Identiteit, Verbintenis, Brieven, Resultaten { @Override public DocumentTemplateContext getBeperkteContext() { return DocumentTemplateContext.Verbintenis; } }, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Examens, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ Onderwijsovereenkomst, /** * Een enum waarde welke alleen bestemd is voor de * {@link OnderwijsDocumentTemplate}. Omdat we niet kunnen erven van een Enum * moeten het maar zo. */ BPVOvereenkomst, /** * Een enum waarde welke alleen bestemd is voor templates in andere modules. * Omdat we niet kunnen erven van een Enum moet het maar zo. */ Overig; /** * Alternatief voor values(),<SUF>*/ public static DocumentTemplateCategorie[] getValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Intake); values.add(DocumentTemplateCategorie.Identiteit); values.add(DocumentTemplateCategorie.Verbintenis); values.add(DocumentTemplateCategorie.Brieven); values.add(DocumentTemplateCategorie.Resultaten); values.add(DocumentTemplateCategorie.Overig); return values.toArray(new DocumentTemplateCategorie[0]); } public static DocumentTemplateCategorie[] getExamenValues() { List<DocumentTemplateCategorie> values = new ArrayList<>(); values.add(DocumentTemplateCategorie.Examens); values.add(DocumentTemplateCategorie.Onderwijsovereenkomst); values.add(DocumentTemplateCategorie.BPVOvereenkomst); return values.toArray(new DocumentTemplateCategorie[0]); } public DocumentTemplateContext getBeperkteContext() { return null; } }
201672_26
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty 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 org.jitsi.jicofo.recording.jibri; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import java.util.*; import java.util.concurrent.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * Creates new {@link JibriSession} instance. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( JibriSession.Owner owner, EntityBareJid roomName, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.owner = owner; this.roomName = roomName; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @return true if the start is successful, false otherwise */ synchronized public boolean start() { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid != null) { try { jibriEventHandler.start(FocusBundleActivator.bundleContext); sendJibriStartIq(jibriJid); logger.info("Starting session with Jibri " + jibriJid); return true; } catch (Exception e) { logger.error("Failed to start Jibri event handler: " + e, e); } } else { logger.error("Unable to find an available Jibri, can't start"); } return false; } /** * Stops this session if it's not already stopped. */ synchronized public void stop() { if (currentJibriJid == null) { return; } JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); logger.info("Trying to stop: " + stopRequest.toXML()); // When we send stop, we won't get an OFF presence back (just // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { JibriIq resp = (JibriIq)stanza; handleJibriStatusUpdate(resp.getFrom(), resp.getStatus(), resp.getFailureReason()); }, exception -> { logger.error("Error sending stop iq: " + exception.toString()); }, 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } IQ processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate(iq.getFrom(), status, iq.getFailureReason()); } else { logger.error("Received UNDEFINED status from jibri: " + iq.toString()); } return IQ.createResultIQ(iq); } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. */ private void sendJibriStartIq(final Jid jibriJid) { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug("Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); try { JibriIq result = (JibriIq)xmpp.sendPacketAndGetReply(startIq); handleJibriStatusUpdate(result.getFrom(), result.getStatus(), result.getFailureReason()); } catch (OperationFailedException e) { logger.error("Error sending Jibri start IQ: " + e.toString()); } } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we should retry again, false otherwise */ private boolean shouldRetryRequest() { return (maxNumRetries < 0 || numRetries < maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @return true if we were able to find another Jibri to retry the request with, * false otherwise */ private boolean retryRequestWithAnotherJibri() { numRetries++; return start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully (or there was an error but we * have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's new state), make sure we stop // the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info("Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another Jibri to keep things going if (failureReason != null) { // There was an error with the current Jibri, see if we should retry if (shouldRetryRequest()) { logger.info("Jibri failed, trying to fall back to another Jibri"); if (retryRequestWithAnotherJibri()) { // The fallback to another Jibri succeeded. logger.info("Successfully resumed session with another Jibri"); } else { logger.info("Failed to fall back to another Jibri, this session has now failed"); // Propagate up that the session has failed entirely. We'll pass the original failure reason. owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } } else { // The Jibri we tried failed and we've reached the maxmium amount of retries we've been // configured to attempt, so we'll give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and cleaning up session"); // The Jibri stopped for some non-error reason owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); // The Jibri stopped for some non-error reason owner.onSessionStateChanged(this, newStatus, failureReason); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate(jibriJid, Status.OFF, FailureReason.ERROR); } } } } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's likely hung or having // some issue. We'll send a stop (so if/when it does 'recover', it knows to // stop) and simulate an error status (like we do in JibriEventHandler#handleEvent // when a Jibri goes offline) to trigger the fallback logic. stop(); handleJibriStatusUpdate(currentJibriJid, Status.OFF, FailureReason.ERROR); } } } } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } }
pfisher/jicofo
src/main/java/org/jitsi/jicofo/recording/jibri/JibriSession.java
5,793
// When we send stop, we won't get an OFF presence back (just
line_comment
nl
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty 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 org.jitsi.jicofo.recording.jibri; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import java.util.*; import java.util.concurrent.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * Creates new {@link JibriSession} instance. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( JibriSession.Owner owner, EntityBareJid roomName, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.owner = owner; this.roomName = roomName; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @return true if the start is successful, false otherwise */ synchronized public boolean start() { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid != null) { try { jibriEventHandler.start(FocusBundleActivator.bundleContext); sendJibriStartIq(jibriJid); logger.info("Starting session with Jibri " + jibriJid); return true; } catch (Exception e) { logger.error("Failed to start Jibri event handler: " + e, e); } } else { logger.error("Unable to find an available Jibri, can't start"); } return false; } /** * Stops this session if it's not already stopped. */ synchronized public void stop() { if (currentJibriJid == null) { return; } JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); logger.info("Trying to stop: " + stopRequest.toXML()); // When we<SUF> // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { JibriIq resp = (JibriIq)stanza; handleJibriStatusUpdate(resp.getFrom(), resp.getStatus(), resp.getFailureReason()); }, exception -> { logger.error("Error sending stop iq: " + exception.toString()); }, 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } IQ processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate(iq.getFrom(), status, iq.getFailureReason()); } else { logger.error("Received UNDEFINED status from jibri: " + iq.toString()); } return IQ.createResultIQ(iq); } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. */ private void sendJibriStartIq(final Jid jibriJid) { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug("Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); try { JibriIq result = (JibriIq)xmpp.sendPacketAndGetReply(startIq); handleJibriStatusUpdate(result.getFrom(), result.getStatus(), result.getFailureReason()); } catch (OperationFailedException e) { logger.error("Error sending Jibri start IQ: " + e.toString()); } } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we should retry again, false otherwise */ private boolean shouldRetryRequest() { return (maxNumRetries < 0 || numRetries < maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @return true if we were able to find another Jibri to retry the request with, * false otherwise */ private boolean retryRequestWithAnotherJibri() { numRetries++; return start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully (or there was an error but we * have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's new state), make sure we stop // the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info("Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another Jibri to keep things going if (failureReason != null) { // There was an error with the current Jibri, see if we should retry if (shouldRetryRequest()) { logger.info("Jibri failed, trying to fall back to another Jibri"); if (retryRequestWithAnotherJibri()) { // The fallback to another Jibri succeeded. logger.info("Successfully resumed session with another Jibri"); } else { logger.info("Failed to fall back to another Jibri, this session has now failed"); // Propagate up that the session has failed entirely. We'll pass the original failure reason. owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } } else { // The Jibri we tried failed and we've reached the maxmium amount of retries we've been // configured to attempt, so we'll give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and cleaning up session"); // The Jibri stopped for some non-error reason owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); // The Jibri stopped for some non-error reason owner.onSessionStateChanged(this, newStatus, failureReason); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate(jibriJid, Status.OFF, FailureReason.ERROR); } } } } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's likely hung or having // some issue. We'll send a stop (so if/when it does 'recover', it knows to // stop) and simulate an error status (like we do in JibriEventHandler#handleEvent // when a Jibri goes offline) to trigger the fallback logic. stop(); handleJibriStatusUpdate(currentJibriJid, Status.OFF, FailureReason.ERROR); } } } } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } }
201694_35
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty 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 org.jitsi.jicofo.recording.jibri; import org.jitsi.jicofo.util.*; import org.jitsi.utils.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import org.osgi.framework.*; import java.util.*; import java.util.concurrent.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); /** * Provides the {@link EventAdmin} instance for emitting events. */ private final EventAdminProvider eventAdminProvider; /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; /** * Creates new {@link JibriSession} instance. * @param bundleContext the OSGI context. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( BundleContext bundleContext, JibriSession.Owner owner, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.eventAdminProvider = new EventAdminProvider(bundleContext); this.owner = owner; this.roomName = roomName; this.initiator = initiator; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Used internally to call * {@link Owner#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged( Status newStatus, FailureReason failureReason) { if (failureReason != null) { emitSessionFailedEvent(); } owner.onSessionStateChanged(this, newStatus, failureReason); } /** * Asynchronously emits {@link JibriSessionEvent#FAILED_TO_START} event over * the {@link EventAdmin} bus. */ private void emitSessionFailedEvent() { eventAdminProvider .get() .postEvent( JibriSessionEvent.newFailedToStartEvent( getJibriType())); } /** * @return The {@link JibriSessionEvent.Type} of this session. */ public JibriSessionEvent.Type getJibriType() { if (isSIP) { return JibriSessionEvent.Type.SIP_CALL; } else if (StringUtils.isNullOrEmpty(streamID)) { return JibriSessionEvent.Type.RECORDING; } else { return JibriSessionEvent.Type.LIVE_STREAMING; } } /** * @return {@code true} if this sessions is active or {@code false} * otherwise. */ public boolean isActive() { return Status.ON.equals(jibriStatus); } /** * @return {@code true} if this session is pending or {@code false} * otherwise. */ public boolean isPending() { return Status.UNDEFINED.equals(jibriStatus) || Status.PENDING.equals(jibriStatus); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { emitSessionFailedEvent(); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException(StartException.ALL_BUSY); } throw new StartException(StartException.NOT_AVAILABLE); } try { jibriEventHandler.start(FocusBundleActivator.bundleContext); logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); throw new StartException(StartException.INTERNAL_SERVER_ERROR); } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); logger.info("Trying to stop: " + stopRequest.toXML()); // When we send stop, we won't get an OFF presence back (just // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> { logger.error( "Error sending stop iq: " + exception.toString()); }, 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @param request * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) * @param iq */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate( iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error( "Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. * @throws OperationFailedException if XMPP connection failed * @throws StartException if something went wrong */ private void sendJibriStartIq(final Jid jibriJid) throws OperationFailedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = xmpp.sendPacketAndGetReply(startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException(StartException.UNEXPECTED_RESPONSE); } JibriIq jibriIq = (JibriIq) reply; // According to the "protocol" only PENDING status is allowed in // response to the start request. if (!Status.PENDING.equals(jibriIq.getStatus())) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException(StartException.UNEXPECTED_RESPONSE); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info( "Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry " + "wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info( "Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.info( "Failed to fall back to another Jibri, this " + "session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we " + "should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate( jibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } static public class StartException extends Exception { final static String ALL_BUSY = "All Jibri instances are busy"; final static String INTERNAL_SERVER_ERROR = "Internal server error"; final static String NOT_AVAILABLE = "No Jibris available"; final static String UNEXPECTED_RESPONSE = "Unexpected response"; private final String reason; StartException(String reason) { super(reason); this.reason = reason; } String getReason() { return reason; } } }
obfusk/jicofo
src/main/java/org/jitsi/jicofo/recording/jibri/JibriSession.java
7,444
// When we send stop, we won't get an OFF presence back (just
line_comment
nl
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty 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 org.jitsi.jicofo.recording.jibri; import org.jitsi.jicofo.util.*; import org.jitsi.utils.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import org.osgi.framework.*; import java.util.*; import java.util.concurrent.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); /** * Provides the {@link EventAdmin} instance for emitting events. */ private final EventAdminProvider eventAdminProvider; /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; /** * Creates new {@link JibriSession} instance. * @param bundleContext the OSGI context. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( BundleContext bundleContext, JibriSession.Owner owner, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.eventAdminProvider = new EventAdminProvider(bundleContext); this.owner = owner; this.roomName = roomName; this.initiator = initiator; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Used internally to call * {@link Owner#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged( Status newStatus, FailureReason failureReason) { if (failureReason != null) { emitSessionFailedEvent(); } owner.onSessionStateChanged(this, newStatus, failureReason); } /** * Asynchronously emits {@link JibriSessionEvent#FAILED_TO_START} event over * the {@link EventAdmin} bus. */ private void emitSessionFailedEvent() { eventAdminProvider .get() .postEvent( JibriSessionEvent.newFailedToStartEvent( getJibriType())); } /** * @return The {@link JibriSessionEvent.Type} of this session. */ public JibriSessionEvent.Type getJibriType() { if (isSIP) { return JibriSessionEvent.Type.SIP_CALL; } else if (StringUtils.isNullOrEmpty(streamID)) { return JibriSessionEvent.Type.RECORDING; } else { return JibriSessionEvent.Type.LIVE_STREAMING; } } /** * @return {@code true} if this sessions is active or {@code false} * otherwise. */ public boolean isActive() { return Status.ON.equals(jibriStatus); } /** * @return {@code true} if this session is pending or {@code false} * otherwise. */ public boolean isPending() { return Status.UNDEFINED.equals(jibriStatus) || Status.PENDING.equals(jibriStatus); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { emitSessionFailedEvent(); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException(StartException.ALL_BUSY); } throw new StartException(StartException.NOT_AVAILABLE); } try { jibriEventHandler.start(FocusBundleActivator.bundleContext); logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); throw new StartException(StartException.INTERNAL_SERVER_ERROR); } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); logger.info("Trying to stop: " + stopRequest.toXML()); // When we<SUF> // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> { logger.error( "Error sending stop iq: " + exception.toString()); }, 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @param request * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) * @param iq */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate( iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error( "Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. * @throws OperationFailedException if XMPP connection failed * @throws StartException if something went wrong */ private void sendJibriStartIq(final Jid jibriJid) throws OperationFailedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = xmpp.sendPacketAndGetReply(startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException(StartException.UNEXPECTED_RESPONSE); } JibriIq jibriIq = (JibriIq) reply; // According to the "protocol" only PENDING status is allowed in // response to the start request. if (!Status.PENDING.equals(jibriIq.getStatus())) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException(StartException.UNEXPECTED_RESPONSE); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info( "Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry " + "wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info( "Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.info( "Failed to fall back to another Jibri, this " + "session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we " + "should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate( jibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } static public class StartException extends Exception { final static String ALL_BUSY = "All Jibri instances are busy"; final static String INTERNAL_SERVER_ERROR = "Internal server error"; final static String NOT_AVAILABLE = "No Jibris available"; final static String UNEXPECTED_RESPONSE = "Unexpected response"; private final String reason; StartException(String reason) { super(reason); this.reason = reason; } String getReason() { return reason; } } }
201712_33
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty 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 org.jitsi.jicofo.recording.jibri; import org.jitsi.jicofo.jibri.*; import org.jitsi.jicofo.util.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.json.simple.*; import org.jxmpp.jid.*; import org.osgi.framework.*; import java.util.*; import java.util.concurrent.*; import static org.apache.commons.lang3.StringUtils.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); private static JibriStats stats = new JibriStats(); public static JSONObject getGlobalStats() { return stats.toJson(); } /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private final Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; /** * Creates new {@link JibriSession} instance. * @param bundleContext the OSGI context. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( JibriSession.Owner owner, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.owner = owner; this.roomName = roomName; this.initiator = initiator; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Used internally to call * {@link Owner#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged(Status newStatus, FailureReason failureReason) { if (failureReason != null) { stats.sessionFailed(getJibriType()); } owner.onSessionStateChanged(this, newStatus, failureReason); } /** * @return The {@link JibriSession.Type} of this session. */ public Type getJibriType() { if (isSIP) { return Type.SIP_CALL; } else if (isBlank(streamID)) { return Type.RECORDING; } else { return Type.LIVE_STREAMING; } } /** * @return {@code true} if this sessions is active or {@code false} * otherwise. */ public boolean isActive() { return Status.ON.equals(jibriStatus); } /** * @return {@code true} if this session is pending or {@code false} * otherwise. */ public boolean isPending() { return Status.UNDEFINED.equals(jibriStatus) || Status.PENDING.equals(jibriStatus); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { stats.sessionFailed(getJibriType()); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException(StartException.ALL_BUSY); } throw new StartException(StartException.NOT_AVAILABLE); } try { jibriEventHandler.start(FocusBundleActivator.bundleContext); logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); jibriDetector.memberHadTransientError(jibriJid); if (!maxRetriesExceeded()) { retryRequestWithAnotherJibri(); } else { throw new StartException(StartException.INTERNAL_SERVER_ERROR); } } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); stopRequest.setSessionId(this.sessionId); logger.info("Trying to stop: " + stopRequest.toXML()); // When we send stop, we won't get an OFF presence back (just // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> logger.error( "Error sending stop iq: " + exception.toString()), 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @param request * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) * @param iq */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate( iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error( "Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. * @throws OperationFailedException if XMPP connection failed * @throws StartException if something went wrong */ private void sendJibriStartIq(final Jid jibriJid) throws OperationFailedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = xmpp.sendPacketAndGetReply(startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException(StartException.UNEXPECTED_RESPONSE); } JibriIq jibriIq = (JibriIq) reply; // According to the "protocol" only PENDING status is allowed in // response to the start request. if (!Status.PENDING.equals(jibriIq.getStatus())) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException(StartException.UNEXPECTED_RESPONSE); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will clear recording state after a timeout of * {@link JibriConfig#getPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info( "Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry " + "wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info( "Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.info( "Failed to fall back to another Jibri, this " + "session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we " + "should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate( jibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * Task scheduled after we have received RESULT response from Jibri and entered PENDING state. Will abort the * recording if we do not transit to ON state, after a timeout of {@link JibriConfig#getPendingTimeout()}. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } static public class StartException extends Exception { final static String ALL_BUSY = "All Jibri instances are busy"; final static String INTERNAL_SERVER_ERROR = "Internal server error"; final static String NOT_AVAILABLE = "No Jibris available"; final static String UNEXPECTED_RESPONSE = "Unexpected response"; private final String reason; StartException(String reason) { super(reason); this.reason = reason; } String getReason() { return reason; } } /** * A Jibri session type. */ public enum Type { /** * SIP Jibri call. */ SIP_CALL, /** * Jibri live streaming session. */ LIVE_STREAMING, /** * Jibri recording session. */ RECORDING } }
isabella232/jicofo
src/main/java/org/jitsi/jicofo/recording/jibri/JibriSession.java
7,466
// When we send stop, we won't get an OFF presence back (just
line_comment
nl
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty 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 org.jitsi.jicofo.recording.jibri; import org.jitsi.jicofo.jibri.*; import org.jitsi.jicofo.util.*; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.json.simple.*; import org.jxmpp.jid.*; import org.osgi.framework.*; import java.util.*; import java.util.concurrent.*; import static org.apache.commons.lang3.StringUtils.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); private static JibriStats stats = new JibriStats(); public static JSONObject getGlobalStats() { return stats.toJson(); } /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * The full JID of the entity that has initiated the recording flow. */ private final Jid initiator; /** * The full JID of the entity that has initiated the stop of the recording. */ private Jid terminator; /** * Creates new {@link JibriSession} instance. * @param bundleContext the OSGI context. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( JibriSession.Owner owner, EntityBareJid roomName, Jid initiator, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.owner = owner; this.roomName = roomName; this.initiator = initiator; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Used internally to call * {@link Owner#onSessionStateChanged(JibriSession, Status, FailureReason)}. * @param newStatus the new status to dispatch. * @param failureReason the failure reason associated with the state * transition if any. */ private void dispatchSessionStateChanged(Status newStatus, FailureReason failureReason) { if (failureReason != null) { stats.sessionFailed(getJibriType()); } owner.onSessionStateChanged(this, newStatus, failureReason); } /** * @return The {@link JibriSession.Type} of this session. */ public Type getJibriType() { if (isSIP) { return Type.SIP_CALL; } else if (isBlank(streamID)) { return Type.RECORDING; } else { return Type.LIVE_STREAMING; } } /** * @return {@code true} if this sessions is active or {@code false} * otherwise. */ public boolean isActive() { return Status.ON.equals(jibriStatus); } /** * @return {@code true} if this session is pending or {@code false} * otherwise. */ public boolean isPending() { return Status.UNDEFINED.equals(jibriStatus) || Status.PENDING.equals(jibriStatus); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @throws StartException if failed to start. */ synchronized public void start() throws StartException { try { startInternal(); } catch (Exception e) { stats.sessionFailed(getJibriType()); throw e; } } /** * Does the actual start logic. * * @throws StartException if fails to start. */ private void startInternal() throws StartException { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid == null) { logger.error("Unable to find an available Jibri, can't start"); if (jibriDetector.isAnyInstanceConnected()) { throw new StartException(StartException.ALL_BUSY); } throw new StartException(StartException.NOT_AVAILABLE); } try { jibriEventHandler.start(FocusBundleActivator.bundleContext); logger.info("Starting session with Jibri " + jibriJid); sendJibriStartIq(jibriJid); } catch (Exception e) { logger.error("Failed to send start Jibri IQ: " + e, e); jibriDetector.memberHadTransientError(jibriJid); if (!maxRetriesExceeded()) { retryRequestWithAnotherJibri(); } else { throw new StartException(StartException.INTERNAL_SERVER_ERROR); } } } /** * Stops this session if it's not already stopped. * @param initiator The jid of the initiator of the stop request. */ synchronized public void stop(Jid initiator) { if (currentJibriJid == null) { return; } this.terminator = initiator; JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); stopRequest.setSessionId(this.sessionId); logger.info("Trying to stop: " + stopRequest.toXML()); // When we<SUF> // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { if (stanza instanceof JibriIq) { processJibriIqFromJibri((JibriIq) stanza); } else { logger.error( "Unexpected response to stop iq: " + (stanza != null ? stanza.toXML() : "null")); JibriIq error = new JibriIq(); error.setFrom(stopRequest.getTo()); error.setFailureReason(FailureReason.ERROR); error.setStatus(Status.OFF); processJibriIqFromJibri(error); } }, exception -> logger.error( "Error sending stop iq: " + exception.toString()), 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } /** * Process a {@link JibriIq} *request* from Jibri * @param request * @return the response */ IQ processJibriIqRequestFromJibri(JibriIq request) { processJibriIqFromJibri(request); return IQ.createResultIQ(request); } /** * Process a {@link JibriIq} from Jibri (note that this * may be an IQ request or an IQ response) * @param iq */ private void processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate( iq.getFrom(), status, iq.getFailureReason(), iq.getShouldRetry()); } else { logger.error( "Received UNDEFINED status from jibri: " + iq.toString()); } } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. * @throws OperationFailedException if XMPP connection failed * @throws StartException if something went wrong */ private void sendJibriStartIq(final Jid jibriJid) throws OperationFailedException, StartException { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug( "Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); IQ reply = xmpp.sendPacketAndGetReply(startIq); if (!(reply instanceof JibriIq)) { logger.error( "Unexpected response to start request: " + (reply != null ? reply.toXML() : "null")); throw new StartException(StartException.UNEXPECTED_RESPONSE); } JibriIq jibriIq = (JibriIq) reply; // According to the "protocol" only PENDING status is allowed in // response to the start request. if (!Status.PENDING.equals(jibriIq.getStatus())) { logger.error( "Unexpected status received in response to the start IQ: " + jibriIq.toXML()); throw new StartException(StartException.UNEXPECTED_RESPONSE); } processJibriIqFromJibri(jibriIq); } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will clear recording state after a timeout of * {@link JibriConfig#getPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we've not exceeded the max amount of retries, * false otherwise */ private boolean maxRetriesExceeded() { return (maxNumRetries >= 0 && numRetries >= maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @throws StartException if failed to start. */ private void retryRequestWithAnotherJibri() throws StartException { numRetries++; start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new * IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully * (or there was an error but we have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) * @param shouldRetryParam if {@code failureReason} is not null, shouldRetry * denotes whether or not we should retry the same * request with another Jibri */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason, @Nullable Boolean shouldRetryParam) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's // new state), make sure we stop the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info( "Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another // Jibri to keep things going if (failureReason != null) { boolean shouldRetry; if (shouldRetryParam == null) { logger.warn("failureReason was non-null but shouldRetry " + "wasn't set, will NOT retry"); shouldRetry = false; } else { shouldRetry = shouldRetryParam; } // There was an error with the current Jibri, see if we should retry if (shouldRetry && !maxRetriesExceeded()) { logger.info("Jibri failed, trying to fall back to another Jibri"); try { retryRequestWithAnotherJibri(); // The fallback to another Jibri succeeded. logger.info( "Successfully resumed session with another Jibri"); } catch (StartException exc) { logger.info( "Failed to fall back to another Jibri, this " + "session has now failed: " + exc, exc); // Propagate up that the session has failed entirely. // We'll pass the original failure reason. dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else { if (!shouldRetry) { logger.info("Jibri failed and signaled that we " + "should not retry the same request"); } else { // The Jibri we tried failed and we've reached the maxmium // amount of retries we've been configured to attempt, so we'll // give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); } dispatchSessionStateChanged(newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and " + "cleaning up session"); // The Jibri stopped for some non-error reason dispatchSessionStateChanged(newStatus, null); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); dispatchSessionStateChanged(newStatus, null); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate( jibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * Task scheduled after we have received RESULT response from Jibri and entered PENDING state. Will abort the * recording if we do not transit to ON state, after a timeout of {@link JibriConfig#getPendingTimeout()}. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's // likely hung or having some issue. We'll send a stop (so // if/when it does 'recover', it knows to stop) and simulate // an error status (like we do in // JibriEventHandler#handleEvent when a Jibri goes offline) // to trigger the fallback logic. stop(null); handleJibriStatusUpdate( currentJibriJid, Status.OFF, FailureReason.ERROR, true); } } } } /** * The JID of the entity that has initiated the recording flow. * @return The JID of the entity that has initiated the recording flow. */ public Jid getInitiator() { return initiator; } /** * The JID of the entity that has initiated the stop of the recording. * @return The JID of the entity that has stopped the recording. */ public Jid getTerminator() { return terminator; } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } static public class StartException extends Exception { final static String ALL_BUSY = "All Jibri instances are busy"; final static String INTERNAL_SERVER_ERROR = "Internal server error"; final static String NOT_AVAILABLE = "No Jibris available"; final static String UNEXPECTED_RESPONSE = "Unexpected response"; private final String reason; StartException(String reason) { super(reason); this.reason = reason; } String getReason() { return reason; } } /** * A Jibri session type. */ public enum Type { /** * SIP Jibri call. */ SIP_CALL, /** * Jibri live streaming session. */ LIVE_STREAMING, /** * Jibri recording session. */ RECORDING } }
201749_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-test-funqmachine/src/main/java/nl/bzk/brp/funqmachine/verstuurder/soap/SoapClient.java
1,396
/** * SoapClient voor het versturen van soap berichten. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het<SUF>*/ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
201749_2
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-test-funqmachine/src/main/java/nl/bzk/brp/funqmachine/verstuurder/soap/SoapClient.java
1,396
/** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. <SUF>*/ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
201749_3
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-test-funqmachine/src/main/java/nl/bzk/brp/funqmachine/verstuurder/soap/SoapClient.java
1,396
/** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor<SUF>*/ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
201749_4
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-test-funqmachine/src/main/java/nl/bzk/brp/funqmachine/verstuurder/soap/SoapClient.java
1,396
// Bouw het initiele request bericht
line_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het<SUF> final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
201749_5
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-test-funqmachine/src/main/java/nl/bzk/brp/funqmachine/verstuurder/soap/SoapClient.java
1,396
// Haal het antwoord op
line_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het<SUF> final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
201749_6
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de content uit het antwoord en retourneer deze. return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-test-funqmachine/src/main/java/nl/bzk/brp/funqmachine/verstuurder/soap/SoapClient.java
1,396
// Extraheer de content uit het antwoord en retourneer deze.
line_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.funqmachine.verstuurder.soap; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import nl.bzk.brp.funqmachine.jbehave.context.AutAutContext; import nl.bzk.brp.service.algemeen.request.OIN; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * SoapClient voor het versturen van soap berichten. */ public class SoapClient { private static final Logger LOGGER = LoggerFactory.getLogger(SoapClient.class); private URL wsdlURL = null; /** * Constructor. * @param params parameters voor het ophalen van WSDL en sturen van de requests */ public SoapClient(final SoapParameters params) { try { wsdlURL = params.getWsdlURL(); } catch (MalformedURLException e) { LOGGER.error("Exception creating SoapClient: {}", e.getMessage()); throw new ServicesNietBereikbaarException("Kan geen SoapClient creeren naar " + wsdlURL, e); } } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes("UTF-8")); } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven * naam van het bericht bestand zal worden ingelezen en als de body van het verzoek naar de webservice worden * verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP headers etc. zorgt. Uit het * antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. * @return de body van het antwoord, ontzien van allerlei niet direct relevante SOAP zaken. */ public Node verzendBerichtNaarService(final String berichtBestand) throws SOAPException { try { // Bouw het initiele request bericht final SOAPMessage request = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op final AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); final SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (verzoek.getOinOndertekenaar() != null) { request.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, verzoek.getOinOndertekenaar()); } if (verzoek.getOinTransporteur() != null) { request.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, verzoek.getOinTransporteur()); } final SOAPMessage response = connection.call(request, wsdlURL); printSOAPMessage(response); // Extraheer de<SUF> return extraheerAntwoordUitSoapBericht(response); } catch (final IOException | TransformerConfigurationException | ParserConfigurationException | SAXException | SOAPException e) { LOGGER.error("Fout tijdens verzenden van SOAP bericht", e); throw new SOAPException(e); } } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document request = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(request); return soapMessage; } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody()); return source.getNode(); } private void printSOAPMessage(final SOAPMessage msg) { try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); LOGGER.info(out.toString(Charset.defaultCharset().name())); } catch (final SOAPException | IOException e) { LOGGER.error("Fout tijdens printen SOAP message", e); } } }
201751_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * Service voor het doen van SOAP requests */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het<SUF>*/ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_7
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * @return indicatie of er een SOAP fout is opgetreden */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of<SUF>*/ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_8
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * @return het requestbericht */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht<SUF>*/ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_9
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * @return het responsebericht */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht<SUF>*/ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_10
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * Assert dat het responsebericht XSD valide is. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het<SUF>*/ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_11
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie<SUF>*/ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_12
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * @return de dienst waar het verzoek voor uitgevoerd is */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst<SUF>*/ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_13
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * @return indicatie of het een vrijbericht verzoek betreft. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of<SUF>*/ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_14
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * @return indicatie of het een vrijbericht verzoek betreft. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of<SUF>*/ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_15
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
/** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor<SUF>*/ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_16
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
// Bouw het initiele request bericht
line_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het<SUF> final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_17
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
// Haal het antwoord op
line_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het<SUF> //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_18
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
//AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek();
line_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek<SUF> SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201751_19
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/brp/test/brp-docker-test/src/main/java/nl/bzk/brp/dockertest/service/VerzoekService.java
6,599
//registreer afnemerindicatie kan plaatsen of verwijderen afn.ind. zijn
line_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.dockertest.service; import com.google.common.collect.Iterables; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienst; import nl.bzk.algemeenbrp.dal.domein.brp.entity.Dienstbundel; import nl.bzk.algemeenbrp.dal.domein.brp.entity.ToegangLeveringsAutorisatie; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortBericht; import nl.bzk.algemeenbrp.dal.domein.brp.enums.SoortDienst; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelService; import nl.bzk.algemeenbrp.services.objectsleutel.ObjectSleutelServiceImpl; import nl.bzk.algemeenbrp.util.common.DatumUtil; import nl.bzk.algemeenbrp.util.common.logging.Logger; import nl.bzk.algemeenbrp.util.common.logging.LoggerFactory; import nl.bzk.brp.dockertest.component.BrpOmgeving; import nl.bzk.brp.dockertest.component.Docker; import nl.bzk.brp.dockertest.component.DockerNaam; import nl.bzk.brp.dockertest.component.OmgevingException; import nl.bzk.brp.dockertest.component.Poorten; import nl.bzk.brp.dockertest.jbehave.JBehaveState; import nl.bzk.brp.dockertest.util.ResourceUtils; import nl.bzk.brp.dockertest.util.SchemaValidator; import nl.bzk.brp.service.algemeen.Mappings; import nl.bzk.brp.service.algemeen.request.OIN; import nl.bzk.brp.test.common.TestclientExceptie; import nl.bzk.brp.test.common.xml.XmlUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.mutable.MutableObject; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Service voor het doen van SOAP requests */ public final class VerzoekService { private static final Logger LOGGER = LoggerFactory.getLogger(); private static final String MORGEN_PLACEHOLDER = "${morgen}"; private static final String GISTER_PLACEHOLDER = "${gister}"; private static final String GISTEREN_PLACEHOLDER = "${gisteren}"; private static final String VANDAAG_PLACEHOLDER = "${vandaag}"; private final BrpOmgeving brpOmgeving; private final ObjectSleutelService objectSleutelService; private Dienst dienst; private String request; private String response; private boolean soapFoutOpgetreden; private boolean vrijberichtVerzoek; private boolean bijhoudingverzoek; private ToegangLeveringsAutorisatie toegangLeveringautorisatie; /** * * @param brpOmgeving */ public VerzoekService(final BrpOmgeving brpOmgeving) { this.brpOmgeving = brpOmgeving; objectSleutelService = new ObjectSleutelServiceImpl(); } /** * * @param requestBestand * @param toegangLeveringsAutorisatie */ public void maakVerzoek(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { LOGGER.info("maakVerzoek {}", requestBestand); reset(); final SoortDienst soortDienst = bepaalSoortDienst(requestBestand); bepaalDienst(toegangLeveringsAutorisatie, soortDienst); this.request = maakRequest(requestBestand, toegangLeveringsAutorisatie); this.toegangLeveringautorisatie = toegangLeveringsAutorisatie; final URL url; try { url = bepaalURL(soortDienst); } catch (MalformedURLException e) { throw new TestclientExceptie(e); } try { final String oinOndertekenaar = toegangLeveringsAutorisatie.getOndertekenaar() == null ? null : toegangLeveringsAutorisatie.getOndertekenaar().getOin(); final String oinTransporteur = toegangLeveringsAutorisatie.getTransporteur() == null ? null : toegangLeveringsAutorisatie.getTransporteur().getOin(); verzendBerichtNaarService(request, url, oinOndertekenaar, oinTransporteur); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } catch (Exception e) { throw new TestclientExceptie(e); } } /** * * @param requestBestand * @param partijNaam * @param gbaVerzoek */ public void maakBijhoudingVerzoek(final Resource requestBestand, String partijNaam, boolean gbaVerzoek) { LOGGER.info("maakBijhoudingVerzoek {}", requestBestand); reset(); this.bijhoudingverzoek = true; URL url = null; this.request = ResourceUtils.resourceToString(requestBestand); try { final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String zendendePartijWaarde = (String) xpath.evaluate("//*[local-name()='zendendePartij']/text()", requestXmlDocument, XPathConstants.STRING); vervangBsnDoorObjectSleutel(requestXmlDocument, xpath); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, MORGEN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTER_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, GISTEREN_PLACEHOLDER); vervangDatumPlaceholdersMetEchteDatum(requestXmlDocument, xpath, VANDAAG_PLACEHOLDER); if (!gbaVerzoek) { final String verzoek = XmlUtils.documentToString(requestXmlDocument); final SoortBericht soortBericht = SoortBericht.parseIdentifier(XmlUtils.resourceToDomSource(requestBestand).getNode().getFirstChild().getLocalName()); url = bepaalURL(soortBericht); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijWaarde), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijWaarde, oin); oinZendendePartij.setValue(oin); } }); verzendBerichtNaarService(verzoek, url, oinZendendePartij.getValue(), oinZendendePartij.getValue()); ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { LOGGER.error("Fout tijdens verwerkenBericht van bijhoudingsbericht", e); throw new TestclientExceptie(e); } catch (SOAPException e) { LOGGER.error(String.format("Fout tijdens versturen bijhoudingsverzoek, url %s", url), e); throw new TestclientExceptie(e); } } /** * * @param requestBestand */ public void maakVrijberichtVerzoek(final ClassPathResource requestBestand) { LOGGER.info("maakVrijberichtVerzoek {}", requestBestand); reset(); this.vrijberichtVerzoek = true; this.request = ResourceUtils.resourceToString(requestBestand); final Document document = XmlUtils.stringToDocument(request); final String zendendePartijCode = XmlUtils.getNodeWaarde("//brp:zenderVrijBericht", document); final MutableObject<String> oinZendendePartij = new MutableObject<>(); brpOmgeving.brpDatabase().template().readonly(jdbcTemplate -> { final List<String> list = jdbcTemplate.queryForList(String.format("select oin from kern.partij where code = '%s'", zendendePartijCode), String.class); if (!list.isEmpty()) { final String oin = list.iterator().next(); LOGGER.debug("OIN voor Partij {} is {}", zendendePartijCode, oin); oinZendendePartij.setValue(oin); } }); try { verzendBerichtNaarService(request, getUrl("vrijbericht/VrijBerichtService/vrbStuurVrijBericht", DockerNaam.VRIJBERICHT), oinZendendePartij.getValue(), oinZendendePartij.getValue()); } catch (IOException | SOAPException | SAXException | ParserConfigurationException e) { LOGGER.error("Fout bij verzenden vrij bericht verzoek: " + e); throw new TestclientExceptie(e); } ResourceUtils.schrijfBerichtNaarBestand(response, JBehaveState.getScenarioState().getCurrentStory().getPath(), JBehaveState.getScenarioState().getCurrectScenario(), "response.xml"); } /** * @return indicatie of er een SOAP fout is opgetreden */ public boolean isSoapFoutOpgetreden() { return soapFoutOpgetreden; } /** * @return het requestbericht */ public String getRequest() { Assert.notNull(request, "Geen request bericht gevonden!"); return request; } /** * @return het responsebericht */ public String getResponse() { Assert.notNull(response, "Geen response bericht gevonden!"); return response; } /** * Assert dat het responsebericht XSD valide is. */ public void assertResponseXsdValide() { final Source xmlSource = new StreamSource(new StringReader(getResponse())); if (dienst == null) { SchemaValidator.valideerTegenVrijBerichtSchema(xmlSource); } else { switch (dienst.getSoortDienst()) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: SchemaValidator.valideerTegenAfnemerindicatieSchema(xmlSource); break; case GEEF_DETAILS_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: case ZOEK_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: SchemaValidator.valideerTegenBevragingSchema(xmlSource); break; case SYNCHRONISATIE_PERSOON: case SYNCHRONISATIE_STAMGEGEVEN: SchemaValidator.valideerTegenSynchronisatieSchema(xmlSource); break; default: throw new TestclientExceptie("Kan antwoordbericht niet valideren voor dienst: " + dienst.getSoortDienst()); } } } /** * @return de Toegangleveringsautorisatie waar het verzoek voor uitgevoerd is */ public ToegangLeveringsAutorisatie getToegangLeveringautorisatie() { return toegangLeveringautorisatie; } /** * @return de dienst waar het verzoek voor uitgevoerd is */ public Dienst getDienst() { return dienst; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isVrijberichtVerzoek() { return vrijberichtVerzoek; } /** * @return indicatie of het een vrijbericht verzoek betreft. */ boolean isBijhoudingVerzoek() { return bijhoudingverzoek; } /** * Standaard methode voor het verzenden van een bericht naar de WebService in een integratietest. De opgegeven naam van het bericht bestand zal worden * ingelezen en als de body van het verzoek naar de webservice worden verstuurd, waarbij deze methode tevens voor het toevoegen van de benodigde SOAP * headers etc. zorgt. Uit het antwoord dat terugkomt van de nl.sandersmee.testtool.ontvanger wordt de body geextraheerd en als {@link Node} geretourneerd * door deze methode. * @param berichtBestand de bestandsnaam die verwijst naar een bestand met daarin de content die moet worden verstuurd. */ private void verzendBerichtNaarService(final String berichtBestand, final URL wsdlURL, final String oinOndertekenaar, final String oinTransporteur) throws IOException, SOAPException, SAXException, ParserConfigurationException { // Bouw het initiele request bericht final SOAPMessage soapMessage = bouwInitieleRequestBericht(getInputStream(berichtBestand)); // Haal het antwoord op //AutAutContext.VerzoekAutorisatie verzoek = AutAutContext.get().getAutorisatieVoorVerzoek(); SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance(); final SOAPConnection connection = factory.createConnection(); if (oinOndertekenaar != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_ONDERTEKENAAR, oinOndertekenaar); } if (oinTransporteur != null) { soapMessage.getMimeHeaders().addHeader(OIN.OIN_TRANSPORTEUR, oinTransporteur); } final SOAPMessage soapResponse = connection.call(soapMessage, wsdlURL); this.soapFoutOpgetreden = soapResponse.getSOAPBody().getFault() != null; this.response = getResponse(soapResponse); LOGGER.debug("\nResponse:\n{}", this.response); } private InputStream getInputStream(final String bericht) throws IOException { return new ByteArrayInputStream(bericht.getBytes(StandardCharsets.UTF_8)); } private SOAPMessage bouwInitieleRequestBericht(final InputStream inputStream) throws ParserConfigurationException, IOException, SAXException, SOAPException { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); final Document document = documentBuilderFactory.newDocumentBuilder().parse(inputStream); final SOAPMessage soapMessage = MessageFactory.newInstance().createMessage(); soapMessage.getSOAPBody().addDocument(document); return soapMessage; } private String getResponse(final SOAPMessage msg) { try { final Node node = extraheerAntwoordUitSoapBericht(msg); return XmlUtils.format(XmlUtils.nodeToString(node)); } catch (Exception e) { throw new TestclientExceptie(e); } } private Node extraheerAntwoordUitSoapBericht(final SOAPMessage soapMessage) throws TransformerConfigurationException, SOAPException { final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(soapMessage.getSOAPBody().getFirstChild()); return source.getNode(); } private String maakRequest(final Resource requestBestand, final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie) { String tempRequest; try (final InputStream inputStream = requestBestand.getInputStream()) { tempRequest = IOUtils.toString(inputStream, StandardCharsets.UTF_8); } catch (IOException e) { throw new OmgevingException(e); } tempRequest = StringUtils.replace(tempRequest, "${levsautorisatieId}", toegangLeveringsAutorisatie.getLeveringsautorisatie().getId().toString()); tempRequest = StringUtils.replace(tempRequest, "${partijCode}", StringUtils.leftPad(String.valueOf(toegangLeveringsAutorisatie.getGeautoriseerde().getPartij().getCode()), 6, "0")); tempRequest = StringUtils.replace(tempRequest, "${dienstId}", dienst.getId().toString()); LOGGER.debug("Request:\n{}", tempRequest); return tempRequest; } private void bepaalDienst(final ToegangLeveringsAutorisatie toegangLeveringsAutorisatie, final SoortDienst soortDienst) { final Set<Dienstbundel> dienstbundelSet = toegangLeveringsAutorisatie.getLeveringsautorisatie().getDienstbundelSet(); for (Dienstbundel dienstbundel : dienstbundelSet) { for (Dienst mogelijkeDienst : dienstbundel.getDienstSet()) { if (mogelijkeDienst.getSoortDienst() == soortDienst) { this.dienst = mogelijkeDienst; break; } } } Assert.notNull(dienst, "Dienst niet gevonden van type: " + soortDienst); LOGGER.debug("Toegangleveringsautorisatie = {}, Dienst = {}", toegangLeveringsAutorisatie.getId(), this.dienst.getId()); } private SoortDienst bepaalSoortDienst(final Resource requestBestand) { final SoortDienst soortDienst; try { final DOMSource requestSource = XmlUtils.resourceToDomSource(requestBestand); final Set<SoortDienst> soortDienstSet = Mappings.soortDienst(requestSource.getNode().getFirstChild().getLocalName()); Assert.isTrue(!soortDienstSet.isEmpty(), "SoortDienst niet gevonden voor requestelement: " + requestSource.getNode().getFirstChild().getLocalName()); if (soortDienstSet.size() > 1) { //registreer afnemerindicatie<SUF> final Document requestXmlDocument = XmlUtils.inputStreamToDocument(requestBestand.getInputStream()); if (brpOmgeving.getxPathHelper() .isNodeAanwezig(XmlUtils.documentToString(requestXmlDocument), "brp:lvg_synRegistreerAfnemerindicatie/brp:plaatsingAfnemerindicatie")) { soortDienst = SoortDienst.PLAATSING_AFNEMERINDICATIE; } else { soortDienst = SoortDienst.VERWIJDERING_AFNEMERINDICATIE; } } else { soortDienst = Iterables.getOnlyElement(soortDienstSet); } } catch (IOException e) { throw new TestclientExceptie(e); } return soortDienst; } private URL bepaalURL(final SoortDienst soortDienst) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortDienst) { case PLAATSING_AFNEMERINDICATIE: case VERWIJDERING_AFNEMERINDICATIE: servicePostfix = "afnemerindicaties/AfnemerindicatiesService/lvgAfnemerindicaties"; dockerNaam = DockerNaam.ONDERHOUDAFNEMERINDICATIES; break; case GEEF_STUF_BG_BERICHT: servicePostfix = "stuf/StufbgVertalingService/stvStufbgVertaling"; dockerNaam = DockerNaam.STUF; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: servicePostfix = "bevraging/LeveringBevragingService/lvgBevraging"; dockerNaam = DockerNaam.BEVRAGING; break; case SYNCHRONISATIE_STAMGEGEVEN: case SYNCHRONISATIE_PERSOON: servicePostfix = "synchronisatie/SynchronisatieService/lvgSynchronisatie"; dockerNaam = DockerNaam.SYNCHRONISATIE; break; default: Assert.isTrue(false, "Dienst wordt niet ondersteund: " + soortDienst); } return getUrl(servicePostfix, dockerNaam); } private URL bepaalURL(final SoortBericht soortBericht) throws MalformedURLException { String servicePostfix = null; DockerNaam dockerNaam = null; switch (soortBericht) { case BHG_HGP_REGISTREER_HUWELIJK_GEREGISTREERD_PARTNERSCHAP: servicePostfix = "bijhouding/BijhoudingService/bhgHuwelijkGeregistreerdPartnerschap"; dockerNaam = DockerNaam.BIJHOUDING; break; case BHG_AFS_REGISTREER_GEBOORTE: servicePostfix = "bijhouding/BijhoudingService/bhgAfstamming"; dockerNaam = DockerNaam.BIJHOUDING; break; default: Assert.isTrue(false, "Verzoek wordt niet ondersteund: " + soortBericht); } return getUrl(servicePostfix, dockerNaam); } private URL getUrl(final String servicePostfix, final DockerNaam dockerNaam) throws MalformedURLException { final Docker component = brpOmgeving.geefDocker(dockerNaam); return new URL(String.format("http://%s:%s/%s", brpOmgeving.getDockerHostname(), component.getPoortMap().get(Poorten.APPSERVER_PORT), servicePostfix)); } private void vervangBsnDoorObjectSleutel(final Document doc, final XPath xpath) throws XPathExpressionException { final NodeList persoonNodes = (NodeList) xpath.evaluate("//*[local-name()='persoon']", doc, XPathConstants.NODESET); for (int index = 0; index < persoonNodes.getLength(); index++) { final Node node = persoonNodes.item(index); final Node objectSleutelNode = node.getAttributes().getNamedItem("brp:objectSleutel"); if (objectSleutelNode != null) { final PersIdVerzoek persIdVerzoek = new PersIdVerzoek(objectSleutelNode.getNodeValue()); brpOmgeving.brpDatabase().template().readonly(persIdVerzoek); final String objectSleutel = objectSleutelService.maakPersoonObjectSleutel(persIdVerzoek.getPersId(), persIdVerzoek.getLockVersie()).maskeren(); objectSleutelNode.setNodeValue(objectSleutel); } } } private void vervangDatumPlaceholdersMetEchteDatum(final Document doc, final XPath xpath, final String datumPlaceholder) throws XPathExpressionException { final NodeList datumNodes = (NodeList) xpath.evaluate("//*[text()[contains(., '" + datumPlaceholder + "')]]", doc, XPathConstants.NODESET); final int nieuweDatum; switch (datumPlaceholder) { case MORGEN_PLACEHOLDER: nieuweDatum = DatumUtil.morgen(); break; case GISTEREN_PLACEHOLDER: case GISTER_PLACEHOLDER: nieuweDatum = DatumUtil.gisteren(); break; case VANDAAG_PLACEHOLDER: nieuweDatum = DatumUtil.vandaag(); break; default: throw new TestclientExceptie("Onbekende placeholder voor een datum gevonden"); } for (int index = 0; index < datumNodes.getLength(); index++) { final Node datumNode = datumNodes.item(index); String nd = Integer.toString(nieuweDatum); datumNode.setTextContent(nd.substring(0, 4) + "-" + nd.substring(4, 6) + "-" + nd.substring(6)); } } private void updateCacheSelectief(final SoortDienst soortDienst) { DockerNaam[] teVerversenComponenten; switch (soortDienst) { case VERWIJDERING_AFNEMERINDICATIE: case PLAATSING_AFNEMERINDICATIE: teVerversenComponenten = new DockerNaam[]{DockerNaam.ONDERHOUDAFNEMERINDICATIES, DockerNaam.VERZENDING}; break; case GEEF_DETAILS_PERSOON: case GEEF_MEDEBEWONERS_VAN_PERSOON: case ZOEK_PERSOON: case ZOEK_PERSOON_OP_ADRESGEGEVENS: teVerversenComponenten = new DockerNaam[]{DockerNaam.BEVRAGING}; break; case SYNCHRONISATIE_PERSOON: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE, DockerNaam.VERZENDING}; break; case SYNCHRONISATIE_STAMGEGEVEN: teVerversenComponenten = new DockerNaam[]{DockerNaam.SYNCHRONISATIE}; break; default: teVerversenComponenten = null; } if (teVerversenComponenten != null) { brpOmgeving.cache().refresh(teVerversenComponenten); } } private void reset() { dienst = null; request = null; response = null; soapFoutOpgetreden = false; toegangLeveringautorisatie = null; if (brpOmgeving.bevat(DockerNaam.ROUTERINGCENTRALE)) { brpOmgeving.asynchroonBericht().purge(); } vrijberichtVerzoek = false; } }
201754_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.business.stappen.bevraging; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.inject.Inject; import nl.bzk.brp.business.definities.impl.afstamming.KandidaatVader; import nl.bzk.brp.business.dto.BerichtContext; import nl.bzk.brp.business.dto.bevraging.AbstractBevragingsBericht; import nl.bzk.brp.business.dto.bevraging.OpvragenPersoonResultaat; import nl.bzk.brp.business.dto.bevraging.VraagDetailsPersoonBericht; import nl.bzk.brp.business.dto.bevraging.VraagKandidaatVaderBericht; import nl.bzk.brp.business.dto.bevraging.VraagPersonenOpAdresInclusiefBetrokkenhedenBericht; import nl.bzk.brp.business.dto.bevraging.zoekcriteria.ZoekCriteriaPersoonOpAdres; import nl.bzk.brp.business.stappen.AbstractBerichtVerwerkingsStap; import nl.bzk.brp.dataaccess.repository.PersoonRepository; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Datum; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisletter; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummer; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummertoevoeging; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Ja; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Postcode; import nl.bzk.brp.model.algemeen.stamgegeven.ber.SoortMelding; import nl.bzk.brp.model.algemeen.stamgegeven.kern.Geslachtsaanduiding; import nl.bzk.brp.model.operationeel.kern.BetrokkenheidModel; import nl.bzk.brp.model.operationeel.kern.PersoonAdresModel; import nl.bzk.brp.model.operationeel.kern.PersoonIndicatieModel; import nl.bzk.brp.model.operationeel.kern.PersoonModel; import nl.bzk.brp.model.operationeel.kern.RelatieModel; import nl.bzk.brp.model.validatie.Melding; import nl.bzk.brp.model.validatie.MeldingCode; import nl.bzk.brp.util.AttribuutTypeUtil; import nl.bzk.brp.util.ObjectUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; /** Uitvoer stap die het opvragen van een persoon afhandelt. De persoon wordt via de DAL laag opgehaald. */ public class OpvragenPersoonBerichtUitvoerStap extends AbstractBerichtVerwerkingsStap<AbstractBevragingsBericht, OpvragenPersoonResultaat> { @Inject private PersoonRepository persoonRepository; @Inject private KandidaatVader kandidaatVader; @Override public boolean voerVerwerkingsStapUitVoorBericht(final AbstractBevragingsBericht bericht, final BerichtContext context, final OpvragenPersoonResultaat resultaat) { boolean verwerkingsResultaat; if (bericht instanceof VraagDetailsPersoonBericht) { verwerkingsResultaat = vraagOpDetailPersoon((VraagDetailsPersoonBericht) bericht, resultaat); } else if (bericht instanceof VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) { verwerkingsResultaat = vraagOpPersonenOpAdresInclusiefBetrokkenheden( (VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) bericht, resultaat); } else if (bericht instanceof VraagKandidaatVaderBericht) { verwerkingsResultaat = vraagOpKandidaatVader((VraagKandidaatVaderBericht) bericht, resultaat); } else { verwerkingsResultaat = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; } return verwerkingsResultaat; } /** * Methode om persoon details op te halen. * * @param bericht het VraagDetailsPersoonBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpDetailPersoon(final VraagDetailsPersoonBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean metHistorie = false; boolean inclFormeleHistorie = false; if (bericht.getVraag().getVraagOpties() != null) { if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieFormeel()) { metHistorie = true; inclFormeleHistorie = true; } else if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieMaterieel()) { metHistorie = true; } } final PersoonModel gevondenPersoon = persoonRepository.haalPersoonOpMetBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (gevondenPersoon != null) { if (metHistorie) { persoonRepository.vulaanAdresMetHistorie(gevondenPersoon, inclFormeleHistorie); } // bolie: tijdelijke hack, omdat we alles met lazy loading definieren, moeten we zorgen dat alle elementen // geladen moeten worden voordat de transactie afgelopen is. laadRelatiesPersoon(gevondenPersoon); laadPersoonIndicaties(gevondenPersoon); gevondenPersoon.getTechnischeSleutel(); resultaat.setGevondenPersonen(new HashSet<PersoonModel>()); resultaat.getGevondenPersonen().add(gevondenPersoon); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "burgerservicenummer")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * Methode om alle personen op te halen die op het adres zijn ingeschreven op basis van de vraag in het bericht. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpPersonenOpAdresInclusiefBetrokkenheden( final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht, final OpvragenPersoonResultaat resultaat) { List<PersoonModel> gevondenPersonen = new ArrayList<PersoonModel>(); if (isBsnCriteria(bericht)) { gevondenPersonen = persoonRepository.haalPersonenMetWoonAdresOpViaBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (CollectionUtils.isNotEmpty(gevondenPersonen) && CollectionUtils.isNotEmpty(gevondenPersonen.get(0).getAdressen())) { // Uitgaande van dat er maar 1 persoon terugkomt met bsn zoek vraag. // Uitgaande dat er er maar 1 woon adres aanwezig kan zijn. PersoonAdresModel persoonAdres = gevondenPersonen.get(0).getAdressen().iterator().next(); gevondenPersonen = haalAllePersonenOpMetAdres(persoonAdres); } } else if (isPostcodeCriteria(bericht)) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); gevondenPersonen = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(new Postcode(zoekCriteria.getPostcode()), new Huisnummer(zoekCriteria.getHuisnummer().toString()), new Huisletter(zoekCriteria.getHuisletter()), new Huisnummertoevoeging(zoekCriteria.getHuisnummertoevoeging())); } else if (isGemCodeCriteria(bericht)) { // TODO implementeer aanroep naar juiste methode om te zoeken met gemeente adres // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } else { // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } // Alle null waardes er uit halen (kunnen voorkomen) gevondenPersonen.removeAll(Collections.singletonList(null)); if (CollectionUtils.isNotEmpty(gevondenPersonen)) { verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(gevondenPersonen); resultaat.setGevondenPersonen(new HashSet<PersoonModel>(gevondenPersonen)); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * test of een persoon (betrokkene) in een list van personen bevindt. Er wordt alleen gekeken naar de persoon.id. * We kunnen niet zo maar .contains(object) gebruiker, omdat de lijst is een 'simpel persoon' en de betrokkene * een 'referentie persoon' is. * * @param gevondenPersonen de lijst van personen * @param betrokkene de betrokkene * @return true als deze in de lijst zit, false anders. */ private boolean isBetrokkeneInGevondenPersonen(final List<PersoonModel> gevondenPersonen, final PersoonModel betrokkene) { boolean resultaat = false; for (PersoonModel persoon : gevondenPersonen) { if (persoon.getID().equals(betrokkene.getID())) { resultaat = true; break; } } return resultaat; } /** * Deze methode schoont alle betrokkene van de gevonden personen die niet op dit adres wonen. * * @param gevondenPersonen de lijst van gevonden personen. */ private void verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(final List<PersoonModel> gevondenPersonen) { for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { for (BetrokkenheidModel betrokkenheid : persoon.getBetrokkenheden()) { RelatieModel relatie = betrokkenheid.getRelatie(); // loop door een 'copy' omdat we anders een concurrent probleem hebben tijdens het verwijderen. List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(relatie.getBetrokkenheden()); for (BetrokkenheidModel bPartner : copy) { if (!isBetrokkeneInGevondenPersonen(gevondenPersonen, bPartner.getPersoon())) { relatie.getBetrokkenheden().remove(bPartner); } } } } } for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { // We moeten nu opschonen, elk relatie dat slechts 1 'member' heeft gaat niet goed; want dat is // altijd de persoon himself. Verwijder de realtie EN daarmee de betrokkenheid. // for some reason, binding gaat fout met alleen 1-member link List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(persoon.getBetrokkenheden()); for (BetrokkenheidModel betrokkenheid : copy) { if (betrokkenheid.getRelatie().getBetrokkenheden().size() <= 1) { // relatie met 1 of minder betrkkenheden is geen relatie. verwijder deze (dus ook de // betrokkenheid. persoon.getBetrokkenheden().remove(betrokkenheid); } } } } } /** * Methode om alle personen op te halen die mogelijk de vader zou kunnen zijn . * * @param bericht het bericht * @param resultaat de lijst van personen die potentieel vader kunnen zijn. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpKandidaatVader(final VraagKandidaatVaderBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean retval = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; PersoonModel moeder = persoonRepository.findByBurgerservicenummer(bericht.getVraag().getZoekCriteria().getBurgerservicenummer()); // deze validatie(s) zou eerder moeten gebeuren. if (moeder == null) { // TODO Foutmelding 'BSN onbekend', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "BSN is onbekend.", bericht .getVraag().getZoekCriteria(), "burgerservicenummer")); } else if (moeder.getGeslachtsaanduiding().getGeslachtsaanduiding() != Geslachtsaanduiding.VROUW) { // TODO Foutmelding 'BSN is geen Vrouw', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "De persoon is niet van het vrouwelijk geslacht.", bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } else { List<PersoonModel> kandidatenVader = kandidaatVader .bepaalKandidatenVader(moeder, new Datum(bericht.getVraag().getZoekCriteria().getGeboortedatumKind())); if (!kandidatenVader.isEmpty()) { Set<PersoonModel> resultaten = new TreeSet<PersoonModel>(); resultaten.addAll(kandidatenVader); resultaat.setGevondenPersonen(resultaten); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.BRPUC50110, MeldingCode.BRPUC50110.getOmschrijving(), bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } retval = AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } return retval; } /** * Algoritme om alle personen op te halen die wonen op een adres. * <p/> * Zoekmethoden: 1. identificatiecodeNummeraanduiding 2. combinatie NaamOpenbareRuimte, Huisnummer, Huisletter, * HuisnummerToevoeging, LocatieOmschrijving, LocatieTOVAdres en Woonplaats gelijk zijn, mits NaamOpenbareRuimte, * Huisnummer en Woonplaats gevuld zijn 3. De combinatie Postcode, huisnummer, Huisletter en HuisnummerToevoeging * gelijk zijn, mits postcode en huis gevuld zijn. * <p/> * Wanneer met de ene methode niks gevonden wordt dan wordt de volgende methode uitgeprobeerd. * * @param persoonAdres PersistentPersoonAdres waarmee gezocht moet worden. * @return alle personen die op het adres wonen. * @brp.bedrijfsregel BRPUC50121 */ private List<PersoonModel> haalAllePersonenOpMetAdres(final PersoonAdresModel persoonAdres) { List<PersoonModel> resultaat = new ArrayList<PersoonModel>(); if (persoonAdres != null) { // Zoek verder met de PersistentPersoonAdres if (AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getIdentificatiecodeNummeraanduiding())) { // Zoeken met IdentificatiecodeNummeraanduiding resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaIdentificatiecodeNummeraanduiding(persoonAdres .getStandaard().getIdentificatiecodeNummeraanduiding()); // Resultaat moet op zijn minst de persoon zelf teruggeven. if (resultaat.size() < 2) { if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres .getStandaard().getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } } else if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } else { resultaat.add(persoonAdres.getPersoon()); } } return resultaat; } /** * Controlleer of het om een bsn zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als alleen de BSN is ingevuld in het zoek bericht */ private boolean isBsnCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return AttribuutTypeUtil.isNotBlank(zoekCriteria.getBurgerservicenummer()) && ObjectUtil.isAllEmpty(zoekCriteria.getPostcode(), zoekCriteria.getHuisnummer(), zoekCriteria.getHuisletter(), zoekCriteria.getHuisnummertoevoeging(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een postcode zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om postcode huisnummer zoek criteria gaat */ private boolean isPostcodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return StringUtils.isNotBlank(zoekCriteria.getPostcode()) && zoekCriteria.getHuisnummer() != null && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een gemeente code zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om plaats adres huisnummer zoek criteria gaat */ private boolean isGemCodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return zoekCriteria.getHuisnummer() != null && StringUtils.isNotBlank(zoekCriteria.getNaamOpenbareRuimte()) && StringUtils.isNotBlank(zoekCriteria.getGemeentecode()) && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getPostcode()); } /** * Bepaalt of zoek opdracht met volledige adres uitgevoerd mag worden. Hier wordt gekeken of NaamOpenbareRuimte, * huisnummer en woonplaats is ingevuld. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als de genoemde velden gevuld zijn. */ private boolean isZoekbaarMetVolledigAdres(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getNaamOpenbareRuimte()) && persoonAdres.getStandaard().getHuisnummer() != null && persoonAdres.getStandaard().getHuisnummer().getWaarde() != null && persoonAdres.getStandaard().getWoonplaats() != null; } /** * Bepaalt of zoek opdracht met postcode en huisnummer uitgevoerd mag worden. Hier wordt gekeken naar postcode en * huisnummer. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als postcode en huisnummer zijn ingevuld. */ private boolean isZoekbaarMetOpPostcodeHuisnummer(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getPostcode()) && AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getHuisnummer()); } /** * Lazy loading, loop door de betrookenheden->relatie->betrokkenheden van de persoon. * @param persoon de persoon. */ private void laadRelatiesPersoon(final PersoonModel persoon) { for (BetrokkenheidModel betr : persoon.getBetrokkenheden()) { RelatieModel relatie = betr.getRelatie(); for (BetrokkenheidModel betrUitRelatie : relatie.getBetrokkenheden()) { if (betrUitRelatie != betr) { // lazy loading... betrUitRelatie.getPersoon().getTechnischeSleutel(); laadPersoonIndicaties(betrUitRelatie.getPersoon()); } } } } /** * Lazy loading, loop door de indicatie van de persoon. * @param persoon de persoon. */ private void laadPersoonIndicaties(final PersoonModel persoon) { for (PersoonIndicatieModel ind : persoon.getIndicaties()) { // lazy loading... ind.getPersoon(); } } }
MinBZK/OperatieBRP
2013/brp 2013-02-07/BRP/branches/brp-stappen-refactoring/business/src/main/java/nl/bzk/brp/business/stappen/bevraging/OpvragenPersoonBerichtUitvoerStap.java
6,348
/** Uitvoer stap die het opvragen van een persoon afhandelt. De persoon wordt via de DAL laag opgehaald. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.business.stappen.bevraging; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.inject.Inject; import nl.bzk.brp.business.definities.impl.afstamming.KandidaatVader; import nl.bzk.brp.business.dto.BerichtContext; import nl.bzk.brp.business.dto.bevraging.AbstractBevragingsBericht; import nl.bzk.brp.business.dto.bevraging.OpvragenPersoonResultaat; import nl.bzk.brp.business.dto.bevraging.VraagDetailsPersoonBericht; import nl.bzk.brp.business.dto.bevraging.VraagKandidaatVaderBericht; import nl.bzk.brp.business.dto.bevraging.VraagPersonenOpAdresInclusiefBetrokkenhedenBericht; import nl.bzk.brp.business.dto.bevraging.zoekcriteria.ZoekCriteriaPersoonOpAdres; import nl.bzk.brp.business.stappen.AbstractBerichtVerwerkingsStap; import nl.bzk.brp.dataaccess.repository.PersoonRepository; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Datum; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisletter; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummer; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummertoevoeging; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Ja; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Postcode; import nl.bzk.brp.model.algemeen.stamgegeven.ber.SoortMelding; import nl.bzk.brp.model.algemeen.stamgegeven.kern.Geslachtsaanduiding; import nl.bzk.brp.model.operationeel.kern.BetrokkenheidModel; import nl.bzk.brp.model.operationeel.kern.PersoonAdresModel; import nl.bzk.brp.model.operationeel.kern.PersoonIndicatieModel; import nl.bzk.brp.model.operationeel.kern.PersoonModel; import nl.bzk.brp.model.operationeel.kern.RelatieModel; import nl.bzk.brp.model.validatie.Melding; import nl.bzk.brp.model.validatie.MeldingCode; import nl.bzk.brp.util.AttribuutTypeUtil; import nl.bzk.brp.util.ObjectUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; /** Uitvoer stap die<SUF>*/ public class OpvragenPersoonBerichtUitvoerStap extends AbstractBerichtVerwerkingsStap<AbstractBevragingsBericht, OpvragenPersoonResultaat> { @Inject private PersoonRepository persoonRepository; @Inject private KandidaatVader kandidaatVader; @Override public boolean voerVerwerkingsStapUitVoorBericht(final AbstractBevragingsBericht bericht, final BerichtContext context, final OpvragenPersoonResultaat resultaat) { boolean verwerkingsResultaat; if (bericht instanceof VraagDetailsPersoonBericht) { verwerkingsResultaat = vraagOpDetailPersoon((VraagDetailsPersoonBericht) bericht, resultaat); } else if (bericht instanceof VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) { verwerkingsResultaat = vraagOpPersonenOpAdresInclusiefBetrokkenheden( (VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) bericht, resultaat); } else if (bericht instanceof VraagKandidaatVaderBericht) { verwerkingsResultaat = vraagOpKandidaatVader((VraagKandidaatVaderBericht) bericht, resultaat); } else { verwerkingsResultaat = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; } return verwerkingsResultaat; } /** * Methode om persoon details op te halen. * * @param bericht het VraagDetailsPersoonBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpDetailPersoon(final VraagDetailsPersoonBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean metHistorie = false; boolean inclFormeleHistorie = false; if (bericht.getVraag().getVraagOpties() != null) { if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieFormeel()) { metHistorie = true; inclFormeleHistorie = true; } else if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieMaterieel()) { metHistorie = true; } } final PersoonModel gevondenPersoon = persoonRepository.haalPersoonOpMetBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (gevondenPersoon != null) { if (metHistorie) { persoonRepository.vulaanAdresMetHistorie(gevondenPersoon, inclFormeleHistorie); } // bolie: tijdelijke hack, omdat we alles met lazy loading definieren, moeten we zorgen dat alle elementen // geladen moeten worden voordat de transactie afgelopen is. laadRelatiesPersoon(gevondenPersoon); laadPersoonIndicaties(gevondenPersoon); gevondenPersoon.getTechnischeSleutel(); resultaat.setGevondenPersonen(new HashSet<PersoonModel>()); resultaat.getGevondenPersonen().add(gevondenPersoon); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "burgerservicenummer")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * Methode om alle personen op te halen die op het adres zijn ingeschreven op basis van de vraag in het bericht. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpPersonenOpAdresInclusiefBetrokkenheden( final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht, final OpvragenPersoonResultaat resultaat) { List<PersoonModel> gevondenPersonen = new ArrayList<PersoonModel>(); if (isBsnCriteria(bericht)) { gevondenPersonen = persoonRepository.haalPersonenMetWoonAdresOpViaBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (CollectionUtils.isNotEmpty(gevondenPersonen) && CollectionUtils.isNotEmpty(gevondenPersonen.get(0).getAdressen())) { // Uitgaande van dat er maar 1 persoon terugkomt met bsn zoek vraag. // Uitgaande dat er er maar 1 woon adres aanwezig kan zijn. PersoonAdresModel persoonAdres = gevondenPersonen.get(0).getAdressen().iterator().next(); gevondenPersonen = haalAllePersonenOpMetAdres(persoonAdres); } } else if (isPostcodeCriteria(bericht)) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); gevondenPersonen = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(new Postcode(zoekCriteria.getPostcode()), new Huisnummer(zoekCriteria.getHuisnummer().toString()), new Huisletter(zoekCriteria.getHuisletter()), new Huisnummertoevoeging(zoekCriteria.getHuisnummertoevoeging())); } else if (isGemCodeCriteria(bericht)) { // TODO implementeer aanroep naar juiste methode om te zoeken met gemeente adres // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } else { // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } // Alle null waardes er uit halen (kunnen voorkomen) gevondenPersonen.removeAll(Collections.singletonList(null)); if (CollectionUtils.isNotEmpty(gevondenPersonen)) { verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(gevondenPersonen); resultaat.setGevondenPersonen(new HashSet<PersoonModel>(gevondenPersonen)); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * test of een persoon (betrokkene) in een list van personen bevindt. Er wordt alleen gekeken naar de persoon.id. * We kunnen niet zo maar .contains(object) gebruiker, omdat de lijst is een 'simpel persoon' en de betrokkene * een 'referentie persoon' is. * * @param gevondenPersonen de lijst van personen * @param betrokkene de betrokkene * @return true als deze in de lijst zit, false anders. */ private boolean isBetrokkeneInGevondenPersonen(final List<PersoonModel> gevondenPersonen, final PersoonModel betrokkene) { boolean resultaat = false; for (PersoonModel persoon : gevondenPersonen) { if (persoon.getID().equals(betrokkene.getID())) { resultaat = true; break; } } return resultaat; } /** * Deze methode schoont alle betrokkene van de gevonden personen die niet op dit adres wonen. * * @param gevondenPersonen de lijst van gevonden personen. */ private void verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(final List<PersoonModel> gevondenPersonen) { for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { for (BetrokkenheidModel betrokkenheid : persoon.getBetrokkenheden()) { RelatieModel relatie = betrokkenheid.getRelatie(); // loop door een 'copy' omdat we anders een concurrent probleem hebben tijdens het verwijderen. List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(relatie.getBetrokkenheden()); for (BetrokkenheidModel bPartner : copy) { if (!isBetrokkeneInGevondenPersonen(gevondenPersonen, bPartner.getPersoon())) { relatie.getBetrokkenheden().remove(bPartner); } } } } } for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { // We moeten nu opschonen, elk relatie dat slechts 1 'member' heeft gaat niet goed; want dat is // altijd de persoon himself. Verwijder de realtie EN daarmee de betrokkenheid. // for some reason, binding gaat fout met alleen 1-member link List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(persoon.getBetrokkenheden()); for (BetrokkenheidModel betrokkenheid : copy) { if (betrokkenheid.getRelatie().getBetrokkenheden().size() <= 1) { // relatie met 1 of minder betrkkenheden is geen relatie. verwijder deze (dus ook de // betrokkenheid. persoon.getBetrokkenheden().remove(betrokkenheid); } } } } } /** * Methode om alle personen op te halen die mogelijk de vader zou kunnen zijn . * * @param bericht het bericht * @param resultaat de lijst van personen die potentieel vader kunnen zijn. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpKandidaatVader(final VraagKandidaatVaderBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean retval = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; PersoonModel moeder = persoonRepository.findByBurgerservicenummer(bericht.getVraag().getZoekCriteria().getBurgerservicenummer()); // deze validatie(s) zou eerder moeten gebeuren. if (moeder == null) { // TODO Foutmelding 'BSN onbekend', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "BSN is onbekend.", bericht .getVraag().getZoekCriteria(), "burgerservicenummer")); } else if (moeder.getGeslachtsaanduiding().getGeslachtsaanduiding() != Geslachtsaanduiding.VROUW) { // TODO Foutmelding 'BSN is geen Vrouw', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "De persoon is niet van het vrouwelijk geslacht.", bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } else { List<PersoonModel> kandidatenVader = kandidaatVader .bepaalKandidatenVader(moeder, new Datum(bericht.getVraag().getZoekCriteria().getGeboortedatumKind())); if (!kandidatenVader.isEmpty()) { Set<PersoonModel> resultaten = new TreeSet<PersoonModel>(); resultaten.addAll(kandidatenVader); resultaat.setGevondenPersonen(resultaten); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.BRPUC50110, MeldingCode.BRPUC50110.getOmschrijving(), bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } retval = AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } return retval; } /** * Algoritme om alle personen op te halen die wonen op een adres. * <p/> * Zoekmethoden: 1. identificatiecodeNummeraanduiding 2. combinatie NaamOpenbareRuimte, Huisnummer, Huisletter, * HuisnummerToevoeging, LocatieOmschrijving, LocatieTOVAdres en Woonplaats gelijk zijn, mits NaamOpenbareRuimte, * Huisnummer en Woonplaats gevuld zijn 3. De combinatie Postcode, huisnummer, Huisletter en HuisnummerToevoeging * gelijk zijn, mits postcode en huis gevuld zijn. * <p/> * Wanneer met de ene methode niks gevonden wordt dan wordt de volgende methode uitgeprobeerd. * * @param persoonAdres PersistentPersoonAdres waarmee gezocht moet worden. * @return alle personen die op het adres wonen. * @brp.bedrijfsregel BRPUC50121 */ private List<PersoonModel> haalAllePersonenOpMetAdres(final PersoonAdresModel persoonAdres) { List<PersoonModel> resultaat = new ArrayList<PersoonModel>(); if (persoonAdres != null) { // Zoek verder met de PersistentPersoonAdres if (AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getIdentificatiecodeNummeraanduiding())) { // Zoeken met IdentificatiecodeNummeraanduiding resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaIdentificatiecodeNummeraanduiding(persoonAdres .getStandaard().getIdentificatiecodeNummeraanduiding()); // Resultaat moet op zijn minst de persoon zelf teruggeven. if (resultaat.size() < 2) { if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres .getStandaard().getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } } else if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } else { resultaat.add(persoonAdres.getPersoon()); } } return resultaat; } /** * Controlleer of het om een bsn zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als alleen de BSN is ingevuld in het zoek bericht */ private boolean isBsnCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return AttribuutTypeUtil.isNotBlank(zoekCriteria.getBurgerservicenummer()) && ObjectUtil.isAllEmpty(zoekCriteria.getPostcode(), zoekCriteria.getHuisnummer(), zoekCriteria.getHuisletter(), zoekCriteria.getHuisnummertoevoeging(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een postcode zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om postcode huisnummer zoek criteria gaat */ private boolean isPostcodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return StringUtils.isNotBlank(zoekCriteria.getPostcode()) && zoekCriteria.getHuisnummer() != null && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een gemeente code zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om plaats adres huisnummer zoek criteria gaat */ private boolean isGemCodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return zoekCriteria.getHuisnummer() != null && StringUtils.isNotBlank(zoekCriteria.getNaamOpenbareRuimte()) && StringUtils.isNotBlank(zoekCriteria.getGemeentecode()) && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getPostcode()); } /** * Bepaalt of zoek opdracht met volledige adres uitgevoerd mag worden. Hier wordt gekeken of NaamOpenbareRuimte, * huisnummer en woonplaats is ingevuld. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als de genoemde velden gevuld zijn. */ private boolean isZoekbaarMetVolledigAdres(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getNaamOpenbareRuimte()) && persoonAdres.getStandaard().getHuisnummer() != null && persoonAdres.getStandaard().getHuisnummer().getWaarde() != null && persoonAdres.getStandaard().getWoonplaats() != null; } /** * Bepaalt of zoek opdracht met postcode en huisnummer uitgevoerd mag worden. Hier wordt gekeken naar postcode en * huisnummer. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als postcode en huisnummer zijn ingevuld. */ private boolean isZoekbaarMetOpPostcodeHuisnummer(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getPostcode()) && AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getHuisnummer()); } /** * Lazy loading, loop door de betrookenheden->relatie->betrokkenheden van de persoon. * @param persoon de persoon. */ private void laadRelatiesPersoon(final PersoonModel persoon) { for (BetrokkenheidModel betr : persoon.getBetrokkenheden()) { RelatieModel relatie = betr.getRelatie(); for (BetrokkenheidModel betrUitRelatie : relatie.getBetrokkenheden()) { if (betrUitRelatie != betr) { // lazy loading... betrUitRelatie.getPersoon().getTechnischeSleutel(); laadPersoonIndicaties(betrUitRelatie.getPersoon()); } } } } /** * Lazy loading, loop door de indicatie van de persoon. * @param persoon de persoon. */ private void laadPersoonIndicaties(final PersoonModel persoon) { for (PersoonIndicatieModel ind : persoon.getIndicaties()) { // lazy loading... ind.getPersoon(); } } }
201754_2
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.business.stappen.bevraging; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.inject.Inject; import nl.bzk.brp.business.definities.impl.afstamming.KandidaatVader; import nl.bzk.brp.business.dto.BerichtContext; import nl.bzk.brp.business.dto.bevraging.AbstractBevragingsBericht; import nl.bzk.brp.business.dto.bevraging.OpvragenPersoonResultaat; import nl.bzk.brp.business.dto.bevraging.VraagDetailsPersoonBericht; import nl.bzk.brp.business.dto.bevraging.VraagKandidaatVaderBericht; import nl.bzk.brp.business.dto.bevraging.VraagPersonenOpAdresInclusiefBetrokkenhedenBericht; import nl.bzk.brp.business.dto.bevraging.zoekcriteria.ZoekCriteriaPersoonOpAdres; import nl.bzk.brp.business.stappen.AbstractBerichtVerwerkingsStap; import nl.bzk.brp.dataaccess.repository.PersoonRepository; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Datum; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisletter; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummer; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummertoevoeging; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Ja; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Postcode; import nl.bzk.brp.model.algemeen.stamgegeven.ber.SoortMelding; import nl.bzk.brp.model.algemeen.stamgegeven.kern.Geslachtsaanduiding; import nl.bzk.brp.model.operationeel.kern.BetrokkenheidModel; import nl.bzk.brp.model.operationeel.kern.PersoonAdresModel; import nl.bzk.brp.model.operationeel.kern.PersoonIndicatieModel; import nl.bzk.brp.model.operationeel.kern.PersoonModel; import nl.bzk.brp.model.operationeel.kern.RelatieModel; import nl.bzk.brp.model.validatie.Melding; import nl.bzk.brp.model.validatie.MeldingCode; import nl.bzk.brp.util.AttribuutTypeUtil; import nl.bzk.brp.util.ObjectUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; /** Uitvoer stap die het opvragen van een persoon afhandelt. De persoon wordt via de DAL laag opgehaald. */ public class OpvragenPersoonBerichtUitvoerStap extends AbstractBerichtVerwerkingsStap<AbstractBevragingsBericht, OpvragenPersoonResultaat> { @Inject private PersoonRepository persoonRepository; @Inject private KandidaatVader kandidaatVader; @Override public boolean voerVerwerkingsStapUitVoorBericht(final AbstractBevragingsBericht bericht, final BerichtContext context, final OpvragenPersoonResultaat resultaat) { boolean verwerkingsResultaat; if (bericht instanceof VraagDetailsPersoonBericht) { verwerkingsResultaat = vraagOpDetailPersoon((VraagDetailsPersoonBericht) bericht, resultaat); } else if (bericht instanceof VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) { verwerkingsResultaat = vraagOpPersonenOpAdresInclusiefBetrokkenheden( (VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) bericht, resultaat); } else if (bericht instanceof VraagKandidaatVaderBericht) { verwerkingsResultaat = vraagOpKandidaatVader((VraagKandidaatVaderBericht) bericht, resultaat); } else { verwerkingsResultaat = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; } return verwerkingsResultaat; } /** * Methode om persoon details op te halen. * * @param bericht het VraagDetailsPersoonBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpDetailPersoon(final VraagDetailsPersoonBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean metHistorie = false; boolean inclFormeleHistorie = false; if (bericht.getVraag().getVraagOpties() != null) { if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieFormeel()) { metHistorie = true; inclFormeleHistorie = true; } else if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieMaterieel()) { metHistorie = true; } } final PersoonModel gevondenPersoon = persoonRepository.haalPersoonOpMetBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (gevondenPersoon != null) { if (metHistorie) { persoonRepository.vulaanAdresMetHistorie(gevondenPersoon, inclFormeleHistorie); } // bolie: tijdelijke hack, omdat we alles met lazy loading definieren, moeten we zorgen dat alle elementen // geladen moeten worden voordat de transactie afgelopen is. laadRelatiesPersoon(gevondenPersoon); laadPersoonIndicaties(gevondenPersoon); gevondenPersoon.getTechnischeSleutel(); resultaat.setGevondenPersonen(new HashSet<PersoonModel>()); resultaat.getGevondenPersonen().add(gevondenPersoon); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "burgerservicenummer")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * Methode om alle personen op te halen die op het adres zijn ingeschreven op basis van de vraag in het bericht. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpPersonenOpAdresInclusiefBetrokkenheden( final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht, final OpvragenPersoonResultaat resultaat) { List<PersoonModel> gevondenPersonen = new ArrayList<PersoonModel>(); if (isBsnCriteria(bericht)) { gevondenPersonen = persoonRepository.haalPersonenMetWoonAdresOpViaBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (CollectionUtils.isNotEmpty(gevondenPersonen) && CollectionUtils.isNotEmpty(gevondenPersonen.get(0).getAdressen())) { // Uitgaande van dat er maar 1 persoon terugkomt met bsn zoek vraag. // Uitgaande dat er er maar 1 woon adres aanwezig kan zijn. PersoonAdresModel persoonAdres = gevondenPersonen.get(0).getAdressen().iterator().next(); gevondenPersonen = haalAllePersonenOpMetAdres(persoonAdres); } } else if (isPostcodeCriteria(bericht)) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); gevondenPersonen = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(new Postcode(zoekCriteria.getPostcode()), new Huisnummer(zoekCriteria.getHuisnummer().toString()), new Huisletter(zoekCriteria.getHuisletter()), new Huisnummertoevoeging(zoekCriteria.getHuisnummertoevoeging())); } else if (isGemCodeCriteria(bericht)) { // TODO implementeer aanroep naar juiste methode om te zoeken met gemeente adres // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } else { // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } // Alle null waardes er uit halen (kunnen voorkomen) gevondenPersonen.removeAll(Collections.singletonList(null)); if (CollectionUtils.isNotEmpty(gevondenPersonen)) { verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(gevondenPersonen); resultaat.setGevondenPersonen(new HashSet<PersoonModel>(gevondenPersonen)); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * test of een persoon (betrokkene) in een list van personen bevindt. Er wordt alleen gekeken naar de persoon.id. * We kunnen niet zo maar .contains(object) gebruiker, omdat de lijst is een 'simpel persoon' en de betrokkene * een 'referentie persoon' is. * * @param gevondenPersonen de lijst van personen * @param betrokkene de betrokkene * @return true als deze in de lijst zit, false anders. */ private boolean isBetrokkeneInGevondenPersonen(final List<PersoonModel> gevondenPersonen, final PersoonModel betrokkene) { boolean resultaat = false; for (PersoonModel persoon : gevondenPersonen) { if (persoon.getID().equals(betrokkene.getID())) { resultaat = true; break; } } return resultaat; } /** * Deze methode schoont alle betrokkene van de gevonden personen die niet op dit adres wonen. * * @param gevondenPersonen de lijst van gevonden personen. */ private void verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(final List<PersoonModel> gevondenPersonen) { for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { for (BetrokkenheidModel betrokkenheid : persoon.getBetrokkenheden()) { RelatieModel relatie = betrokkenheid.getRelatie(); // loop door een 'copy' omdat we anders een concurrent probleem hebben tijdens het verwijderen. List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(relatie.getBetrokkenheden()); for (BetrokkenheidModel bPartner : copy) { if (!isBetrokkeneInGevondenPersonen(gevondenPersonen, bPartner.getPersoon())) { relatie.getBetrokkenheden().remove(bPartner); } } } } } for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { // We moeten nu opschonen, elk relatie dat slechts 1 'member' heeft gaat niet goed; want dat is // altijd de persoon himself. Verwijder de realtie EN daarmee de betrokkenheid. // for some reason, binding gaat fout met alleen 1-member link List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(persoon.getBetrokkenheden()); for (BetrokkenheidModel betrokkenheid : copy) { if (betrokkenheid.getRelatie().getBetrokkenheden().size() <= 1) { // relatie met 1 of minder betrkkenheden is geen relatie. verwijder deze (dus ook de // betrokkenheid. persoon.getBetrokkenheden().remove(betrokkenheid); } } } } } /** * Methode om alle personen op te halen die mogelijk de vader zou kunnen zijn . * * @param bericht het bericht * @param resultaat de lijst van personen die potentieel vader kunnen zijn. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpKandidaatVader(final VraagKandidaatVaderBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean retval = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; PersoonModel moeder = persoonRepository.findByBurgerservicenummer(bericht.getVraag().getZoekCriteria().getBurgerservicenummer()); // deze validatie(s) zou eerder moeten gebeuren. if (moeder == null) { // TODO Foutmelding 'BSN onbekend', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "BSN is onbekend.", bericht .getVraag().getZoekCriteria(), "burgerservicenummer")); } else if (moeder.getGeslachtsaanduiding().getGeslachtsaanduiding() != Geslachtsaanduiding.VROUW) { // TODO Foutmelding 'BSN is geen Vrouw', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "De persoon is niet van het vrouwelijk geslacht.", bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } else { List<PersoonModel> kandidatenVader = kandidaatVader .bepaalKandidatenVader(moeder, new Datum(bericht.getVraag().getZoekCriteria().getGeboortedatumKind())); if (!kandidatenVader.isEmpty()) { Set<PersoonModel> resultaten = new TreeSet<PersoonModel>(); resultaten.addAll(kandidatenVader); resultaat.setGevondenPersonen(resultaten); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.BRPUC50110, MeldingCode.BRPUC50110.getOmschrijving(), bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } retval = AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } return retval; } /** * Algoritme om alle personen op te halen die wonen op een adres. * <p/> * Zoekmethoden: 1. identificatiecodeNummeraanduiding 2. combinatie NaamOpenbareRuimte, Huisnummer, Huisletter, * HuisnummerToevoeging, LocatieOmschrijving, LocatieTOVAdres en Woonplaats gelijk zijn, mits NaamOpenbareRuimte, * Huisnummer en Woonplaats gevuld zijn 3. De combinatie Postcode, huisnummer, Huisletter en HuisnummerToevoeging * gelijk zijn, mits postcode en huis gevuld zijn. * <p/> * Wanneer met de ene methode niks gevonden wordt dan wordt de volgende methode uitgeprobeerd. * * @param persoonAdres PersistentPersoonAdres waarmee gezocht moet worden. * @return alle personen die op het adres wonen. * @brp.bedrijfsregel BRPUC50121 */ private List<PersoonModel> haalAllePersonenOpMetAdres(final PersoonAdresModel persoonAdres) { List<PersoonModel> resultaat = new ArrayList<PersoonModel>(); if (persoonAdres != null) { // Zoek verder met de PersistentPersoonAdres if (AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getIdentificatiecodeNummeraanduiding())) { // Zoeken met IdentificatiecodeNummeraanduiding resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaIdentificatiecodeNummeraanduiding(persoonAdres .getStandaard().getIdentificatiecodeNummeraanduiding()); // Resultaat moet op zijn minst de persoon zelf teruggeven. if (resultaat.size() < 2) { if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres .getStandaard().getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } } else if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } else { resultaat.add(persoonAdres.getPersoon()); } } return resultaat; } /** * Controlleer of het om een bsn zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als alleen de BSN is ingevuld in het zoek bericht */ private boolean isBsnCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return AttribuutTypeUtil.isNotBlank(zoekCriteria.getBurgerservicenummer()) && ObjectUtil.isAllEmpty(zoekCriteria.getPostcode(), zoekCriteria.getHuisnummer(), zoekCriteria.getHuisletter(), zoekCriteria.getHuisnummertoevoeging(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een postcode zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om postcode huisnummer zoek criteria gaat */ private boolean isPostcodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return StringUtils.isNotBlank(zoekCriteria.getPostcode()) && zoekCriteria.getHuisnummer() != null && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een gemeente code zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om plaats adres huisnummer zoek criteria gaat */ private boolean isGemCodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return zoekCriteria.getHuisnummer() != null && StringUtils.isNotBlank(zoekCriteria.getNaamOpenbareRuimte()) && StringUtils.isNotBlank(zoekCriteria.getGemeentecode()) && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getPostcode()); } /** * Bepaalt of zoek opdracht met volledige adres uitgevoerd mag worden. Hier wordt gekeken of NaamOpenbareRuimte, * huisnummer en woonplaats is ingevuld. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als de genoemde velden gevuld zijn. */ private boolean isZoekbaarMetVolledigAdres(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getNaamOpenbareRuimte()) && persoonAdres.getStandaard().getHuisnummer() != null && persoonAdres.getStandaard().getHuisnummer().getWaarde() != null && persoonAdres.getStandaard().getWoonplaats() != null; } /** * Bepaalt of zoek opdracht met postcode en huisnummer uitgevoerd mag worden. Hier wordt gekeken naar postcode en * huisnummer. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als postcode en huisnummer zijn ingevuld. */ private boolean isZoekbaarMetOpPostcodeHuisnummer(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getPostcode()) && AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getHuisnummer()); } /** * Lazy loading, loop door de betrookenheden->relatie->betrokkenheden van de persoon. * @param persoon de persoon. */ private void laadRelatiesPersoon(final PersoonModel persoon) { for (BetrokkenheidModel betr : persoon.getBetrokkenheden()) { RelatieModel relatie = betr.getRelatie(); for (BetrokkenheidModel betrUitRelatie : relatie.getBetrokkenheden()) { if (betrUitRelatie != betr) { // lazy loading... betrUitRelatie.getPersoon().getTechnischeSleutel(); laadPersoonIndicaties(betrUitRelatie.getPersoon()); } } } } /** * Lazy loading, loop door de indicatie van de persoon. * @param persoon de persoon. */ private void laadPersoonIndicaties(final PersoonModel persoon) { for (PersoonIndicatieModel ind : persoon.getIndicaties()) { // lazy loading... ind.getPersoon(); } } }
MinBZK/OperatieBRP
2013/brp 2013-02-07/BRP/branches/brp-stappen-refactoring/business/src/main/java/nl/bzk/brp/business/stappen/bevraging/OpvragenPersoonBerichtUitvoerStap.java
6,348
/** * Methode om persoon details op te halen. * * @param bericht het VraagDetailsPersoonBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.business.stappen.bevraging; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.inject.Inject; import nl.bzk.brp.business.definities.impl.afstamming.KandidaatVader; import nl.bzk.brp.business.dto.BerichtContext; import nl.bzk.brp.business.dto.bevraging.AbstractBevragingsBericht; import nl.bzk.brp.business.dto.bevraging.OpvragenPersoonResultaat; import nl.bzk.brp.business.dto.bevraging.VraagDetailsPersoonBericht; import nl.bzk.brp.business.dto.bevraging.VraagKandidaatVaderBericht; import nl.bzk.brp.business.dto.bevraging.VraagPersonenOpAdresInclusiefBetrokkenhedenBericht; import nl.bzk.brp.business.dto.bevraging.zoekcriteria.ZoekCriteriaPersoonOpAdres; import nl.bzk.brp.business.stappen.AbstractBerichtVerwerkingsStap; import nl.bzk.brp.dataaccess.repository.PersoonRepository; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Datum; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisletter; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummer; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummertoevoeging; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Ja; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Postcode; import nl.bzk.brp.model.algemeen.stamgegeven.ber.SoortMelding; import nl.bzk.brp.model.algemeen.stamgegeven.kern.Geslachtsaanduiding; import nl.bzk.brp.model.operationeel.kern.BetrokkenheidModel; import nl.bzk.brp.model.operationeel.kern.PersoonAdresModel; import nl.bzk.brp.model.operationeel.kern.PersoonIndicatieModel; import nl.bzk.brp.model.operationeel.kern.PersoonModel; import nl.bzk.brp.model.operationeel.kern.RelatieModel; import nl.bzk.brp.model.validatie.Melding; import nl.bzk.brp.model.validatie.MeldingCode; import nl.bzk.brp.util.AttribuutTypeUtil; import nl.bzk.brp.util.ObjectUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; /** Uitvoer stap die het opvragen van een persoon afhandelt. De persoon wordt via de DAL laag opgehaald. */ public class OpvragenPersoonBerichtUitvoerStap extends AbstractBerichtVerwerkingsStap<AbstractBevragingsBericht, OpvragenPersoonResultaat> { @Inject private PersoonRepository persoonRepository; @Inject private KandidaatVader kandidaatVader; @Override public boolean voerVerwerkingsStapUitVoorBericht(final AbstractBevragingsBericht bericht, final BerichtContext context, final OpvragenPersoonResultaat resultaat) { boolean verwerkingsResultaat; if (bericht instanceof VraagDetailsPersoonBericht) { verwerkingsResultaat = vraagOpDetailPersoon((VraagDetailsPersoonBericht) bericht, resultaat); } else if (bericht instanceof VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) { verwerkingsResultaat = vraagOpPersonenOpAdresInclusiefBetrokkenheden( (VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) bericht, resultaat); } else if (bericht instanceof VraagKandidaatVaderBericht) { verwerkingsResultaat = vraagOpKandidaatVader((VraagKandidaatVaderBericht) bericht, resultaat); } else { verwerkingsResultaat = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; } return verwerkingsResultaat; } /** * Methode om persoon<SUF>*/ private boolean vraagOpDetailPersoon(final VraagDetailsPersoonBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean metHistorie = false; boolean inclFormeleHistorie = false; if (bericht.getVraag().getVraagOpties() != null) { if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieFormeel()) { metHistorie = true; inclFormeleHistorie = true; } else if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieMaterieel()) { metHistorie = true; } } final PersoonModel gevondenPersoon = persoonRepository.haalPersoonOpMetBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (gevondenPersoon != null) { if (metHistorie) { persoonRepository.vulaanAdresMetHistorie(gevondenPersoon, inclFormeleHistorie); } // bolie: tijdelijke hack, omdat we alles met lazy loading definieren, moeten we zorgen dat alle elementen // geladen moeten worden voordat de transactie afgelopen is. laadRelatiesPersoon(gevondenPersoon); laadPersoonIndicaties(gevondenPersoon); gevondenPersoon.getTechnischeSleutel(); resultaat.setGevondenPersonen(new HashSet<PersoonModel>()); resultaat.getGevondenPersonen().add(gevondenPersoon); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "burgerservicenummer")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * Methode om alle personen op te halen die op het adres zijn ingeschreven op basis van de vraag in het bericht. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpPersonenOpAdresInclusiefBetrokkenheden( final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht, final OpvragenPersoonResultaat resultaat) { List<PersoonModel> gevondenPersonen = new ArrayList<PersoonModel>(); if (isBsnCriteria(bericht)) { gevondenPersonen = persoonRepository.haalPersonenMetWoonAdresOpViaBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (CollectionUtils.isNotEmpty(gevondenPersonen) && CollectionUtils.isNotEmpty(gevondenPersonen.get(0).getAdressen())) { // Uitgaande van dat er maar 1 persoon terugkomt met bsn zoek vraag. // Uitgaande dat er er maar 1 woon adres aanwezig kan zijn. PersoonAdresModel persoonAdres = gevondenPersonen.get(0).getAdressen().iterator().next(); gevondenPersonen = haalAllePersonenOpMetAdres(persoonAdres); } } else if (isPostcodeCriteria(bericht)) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); gevondenPersonen = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(new Postcode(zoekCriteria.getPostcode()), new Huisnummer(zoekCriteria.getHuisnummer().toString()), new Huisletter(zoekCriteria.getHuisletter()), new Huisnummertoevoeging(zoekCriteria.getHuisnummertoevoeging())); } else if (isGemCodeCriteria(bericht)) { // TODO implementeer aanroep naar juiste methode om te zoeken met gemeente adres // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } else { // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } // Alle null waardes er uit halen (kunnen voorkomen) gevondenPersonen.removeAll(Collections.singletonList(null)); if (CollectionUtils.isNotEmpty(gevondenPersonen)) { verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(gevondenPersonen); resultaat.setGevondenPersonen(new HashSet<PersoonModel>(gevondenPersonen)); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * test of een persoon (betrokkene) in een list van personen bevindt. Er wordt alleen gekeken naar de persoon.id. * We kunnen niet zo maar .contains(object) gebruiker, omdat de lijst is een 'simpel persoon' en de betrokkene * een 'referentie persoon' is. * * @param gevondenPersonen de lijst van personen * @param betrokkene de betrokkene * @return true als deze in de lijst zit, false anders. */ private boolean isBetrokkeneInGevondenPersonen(final List<PersoonModel> gevondenPersonen, final PersoonModel betrokkene) { boolean resultaat = false; for (PersoonModel persoon : gevondenPersonen) { if (persoon.getID().equals(betrokkene.getID())) { resultaat = true; break; } } return resultaat; } /** * Deze methode schoont alle betrokkene van de gevonden personen die niet op dit adres wonen. * * @param gevondenPersonen de lijst van gevonden personen. */ private void verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(final List<PersoonModel> gevondenPersonen) { for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { for (BetrokkenheidModel betrokkenheid : persoon.getBetrokkenheden()) { RelatieModel relatie = betrokkenheid.getRelatie(); // loop door een 'copy' omdat we anders een concurrent probleem hebben tijdens het verwijderen. List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(relatie.getBetrokkenheden()); for (BetrokkenheidModel bPartner : copy) { if (!isBetrokkeneInGevondenPersonen(gevondenPersonen, bPartner.getPersoon())) { relatie.getBetrokkenheden().remove(bPartner); } } } } } for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { // We moeten nu opschonen, elk relatie dat slechts 1 'member' heeft gaat niet goed; want dat is // altijd de persoon himself. Verwijder de realtie EN daarmee de betrokkenheid. // for some reason, binding gaat fout met alleen 1-member link List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(persoon.getBetrokkenheden()); for (BetrokkenheidModel betrokkenheid : copy) { if (betrokkenheid.getRelatie().getBetrokkenheden().size() <= 1) { // relatie met 1 of minder betrkkenheden is geen relatie. verwijder deze (dus ook de // betrokkenheid. persoon.getBetrokkenheden().remove(betrokkenheid); } } } } } /** * Methode om alle personen op te halen die mogelijk de vader zou kunnen zijn . * * @param bericht het bericht * @param resultaat de lijst van personen die potentieel vader kunnen zijn. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpKandidaatVader(final VraagKandidaatVaderBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean retval = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; PersoonModel moeder = persoonRepository.findByBurgerservicenummer(bericht.getVraag().getZoekCriteria().getBurgerservicenummer()); // deze validatie(s) zou eerder moeten gebeuren. if (moeder == null) { // TODO Foutmelding 'BSN onbekend', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "BSN is onbekend.", bericht .getVraag().getZoekCriteria(), "burgerservicenummer")); } else if (moeder.getGeslachtsaanduiding().getGeslachtsaanduiding() != Geslachtsaanduiding.VROUW) { // TODO Foutmelding 'BSN is geen Vrouw', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "De persoon is niet van het vrouwelijk geslacht.", bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } else { List<PersoonModel> kandidatenVader = kandidaatVader .bepaalKandidatenVader(moeder, new Datum(bericht.getVraag().getZoekCriteria().getGeboortedatumKind())); if (!kandidatenVader.isEmpty()) { Set<PersoonModel> resultaten = new TreeSet<PersoonModel>(); resultaten.addAll(kandidatenVader); resultaat.setGevondenPersonen(resultaten); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.BRPUC50110, MeldingCode.BRPUC50110.getOmschrijving(), bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } retval = AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } return retval; } /** * Algoritme om alle personen op te halen die wonen op een adres. * <p/> * Zoekmethoden: 1. identificatiecodeNummeraanduiding 2. combinatie NaamOpenbareRuimte, Huisnummer, Huisletter, * HuisnummerToevoeging, LocatieOmschrijving, LocatieTOVAdres en Woonplaats gelijk zijn, mits NaamOpenbareRuimte, * Huisnummer en Woonplaats gevuld zijn 3. De combinatie Postcode, huisnummer, Huisletter en HuisnummerToevoeging * gelijk zijn, mits postcode en huis gevuld zijn. * <p/> * Wanneer met de ene methode niks gevonden wordt dan wordt de volgende methode uitgeprobeerd. * * @param persoonAdres PersistentPersoonAdres waarmee gezocht moet worden. * @return alle personen die op het adres wonen. * @brp.bedrijfsregel BRPUC50121 */ private List<PersoonModel> haalAllePersonenOpMetAdres(final PersoonAdresModel persoonAdres) { List<PersoonModel> resultaat = new ArrayList<PersoonModel>(); if (persoonAdres != null) { // Zoek verder met de PersistentPersoonAdres if (AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getIdentificatiecodeNummeraanduiding())) { // Zoeken met IdentificatiecodeNummeraanduiding resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaIdentificatiecodeNummeraanduiding(persoonAdres .getStandaard().getIdentificatiecodeNummeraanduiding()); // Resultaat moet op zijn minst de persoon zelf teruggeven. if (resultaat.size() < 2) { if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres .getStandaard().getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } } else if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } else { resultaat.add(persoonAdres.getPersoon()); } } return resultaat; } /** * Controlleer of het om een bsn zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als alleen de BSN is ingevuld in het zoek bericht */ private boolean isBsnCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return AttribuutTypeUtil.isNotBlank(zoekCriteria.getBurgerservicenummer()) && ObjectUtil.isAllEmpty(zoekCriteria.getPostcode(), zoekCriteria.getHuisnummer(), zoekCriteria.getHuisletter(), zoekCriteria.getHuisnummertoevoeging(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een postcode zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om postcode huisnummer zoek criteria gaat */ private boolean isPostcodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return StringUtils.isNotBlank(zoekCriteria.getPostcode()) && zoekCriteria.getHuisnummer() != null && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een gemeente code zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om plaats adres huisnummer zoek criteria gaat */ private boolean isGemCodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return zoekCriteria.getHuisnummer() != null && StringUtils.isNotBlank(zoekCriteria.getNaamOpenbareRuimte()) && StringUtils.isNotBlank(zoekCriteria.getGemeentecode()) && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getPostcode()); } /** * Bepaalt of zoek opdracht met volledige adres uitgevoerd mag worden. Hier wordt gekeken of NaamOpenbareRuimte, * huisnummer en woonplaats is ingevuld. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als de genoemde velden gevuld zijn. */ private boolean isZoekbaarMetVolledigAdres(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getNaamOpenbareRuimte()) && persoonAdres.getStandaard().getHuisnummer() != null && persoonAdres.getStandaard().getHuisnummer().getWaarde() != null && persoonAdres.getStandaard().getWoonplaats() != null; } /** * Bepaalt of zoek opdracht met postcode en huisnummer uitgevoerd mag worden. Hier wordt gekeken naar postcode en * huisnummer. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als postcode en huisnummer zijn ingevuld. */ private boolean isZoekbaarMetOpPostcodeHuisnummer(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getPostcode()) && AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getHuisnummer()); } /** * Lazy loading, loop door de betrookenheden->relatie->betrokkenheden van de persoon. * @param persoon de persoon. */ private void laadRelatiesPersoon(final PersoonModel persoon) { for (BetrokkenheidModel betr : persoon.getBetrokkenheden()) { RelatieModel relatie = betr.getRelatie(); for (BetrokkenheidModel betrUitRelatie : relatie.getBetrokkenheden()) { if (betrUitRelatie != betr) { // lazy loading... betrUitRelatie.getPersoon().getTechnischeSleutel(); laadPersoonIndicaties(betrUitRelatie.getPersoon()); } } } } /** * Lazy loading, loop door de indicatie van de persoon. * @param persoon de persoon. */ private void laadPersoonIndicaties(final PersoonModel persoon) { for (PersoonIndicatieModel ind : persoon.getIndicaties()) { // lazy loading... ind.getPersoon(); } } }
201754_3
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.business.stappen.bevraging; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.inject.Inject; import nl.bzk.brp.business.definities.impl.afstamming.KandidaatVader; import nl.bzk.brp.business.dto.BerichtContext; import nl.bzk.brp.business.dto.bevraging.AbstractBevragingsBericht; import nl.bzk.brp.business.dto.bevraging.OpvragenPersoonResultaat; import nl.bzk.brp.business.dto.bevraging.VraagDetailsPersoonBericht; import nl.bzk.brp.business.dto.bevraging.VraagKandidaatVaderBericht; import nl.bzk.brp.business.dto.bevraging.VraagPersonenOpAdresInclusiefBetrokkenhedenBericht; import nl.bzk.brp.business.dto.bevraging.zoekcriteria.ZoekCriteriaPersoonOpAdres; import nl.bzk.brp.business.stappen.AbstractBerichtVerwerkingsStap; import nl.bzk.brp.dataaccess.repository.PersoonRepository; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Datum; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisletter; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummer; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummertoevoeging; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Ja; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Postcode; import nl.bzk.brp.model.algemeen.stamgegeven.ber.SoortMelding; import nl.bzk.brp.model.algemeen.stamgegeven.kern.Geslachtsaanduiding; import nl.bzk.brp.model.operationeel.kern.BetrokkenheidModel; import nl.bzk.brp.model.operationeel.kern.PersoonAdresModel; import nl.bzk.brp.model.operationeel.kern.PersoonIndicatieModel; import nl.bzk.brp.model.operationeel.kern.PersoonModel; import nl.bzk.brp.model.operationeel.kern.RelatieModel; import nl.bzk.brp.model.validatie.Melding; import nl.bzk.brp.model.validatie.MeldingCode; import nl.bzk.brp.util.AttribuutTypeUtil; import nl.bzk.brp.util.ObjectUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; /** Uitvoer stap die het opvragen van een persoon afhandelt. De persoon wordt via de DAL laag opgehaald. */ public class OpvragenPersoonBerichtUitvoerStap extends AbstractBerichtVerwerkingsStap<AbstractBevragingsBericht, OpvragenPersoonResultaat> { @Inject private PersoonRepository persoonRepository; @Inject private KandidaatVader kandidaatVader; @Override public boolean voerVerwerkingsStapUitVoorBericht(final AbstractBevragingsBericht bericht, final BerichtContext context, final OpvragenPersoonResultaat resultaat) { boolean verwerkingsResultaat; if (bericht instanceof VraagDetailsPersoonBericht) { verwerkingsResultaat = vraagOpDetailPersoon((VraagDetailsPersoonBericht) bericht, resultaat); } else if (bericht instanceof VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) { verwerkingsResultaat = vraagOpPersonenOpAdresInclusiefBetrokkenheden( (VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) bericht, resultaat); } else if (bericht instanceof VraagKandidaatVaderBericht) { verwerkingsResultaat = vraagOpKandidaatVader((VraagKandidaatVaderBericht) bericht, resultaat); } else { verwerkingsResultaat = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; } return verwerkingsResultaat; } /** * Methode om persoon details op te halen. * * @param bericht het VraagDetailsPersoonBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpDetailPersoon(final VraagDetailsPersoonBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean metHistorie = false; boolean inclFormeleHistorie = false; if (bericht.getVraag().getVraagOpties() != null) { if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieFormeel()) { metHistorie = true; inclFormeleHistorie = true; } else if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieMaterieel()) { metHistorie = true; } } final PersoonModel gevondenPersoon = persoonRepository.haalPersoonOpMetBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (gevondenPersoon != null) { if (metHistorie) { persoonRepository.vulaanAdresMetHistorie(gevondenPersoon, inclFormeleHistorie); } // bolie: tijdelijke hack, omdat we alles met lazy loading definieren, moeten we zorgen dat alle elementen // geladen moeten worden voordat de transactie afgelopen is. laadRelatiesPersoon(gevondenPersoon); laadPersoonIndicaties(gevondenPersoon); gevondenPersoon.getTechnischeSleutel(); resultaat.setGevondenPersonen(new HashSet<PersoonModel>()); resultaat.getGevondenPersonen().add(gevondenPersoon); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "burgerservicenummer")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * Methode om alle personen op te halen die op het adres zijn ingeschreven op basis van de vraag in het bericht. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpPersonenOpAdresInclusiefBetrokkenheden( final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht, final OpvragenPersoonResultaat resultaat) { List<PersoonModel> gevondenPersonen = new ArrayList<PersoonModel>(); if (isBsnCriteria(bericht)) { gevondenPersonen = persoonRepository.haalPersonenMetWoonAdresOpViaBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (CollectionUtils.isNotEmpty(gevondenPersonen) && CollectionUtils.isNotEmpty(gevondenPersonen.get(0).getAdressen())) { // Uitgaande van dat er maar 1 persoon terugkomt met bsn zoek vraag. // Uitgaande dat er er maar 1 woon adres aanwezig kan zijn. PersoonAdresModel persoonAdres = gevondenPersonen.get(0).getAdressen().iterator().next(); gevondenPersonen = haalAllePersonenOpMetAdres(persoonAdres); } } else if (isPostcodeCriteria(bericht)) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); gevondenPersonen = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(new Postcode(zoekCriteria.getPostcode()), new Huisnummer(zoekCriteria.getHuisnummer().toString()), new Huisletter(zoekCriteria.getHuisletter()), new Huisnummertoevoeging(zoekCriteria.getHuisnummertoevoeging())); } else if (isGemCodeCriteria(bericht)) { // TODO implementeer aanroep naar juiste methode om te zoeken met gemeente adres // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } else { // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } // Alle null waardes er uit halen (kunnen voorkomen) gevondenPersonen.removeAll(Collections.singletonList(null)); if (CollectionUtils.isNotEmpty(gevondenPersonen)) { verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(gevondenPersonen); resultaat.setGevondenPersonen(new HashSet<PersoonModel>(gevondenPersonen)); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * test of een persoon (betrokkene) in een list van personen bevindt. Er wordt alleen gekeken naar de persoon.id. * We kunnen niet zo maar .contains(object) gebruiker, omdat de lijst is een 'simpel persoon' en de betrokkene * een 'referentie persoon' is. * * @param gevondenPersonen de lijst van personen * @param betrokkene de betrokkene * @return true als deze in de lijst zit, false anders. */ private boolean isBetrokkeneInGevondenPersonen(final List<PersoonModel> gevondenPersonen, final PersoonModel betrokkene) { boolean resultaat = false; for (PersoonModel persoon : gevondenPersonen) { if (persoon.getID().equals(betrokkene.getID())) { resultaat = true; break; } } return resultaat; } /** * Deze methode schoont alle betrokkene van de gevonden personen die niet op dit adres wonen. * * @param gevondenPersonen de lijst van gevonden personen. */ private void verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(final List<PersoonModel> gevondenPersonen) { for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { for (BetrokkenheidModel betrokkenheid : persoon.getBetrokkenheden()) { RelatieModel relatie = betrokkenheid.getRelatie(); // loop door een 'copy' omdat we anders een concurrent probleem hebben tijdens het verwijderen. List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(relatie.getBetrokkenheden()); for (BetrokkenheidModel bPartner : copy) { if (!isBetrokkeneInGevondenPersonen(gevondenPersonen, bPartner.getPersoon())) { relatie.getBetrokkenheden().remove(bPartner); } } } } } for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { // We moeten nu opschonen, elk relatie dat slechts 1 'member' heeft gaat niet goed; want dat is // altijd de persoon himself. Verwijder de realtie EN daarmee de betrokkenheid. // for some reason, binding gaat fout met alleen 1-member link List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(persoon.getBetrokkenheden()); for (BetrokkenheidModel betrokkenheid : copy) { if (betrokkenheid.getRelatie().getBetrokkenheden().size() <= 1) { // relatie met 1 of minder betrkkenheden is geen relatie. verwijder deze (dus ook de // betrokkenheid. persoon.getBetrokkenheden().remove(betrokkenheid); } } } } } /** * Methode om alle personen op te halen die mogelijk de vader zou kunnen zijn . * * @param bericht het bericht * @param resultaat de lijst van personen die potentieel vader kunnen zijn. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpKandidaatVader(final VraagKandidaatVaderBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean retval = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; PersoonModel moeder = persoonRepository.findByBurgerservicenummer(bericht.getVraag().getZoekCriteria().getBurgerservicenummer()); // deze validatie(s) zou eerder moeten gebeuren. if (moeder == null) { // TODO Foutmelding 'BSN onbekend', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "BSN is onbekend.", bericht .getVraag().getZoekCriteria(), "burgerservicenummer")); } else if (moeder.getGeslachtsaanduiding().getGeslachtsaanduiding() != Geslachtsaanduiding.VROUW) { // TODO Foutmelding 'BSN is geen Vrouw', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "De persoon is niet van het vrouwelijk geslacht.", bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } else { List<PersoonModel> kandidatenVader = kandidaatVader .bepaalKandidatenVader(moeder, new Datum(bericht.getVraag().getZoekCriteria().getGeboortedatumKind())); if (!kandidatenVader.isEmpty()) { Set<PersoonModel> resultaten = new TreeSet<PersoonModel>(); resultaten.addAll(kandidatenVader); resultaat.setGevondenPersonen(resultaten); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.BRPUC50110, MeldingCode.BRPUC50110.getOmschrijving(), bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } retval = AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } return retval; } /** * Algoritme om alle personen op te halen die wonen op een adres. * <p/> * Zoekmethoden: 1. identificatiecodeNummeraanduiding 2. combinatie NaamOpenbareRuimte, Huisnummer, Huisletter, * HuisnummerToevoeging, LocatieOmschrijving, LocatieTOVAdres en Woonplaats gelijk zijn, mits NaamOpenbareRuimte, * Huisnummer en Woonplaats gevuld zijn 3. De combinatie Postcode, huisnummer, Huisletter en HuisnummerToevoeging * gelijk zijn, mits postcode en huis gevuld zijn. * <p/> * Wanneer met de ene methode niks gevonden wordt dan wordt de volgende methode uitgeprobeerd. * * @param persoonAdres PersistentPersoonAdres waarmee gezocht moet worden. * @return alle personen die op het adres wonen. * @brp.bedrijfsregel BRPUC50121 */ private List<PersoonModel> haalAllePersonenOpMetAdres(final PersoonAdresModel persoonAdres) { List<PersoonModel> resultaat = new ArrayList<PersoonModel>(); if (persoonAdres != null) { // Zoek verder met de PersistentPersoonAdres if (AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getIdentificatiecodeNummeraanduiding())) { // Zoeken met IdentificatiecodeNummeraanduiding resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaIdentificatiecodeNummeraanduiding(persoonAdres .getStandaard().getIdentificatiecodeNummeraanduiding()); // Resultaat moet op zijn minst de persoon zelf teruggeven. if (resultaat.size() < 2) { if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres .getStandaard().getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } } else if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } else { resultaat.add(persoonAdres.getPersoon()); } } return resultaat; } /** * Controlleer of het om een bsn zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als alleen de BSN is ingevuld in het zoek bericht */ private boolean isBsnCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return AttribuutTypeUtil.isNotBlank(zoekCriteria.getBurgerservicenummer()) && ObjectUtil.isAllEmpty(zoekCriteria.getPostcode(), zoekCriteria.getHuisnummer(), zoekCriteria.getHuisletter(), zoekCriteria.getHuisnummertoevoeging(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een postcode zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om postcode huisnummer zoek criteria gaat */ private boolean isPostcodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return StringUtils.isNotBlank(zoekCriteria.getPostcode()) && zoekCriteria.getHuisnummer() != null && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een gemeente code zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om plaats adres huisnummer zoek criteria gaat */ private boolean isGemCodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return zoekCriteria.getHuisnummer() != null && StringUtils.isNotBlank(zoekCriteria.getNaamOpenbareRuimte()) && StringUtils.isNotBlank(zoekCriteria.getGemeentecode()) && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getPostcode()); } /** * Bepaalt of zoek opdracht met volledige adres uitgevoerd mag worden. Hier wordt gekeken of NaamOpenbareRuimte, * huisnummer en woonplaats is ingevuld. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als de genoemde velden gevuld zijn. */ private boolean isZoekbaarMetVolledigAdres(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getNaamOpenbareRuimte()) && persoonAdres.getStandaard().getHuisnummer() != null && persoonAdres.getStandaard().getHuisnummer().getWaarde() != null && persoonAdres.getStandaard().getWoonplaats() != null; } /** * Bepaalt of zoek opdracht met postcode en huisnummer uitgevoerd mag worden. Hier wordt gekeken naar postcode en * huisnummer. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als postcode en huisnummer zijn ingevuld. */ private boolean isZoekbaarMetOpPostcodeHuisnummer(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getPostcode()) && AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getHuisnummer()); } /** * Lazy loading, loop door de betrookenheden->relatie->betrokkenheden van de persoon. * @param persoon de persoon. */ private void laadRelatiesPersoon(final PersoonModel persoon) { for (BetrokkenheidModel betr : persoon.getBetrokkenheden()) { RelatieModel relatie = betr.getRelatie(); for (BetrokkenheidModel betrUitRelatie : relatie.getBetrokkenheden()) { if (betrUitRelatie != betr) { // lazy loading... betrUitRelatie.getPersoon().getTechnischeSleutel(); laadPersoonIndicaties(betrUitRelatie.getPersoon()); } } } } /** * Lazy loading, loop door de indicatie van de persoon. * @param persoon de persoon. */ private void laadPersoonIndicaties(final PersoonModel persoon) { for (PersoonIndicatieModel ind : persoon.getIndicaties()) { // lazy loading... ind.getPersoon(); } } }
MinBZK/OperatieBRP
2013/brp 2013-02-07/BRP/branches/brp-stappen-refactoring/business/src/main/java/nl/bzk/brp/business/stappen/bevraging/OpvragenPersoonBerichtUitvoerStap.java
6,348
// bolie: tijdelijke hack, omdat we alles met lazy loading definieren, moeten we zorgen dat alle elementen
line_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.brp.business.stappen.bevraging; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.inject.Inject; import nl.bzk.brp.business.definities.impl.afstamming.KandidaatVader; import nl.bzk.brp.business.dto.BerichtContext; import nl.bzk.brp.business.dto.bevraging.AbstractBevragingsBericht; import nl.bzk.brp.business.dto.bevraging.OpvragenPersoonResultaat; import nl.bzk.brp.business.dto.bevraging.VraagDetailsPersoonBericht; import nl.bzk.brp.business.dto.bevraging.VraagKandidaatVaderBericht; import nl.bzk.brp.business.dto.bevraging.VraagPersonenOpAdresInclusiefBetrokkenhedenBericht; import nl.bzk.brp.business.dto.bevraging.zoekcriteria.ZoekCriteriaPersoonOpAdres; import nl.bzk.brp.business.stappen.AbstractBerichtVerwerkingsStap; import nl.bzk.brp.dataaccess.repository.PersoonRepository; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Datum; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisletter; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummer; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Huisnummertoevoeging; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Ja; import nl.bzk.brp.model.algemeen.attribuuttype.kern.Postcode; import nl.bzk.brp.model.algemeen.stamgegeven.ber.SoortMelding; import nl.bzk.brp.model.algemeen.stamgegeven.kern.Geslachtsaanduiding; import nl.bzk.brp.model.operationeel.kern.BetrokkenheidModel; import nl.bzk.brp.model.operationeel.kern.PersoonAdresModel; import nl.bzk.brp.model.operationeel.kern.PersoonIndicatieModel; import nl.bzk.brp.model.operationeel.kern.PersoonModel; import nl.bzk.brp.model.operationeel.kern.RelatieModel; import nl.bzk.brp.model.validatie.Melding; import nl.bzk.brp.model.validatie.MeldingCode; import nl.bzk.brp.util.AttribuutTypeUtil; import nl.bzk.brp.util.ObjectUtil; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; /** Uitvoer stap die het opvragen van een persoon afhandelt. De persoon wordt via de DAL laag opgehaald. */ public class OpvragenPersoonBerichtUitvoerStap extends AbstractBerichtVerwerkingsStap<AbstractBevragingsBericht, OpvragenPersoonResultaat> { @Inject private PersoonRepository persoonRepository; @Inject private KandidaatVader kandidaatVader; @Override public boolean voerVerwerkingsStapUitVoorBericht(final AbstractBevragingsBericht bericht, final BerichtContext context, final OpvragenPersoonResultaat resultaat) { boolean verwerkingsResultaat; if (bericht instanceof VraagDetailsPersoonBericht) { verwerkingsResultaat = vraagOpDetailPersoon((VraagDetailsPersoonBericht) bericht, resultaat); } else if (bericht instanceof VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) { verwerkingsResultaat = vraagOpPersonenOpAdresInclusiefBetrokkenheden( (VraagPersonenOpAdresInclusiefBetrokkenhedenBericht) bericht, resultaat); } else if (bericht instanceof VraagKandidaatVaderBericht) { verwerkingsResultaat = vraagOpKandidaatVader((VraagKandidaatVaderBericht) bericht, resultaat); } else { verwerkingsResultaat = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; } return verwerkingsResultaat; } /** * Methode om persoon details op te halen. * * @param bericht het VraagDetailsPersoonBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpDetailPersoon(final VraagDetailsPersoonBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean metHistorie = false; boolean inclFormeleHistorie = false; if (bericht.getVraag().getVraagOpties() != null) { if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieFormeel()) { metHistorie = true; inclFormeleHistorie = true; } else if (Ja.J == bericht.getVraag().getVraagOpties().getHistorieMaterieel()) { metHistorie = true; } } final PersoonModel gevondenPersoon = persoonRepository.haalPersoonOpMetBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (gevondenPersoon != null) { if (metHistorie) { persoonRepository.vulaanAdresMetHistorie(gevondenPersoon, inclFormeleHistorie); } // bolie: tijdelijke<SUF> // geladen moeten worden voordat de transactie afgelopen is. laadRelatiesPersoon(gevondenPersoon); laadPersoonIndicaties(gevondenPersoon); gevondenPersoon.getTechnischeSleutel(); resultaat.setGevondenPersonen(new HashSet<PersoonModel>()); resultaat.getGevondenPersonen().add(gevondenPersoon); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "burgerservicenummer")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * Methode om alle personen op te halen die op het adres zijn ingeschreven op basis van de vraag in het bericht. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht. * @param resultaat een set met gevonden personen. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpPersonenOpAdresInclusiefBetrokkenheden( final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht, final OpvragenPersoonResultaat resultaat) { List<PersoonModel> gevondenPersonen = new ArrayList<PersoonModel>(); if (isBsnCriteria(bericht)) { gevondenPersonen = persoonRepository.haalPersonenMetWoonAdresOpViaBurgerservicenummer(bericht.getVraag().getZoekCriteria() .getBurgerservicenummer()); if (CollectionUtils.isNotEmpty(gevondenPersonen) && CollectionUtils.isNotEmpty(gevondenPersonen.get(0).getAdressen())) { // Uitgaande van dat er maar 1 persoon terugkomt met bsn zoek vraag. // Uitgaande dat er er maar 1 woon adres aanwezig kan zijn. PersoonAdresModel persoonAdres = gevondenPersonen.get(0).getAdressen().iterator().next(); gevondenPersonen = haalAllePersonenOpMetAdres(persoonAdres); } } else if (isPostcodeCriteria(bericht)) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); gevondenPersonen = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(new Postcode(zoekCriteria.getPostcode()), new Huisnummer(zoekCriteria.getHuisnummer().toString()), new Huisletter(zoekCriteria.getHuisletter()), new Huisnummertoevoeging(zoekCriteria.getHuisnummertoevoeging())); } else if (isGemCodeCriteria(bericht)) { // TODO implementeer aanroep naar juiste methode om te zoeken met gemeente adres // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } else { // dummy statement ! voor sonar/findbugs/checktyle gevondenPersonen.isEmpty(); } // Alle null waardes er uit halen (kunnen voorkomen) gevondenPersonen.removeAll(Collections.singletonList(null)); if (CollectionUtils.isNotEmpty(gevondenPersonen)) { verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(gevondenPersonen); resultaat.setGevondenPersonen(new HashSet<PersoonModel>(gevondenPersonen)); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.ALG0001, "Er zijn geen personen gevonden die voldoen aan de opgegeven criteria.", bericht.getVraag() .getZoekCriteria(), "")); } return AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } /** * test of een persoon (betrokkene) in een list van personen bevindt. Er wordt alleen gekeken naar de persoon.id. * We kunnen niet zo maar .contains(object) gebruiker, omdat de lijst is een 'simpel persoon' en de betrokkene * een 'referentie persoon' is. * * @param gevondenPersonen de lijst van personen * @param betrokkene de betrokkene * @return true als deze in de lijst zit, false anders. */ private boolean isBetrokkeneInGevondenPersonen(final List<PersoonModel> gevondenPersonen, final PersoonModel betrokkene) { boolean resultaat = false; for (PersoonModel persoon : gevondenPersonen) { if (persoon.getID().equals(betrokkene.getID())) { resultaat = true; break; } } return resultaat; } /** * Deze methode schoont alle betrokkene van de gevonden personen die niet op dit adres wonen. * * @param gevondenPersonen de lijst van gevonden personen. */ private void verwijderAlleBetrokkeneNietWondendOpZelfdeAdres(final List<PersoonModel> gevondenPersonen) { for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { for (BetrokkenheidModel betrokkenheid : persoon.getBetrokkenheden()) { RelatieModel relatie = betrokkenheid.getRelatie(); // loop door een 'copy' omdat we anders een concurrent probleem hebben tijdens het verwijderen. List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(relatie.getBetrokkenheden()); for (BetrokkenheidModel bPartner : copy) { if (!isBetrokkeneInGevondenPersonen(gevondenPersonen, bPartner.getPersoon())) { relatie.getBetrokkenheden().remove(bPartner); } } } } } for (PersoonModel persoon : gevondenPersonen) { if (persoon.getBetrokkenheden() != null) { // We moeten nu opschonen, elk relatie dat slechts 1 'member' heeft gaat niet goed; want dat is // altijd de persoon himself. Verwijder de realtie EN daarmee de betrokkenheid. // for some reason, binding gaat fout met alleen 1-member link List<BetrokkenheidModel> copy = new ArrayList<BetrokkenheidModel>(persoon.getBetrokkenheden()); for (BetrokkenheidModel betrokkenheid : copy) { if (betrokkenheid.getRelatie().getBetrokkenheden().size() <= 1) { // relatie met 1 of minder betrkkenheden is geen relatie. verwijder deze (dus ook de // betrokkenheid. persoon.getBetrokkenheden().remove(betrokkenheid); } } } } } /** * Methode om alle personen op te halen die mogelijk de vader zou kunnen zijn . * * @param bericht het bericht * @param resultaat de lijst van personen die potentieel vader kunnen zijn. * @return een boolean die aangeeft of de stap succesvol is uitgevoerd (true) of niet (false). */ private boolean vraagOpKandidaatVader(final VraagKandidaatVaderBericht bericht, final OpvragenPersoonResultaat resultaat) { boolean retval = AbstractBerichtVerwerkingsStap.STOP_VERWERKING; PersoonModel moeder = persoonRepository.findByBurgerservicenummer(bericht.getVraag().getZoekCriteria().getBurgerservicenummer()); // deze validatie(s) zou eerder moeten gebeuren. if (moeder == null) { // TODO Foutmelding 'BSN onbekend', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "BSN is onbekend.", bericht .getVraag().getZoekCriteria(), "burgerservicenummer")); } else if (moeder.getGeslachtsaanduiding().getGeslachtsaanduiding() != Geslachtsaanduiding.VROUW) { // TODO Foutmelding 'BSN is geen Vrouw', moet aangemaakt worden, voorlopg een generieke resultaat.voegMeldingToe(new Melding(SoortMelding.FOUT, MeldingCode.ALG0001, "De persoon is niet van het vrouwelijk geslacht.", bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } else { List<PersoonModel> kandidatenVader = kandidaatVader .bepaalKandidatenVader(moeder, new Datum(bericht.getVraag().getZoekCriteria().getGeboortedatumKind())); if (!kandidatenVader.isEmpty()) { Set<PersoonModel> resultaten = new TreeSet<PersoonModel>(); resultaten.addAll(kandidatenVader); resultaat.setGevondenPersonen(resultaten); } else { resultaat.voegMeldingToe(new Melding(SoortMelding.INFORMATIE, MeldingCode.BRPUC50110, MeldingCode.BRPUC50110.getOmschrijving(), bericht.getVraag().getZoekCriteria(), "burgerservicenummer")); } retval = AbstractBerichtVerwerkingsStap.DOORGAAN_MET_VERWERKING; } return retval; } /** * Algoritme om alle personen op te halen die wonen op een adres. * <p/> * Zoekmethoden: 1. identificatiecodeNummeraanduiding 2. combinatie NaamOpenbareRuimte, Huisnummer, Huisletter, * HuisnummerToevoeging, LocatieOmschrijving, LocatieTOVAdres en Woonplaats gelijk zijn, mits NaamOpenbareRuimte, * Huisnummer en Woonplaats gevuld zijn 3. De combinatie Postcode, huisnummer, Huisletter en HuisnummerToevoeging * gelijk zijn, mits postcode en huis gevuld zijn. * <p/> * Wanneer met de ene methode niks gevonden wordt dan wordt de volgende methode uitgeprobeerd. * * @param persoonAdres PersistentPersoonAdres waarmee gezocht moet worden. * @return alle personen die op het adres wonen. * @brp.bedrijfsregel BRPUC50121 */ private List<PersoonModel> haalAllePersonenOpMetAdres(final PersoonAdresModel persoonAdres) { List<PersoonModel> resultaat = new ArrayList<PersoonModel>(); if (persoonAdres != null) { // Zoek verder met de PersistentPersoonAdres if (AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getIdentificatiecodeNummeraanduiding())) { // Zoeken met IdentificatiecodeNummeraanduiding resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaIdentificatiecodeNummeraanduiding(persoonAdres .getStandaard().getIdentificatiecodeNummeraanduiding()); // Resultaat moet op zijn minst de persoon zelf teruggeven. if (resultaat.size() < 2) { if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres .getStandaard().getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard() .getHuisnummertoevoeging()); } } } else if (isZoekbaarMetVolledigAdres(persoonAdres)) { // Zoeken met volledige adres resultaat = persoonRepository.haalPersonenMetWoonAdresOpViaVolledigAdres(persoonAdres.getStandaard() .getNaamOpenbareRuimte(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres .getStandaard().getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging(), persoonAdres.getStandaard().getWoonplaats(), persoonAdres.getStandaard().getGemeente()); if (resultaat.size() < 2 && isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } } else if (isZoekbaarMetOpPostcodeHuisnummer(persoonAdres)) { // Zoeken met postcode huisnummer resultaat = persoonRepository.haalPersonenOpMetAdresViaPostcodeHuisnummer(persoonAdres.getStandaard() .getPostcode(), persoonAdres.getStandaard().getHuisnummer(), persoonAdres.getStandaard() .getHuisletter(), persoonAdres.getStandaard().getHuisnummertoevoeging()); } else { resultaat.add(persoonAdres.getPersoon()); } } return resultaat; } /** * Controlleer of het om een bsn zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als alleen de BSN is ingevuld in het zoek bericht */ private boolean isBsnCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return AttribuutTypeUtil.isNotBlank(zoekCriteria.getBurgerservicenummer()) && ObjectUtil.isAllEmpty(zoekCriteria.getPostcode(), zoekCriteria.getHuisnummer(), zoekCriteria.getHuisletter(), zoekCriteria.getHuisnummertoevoeging(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een postcode zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om postcode huisnummer zoek criteria gaat */ private boolean isPostcodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return StringUtils.isNotBlank(zoekCriteria.getPostcode()) && zoekCriteria.getHuisnummer() != null && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getNaamOpenbareRuimte(), zoekCriteria.getGemeentecode()); } /** * Controlleer of het om een gemeente code zoek criteria gaat. * * @param bericht het VraagPersonenOpAdresInclusiefBetrokkenhedenBericht * @return true als het gaat om plaats adres huisnummer zoek criteria gaat */ private boolean isGemCodeCriteria(final VraagPersonenOpAdresInclusiefBetrokkenhedenBericht bericht) { ZoekCriteriaPersoonOpAdres zoekCriteria = bericht.getVraag().getZoekCriteria(); return zoekCriteria.getHuisnummer() != null && StringUtils.isNotBlank(zoekCriteria.getNaamOpenbareRuimte()) && StringUtils.isNotBlank(zoekCriteria.getGemeentecode()) && ObjectUtil.isAllEmpty(zoekCriteria.getBurgerservicenummer(), zoekCriteria.getPostcode()); } /** * Bepaalt of zoek opdracht met volledige adres uitgevoerd mag worden. Hier wordt gekeken of NaamOpenbareRuimte, * huisnummer en woonplaats is ingevuld. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als de genoemde velden gevuld zijn. */ private boolean isZoekbaarMetVolledigAdres(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getNaamOpenbareRuimte()) && persoonAdres.getStandaard().getHuisnummer() != null && persoonAdres.getStandaard().getHuisnummer().getWaarde() != null && persoonAdres.getStandaard().getWoonplaats() != null; } /** * Bepaalt of zoek opdracht met postcode en huisnummer uitgevoerd mag worden. Hier wordt gekeken naar postcode en * huisnummer. * * @param persoonAdres adres dat gecontrolleerd moet worden. * @return true als postcode en huisnummer zijn ingevuld. */ private boolean isZoekbaarMetOpPostcodeHuisnummer(final PersoonAdresModel persoonAdres) { return AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getPostcode()) && AttribuutTypeUtil.isNotBlank(persoonAdres.getStandaard().getHuisnummer()); } /** * Lazy loading, loop door de betrookenheden->relatie->betrokkenheden van de persoon. * @param persoon de persoon. */ private void laadRelatiesPersoon(final PersoonModel persoon) { for (BetrokkenheidModel betr : persoon.getBetrokkenheden()) { RelatieModel relatie = betr.getRelatie(); for (BetrokkenheidModel betrUitRelatie : relatie.getBetrokkenheden()) { if (betrUitRelatie != betr) { // lazy loading... betrUitRelatie.getPersoon().getTechnischeSleutel(); laadPersoonIndicaties(betrUitRelatie.getPersoon()); } } } } /** * Lazy loading, loop door de indicatie van de persoon. * @param persoon de persoon. */ private void laadPersoonIndicaties(final PersoonModel persoon) { for (PersoonIndicatieModel ind : persoon.getIndicaties()) { // lazy loading... ind.getPersoon(); } } }