lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
28c337c1434ab0a624eee18a72f933404ac94a85
0
google/blockly-android,rohlfingt/blockly-android,google/blockly-android,rohlfingt/blockly-android,rohlfingt/blockly-android,google/blockly-android
/* * Copyright 2015 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.blockly.ui; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import com.google.blockly.R; import com.google.blockly.control.ConnectionManager; import com.google.blockly.control.Dragger; import com.google.blockly.model.Block; import com.google.blockly.model.Connection; import com.google.blockly.model.Input; import com.google.blockly.model.WorkspacePoint; import java.util.ArrayList; import java.util.List; /** * Draws a block and handles laying out all its inputs/fields. */ public class BlockView extends FrameLayout { private static final String TAG = "BlockView"; // TODO: Replace these with dimens so they get scaled correctly // Minimum height of a block should be the same as an empty field. private static final int MIN_HEIGHT = InputView.MIN_HEIGHT; // Minimum width of a block should be the same as an empty field. private static final int MIN_WIDTH = InputView.MIN_WIDTH; // Color of block outline. private static final int OUTLINE_COLOR = Color.BLACK; private static final int HIGHLIGHT_COLOR = Color.YELLOW; private final WorkspaceHelper mHelper; private final Block mBlock; private final ConnectionManager mConnectionManager; private final Dragger mDragger; // Objects for drawing the block. private final Path mDrawPath = new Path(); private final Paint mAreaPaint = new Paint(); private final Paint mBorderPaint = new Paint(); private final Paint mHighlightPaint = new Paint(); private final Path mHighlightPath = new Path(); // Child views for the block inputs and their children. private final ArrayList<InputView> mInputViews = new ArrayList<>(); // Reference points for connectors relative to this view (needed for selective highlighting). private final ViewPoint mOutputConnectorOffset = new ViewPoint(); private final ViewPoint mPreviousConnectorOffset = new ViewPoint(); private final ViewPoint mNextConnectorOffset = new ViewPoint(); private final ArrayList<ViewPoint> mInputConnectorLocations = new ArrayList<>(); // Current measured size of this block view. private final ViewPoint mBlockViewSize = new ViewPoint(); // Position of the connection currently being updated, for temporary use during updateDrawPath. private final ViewPoint mTempConnectionPosition = new ViewPoint(); // Layout coordinates for inputs in this Block, so they don't have to be computed repeatedly. private final ArrayList<ViewPoint> mInputLayoutOrigins = new ArrayList<>(); // List of widths of multi-field rows when rendering inline inputs. private final ArrayList<Integer> mInlineRowWidth = new ArrayList<>(); private BlockWorkspaceParams mWorkspaceParams; // Fields for highlighting. private boolean mHighlightBlock; private Connection mHighlightConnection; // Offset of the block origin inside the view's measured area. private int mLayoutMarginLeft; private int mMaxInputFieldsWidth; private int mMaxStatementFieldsWidth; // Vertical offset for positioning the "Next" block (if one exists). private int mNextBlockVerticalOffset; // Width of the core "block", ie, rectangle box without connectors or inputs. private int mBlockWidth; // True while this instance is handling an active drag event. private boolean mHandlingEvent = false; private final WorkspacePoint mTempWorkspacePoint = new WorkspacePoint(); /** * Create a new BlockView for the given block using the workspace's style. * This constructor is for non-interactive display blocks. If this block is part of a * {@link Workspace} or (TODO linkify) Toolbox * {@link BlockView(Context, int, Block, WorkspaceHelper, BlockGroup, View.OnTouchListener)} * should be used instead. * * @param context The context for creating this view. * @param block The {@link Block} represented by this view. * @param helper The helper for loading workspace configs and doing calculations. * @param parentGroup The {@link BlockGroup} this view will live in. * @param connectionManager The {@link ConnectionManager} to update when moving connections. */ public BlockView(Context context, Block block, WorkspaceHelper helper, BlockGroup parentGroup, ConnectionManager connectionManager) { this(context, 0 /* default style */, block, helper, parentGroup, null, connectionManager); } /** * Create a new BlockView for the given block using the specified style. The style must extend * {@link R.style#DefaultBlockStyle}. * * @param context The context for creating this view. * @param blockStyle The resource id for the style to use on this view. * @param block The {@link Block} represented by this view. * @param helper The helper for loading workspace configs and doing calculations. * @param parentGroup The {@link BlockGroup} this view will live in. * @param dragger Helper object that handles dragging of this view. * @param connectionManager The {@link ConnectionManager} to update when moving connections. */ public BlockView(Context context, int blockStyle, Block block, WorkspaceHelper helper, BlockGroup parentGroup, Dragger dragger, ConnectionManager connectionManager) { super(context, null, 0); mBlock = block; mConnectionManager = connectionManager; mHelper = helper; mWorkspaceParams = new BlockWorkspaceParams(mBlock, mHelper); mDragger = dragger; parentGroup.addView(this); block.setView(this); setWillNotDraw(false); initViews(context, blockStyle, parentGroup); initDrawingObjects(context); } /** * @return The {@link InputView} for the {@link Input} at the given index. */ public InputView getInputView(int index) { return mInputViews.get(index); } /** * Select a connection for highlighted drawing. * * @param connection The connection whose port to highlight. This must be a connection * associated with the {@link Block} represented by this {@link BlockView} * instance. */ public void setHighlightConnection(Connection connection) { mHighlightBlock = false; mHighlightConnection = connection; invalidate(); } /** * Set highlighting of the entire block, including all inline Value input ports. */ public void setHighlightEntireBlock() { mHighlightBlock = true; mHighlightConnection = null; invalidate(); } /** * Clear all highlighting and return everything to normal rendering. */ public void clearHighlight() { mHighlightBlock = false; mHighlightConnection = null; invalidate(); } /** * Determine whether a {@link MotionEvent} should be handled by this view based on the * approximate area covered by this views visible parts. * * @param event The {@link MotionEvent} to check. * @return True if the event is a DOWN event and the coordinate of the motion event is on the * visible, non-transparent part of this view; false otherwise. Updates {@link #mHandlingEvent} * to avoid repeating the computation over the course of a move. */ public boolean shouldHandle(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { float eventX = event.getX(); float eventY = event.getY(); boolean rtl = mHelper.useRtL(); // First check whether event is in the general horizontal range of the block outline // (minus children) and exit if it is not. int blockBegin = rtl ? mBlockViewSize.x - mLayoutMarginLeft : mLayoutMarginLeft; int blockEnd = rtl ? mBlockViewSize.x - mBlockWidth : mBlockWidth; if (eventX < blockBegin || eventX > blockEnd) { return false; } // In the ballpark - now check whether event is on a field of any of this block's // inputs. If it is, then the event belongs to this BlockView, otherwise it does not. for (int i = 0; i < mInputViews.size(); ++i) { InputView inputView = mInputViews.get(i); if (inputView.isOnFields( eventX - inputView.getLeft(), eventY - inputView.getTop())) { mHandlingEvent = true; return true; } } } else if (event.getAction() == MotionEvent.ACTION_MOVE) { return mHandlingEvent; } else if (event.getAction() == MotionEvent.ACTION_UP) { mHandlingEvent = false; return true; } return false; } @Override public void onDraw(Canvas c) { c.drawPath(mDrawPath, mAreaPaint); c.drawPath(mDrawPath, mBorderPaint); drawHighlights(c); drawConnectorCenters(c); } @Override public boolean onTouchEvent(MotionEvent event) { return mDragger != null && shouldHandle(event) && mDragger.onTouch(this, event); } /** * Measure all children (i.e., block inputs) and compute their sizes and relative positions * for use in {@link #onLayout}. */ @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { adjustListSize(mInputLayoutOrigins); if (getBlock().getInputsInline()) { measureInlineInputs(widthMeasureSpec, heightMeasureSpec); } else { measureExternalInputs(widthMeasureSpec, heightMeasureSpec); } mNextBlockVerticalOffset = mBlockViewSize.y; if (mBlock.getNextConnection() != null) { mBlockViewSize.y += ConnectorHelper.SIZE_PERPENDICULAR; } if (mBlock.getOutputConnection() != null) { mLayoutMarginLeft = ConnectorHelper.SIZE_PERPENDICULAR; mBlockViewSize.x += mLayoutMarginLeft; } else { mLayoutMarginLeft = 0; } setMeasuredDimension(mBlockViewSize.x, mBlockViewSize.y); } @Override public void onLayout(boolean changed, int left, int top, int right, int bottom) { mHelper.getWorkspaceCoordinates(this, mTempWorkspacePoint); getBlock().setPosition(mTempWorkspacePoint.x, mTempWorkspacePoint.y); // Note that layout must be done regardless of the value of the "changed" parameter. boolean rtl = mHelper.useRtL(); int rtlSign = rtl ? -1 : +1; int xFrom = rtl ? mBlockViewSize.x - mLayoutMarginLeft : mLayoutMarginLeft; for (int i = 0; i < mInputViews.size(); i++) { int rowTop = mInputLayoutOrigins.get(i).y; InputView inputView = mInputViews.get(i); int inputViewWidth = inputView.getMeasuredWidth(); int rowFrom = xFrom + rtlSign * mInputLayoutOrigins.get(i).x; if (rtl) { rowFrom -= inputViewWidth; } inputView.layout(rowFrom, rowTop, rowFrom + inputViewWidth, rowTop + inputView.getMeasuredHeight()); } updateDrawPath(); } /** * @return The block for this view. */ public Block getBlock() { return mBlock; } /** * Correctly set the locations of the connections based on their offsets within the * {@link BlockView} and the position of the {@link BlockView} itself. Can be used when the * block has moved but not changed shape (e.g. during a drag). */ public void updateConnectorLocations() { final WorkspacePoint blockWorkspacePosition = mBlock.getPosition(); if (mBlock.getPreviousConnection() != null) { mHelper.viewToWorkspaceUnits(mPreviousConnectorOffset, mTempWorkspacePoint); mConnectionManager.moveConnectionTo(mBlock.getPreviousConnection(), blockWorkspacePosition, mTempWorkspacePoint); } if (mBlock.getNextConnection() != null) { mHelper.viewToWorkspaceUnits(mNextConnectorOffset, mTempWorkspacePoint); mConnectionManager.moveConnectionTo(mBlock.getNextConnection(), blockWorkspacePosition, mTempWorkspacePoint); } if (mBlock.getOutputConnection() != null) { mHelper.viewToWorkspaceUnits(mOutputConnectorOffset, mTempWorkspacePoint); mConnectionManager.moveConnectionTo(mBlock.getOutputConnection(), blockWorkspacePosition, mTempWorkspacePoint); } for (int i = 0; i < mInputViews.size(); i++) { InputView inputView = mInputViews.get(i); Connection conn = inputView.getInput().getConnection(); if (conn != null) { mHelper.viewToWorkspaceUnits(mInputConnectorLocations.get(i), mTempWorkspacePoint); mConnectionManager.moveConnectionTo(conn, blockWorkspacePosition, mTempWorkspacePoint); if (conn.isConnected()) { conn.getTargetBlock().getView().updateConnectorLocations(); } } } } /** * Draw highlights of block-level connections, or the entire block, if necessary. * * @param c The canvas to draw on. */ private void drawHighlights(Canvas c) { if (mHighlightBlock) { c.drawPath(mDrawPath, mHighlightPaint); } else if (mHighlightConnection != null) { int rtlSign = mHelper.useRtL() ? -1 : +1; if (mHighlightConnection == mBlock.getOutputConnection()) { ConnectorHelper.getOutputConnectorPath(rtlSign).offset( mOutputConnectorOffset.x, mOutputConnectorOffset.y, mHighlightPath); } else if (mHighlightConnection == mBlock.getPreviousConnection()) { ConnectorHelper.getPreviousConnectorPath(rtlSign).offset( mPreviousConnectorOffset.x, mPreviousConnectorOffset.y, mHighlightPath); } else if (mHighlightConnection == mBlock.getNextConnection()) { ConnectorHelper.getNextConnectorPath(rtlSign).offset( mNextConnectorOffset.x, mNextConnectorOffset.y, mHighlightPath); } else { // If the connection to highlight is not one of the three block-level connectors, // then it must be one of the inputs (either a "Next" connector for a Statement or // "Input" connector for a Value input). Figure out which input the connection // belongs to. final Input input = mHighlightConnection.getInput(); for (int i = 0; i < mInputViews.size(); ++i) { if (mInputViews.get(i).getInput() == input) { final ViewPoint offset = mInputConnectorLocations.get(i); if (input.getType() == Input.TYPE_STATEMENT) { ConnectorHelper.getNextConnectorPath(rtlSign) .offset(offset.x, offset.y, mHighlightPath); } else { ConnectorHelper.getValueInputConnectorPath(rtlSign) .offset(offset.x, offset.y, mHighlightPath); } break; // Break out of loop once connection has been found. } } } c.drawPath(mHighlightPath, mHighlightPaint); } } /** * Measure view and its children with inline inputs. * <p> * This function does not return a value but has the following side effects. Upon return: * <ol> * <li>The {@link InputView#measure(int, int)} method has been called for all inputs in * this block,</li> * <li>{@link #mBlockViewSize} contains the size of the total size of the block view * including all its inputs, and</li> * <li>{@link #mInputLayoutOrigins} contains the layout positions of all inputs within * the block.</li> * </ol> * </p> */ private void measureInlineInputs(int widthMeasureSpec, int heightMeasureSpec) { int inputViewsSize = mInputViews.size(); // First pass - measure all fields and inputs; compute maximum width of fields over all // Statement inputs. mMaxStatementFieldsWidth = 0; for (int i = 0; i < inputViewsSize; i++) { InputView inputView = mInputViews.get(i); inputView.measureFieldsAndInputs(widthMeasureSpec, heightMeasureSpec); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { mMaxStatementFieldsWidth = Math.max(mMaxStatementFieldsWidth, inputView.getTotalFieldWidth()); } } // Second pass - compute layout positions and sizes of all inputs. int rowLeft = 0; int rowTop = 0; int rowHeight = 0; int maxRowWidth = 0; mInlineRowWidth.clear(); for (int i = 0; i < inputViewsSize; i++) { InputView inputView = mInputViews.get(i); // If this is a Statement input, force its field width to be the maximum over all // Statements, and begin a new layout row. if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { // If the first input is a Statement, add vertical space for drawing connector top. if (i == 0) { rowTop += ConnectorHelper.STATEMENT_INPUT_BOTTOM_HEIGHT; } // Force all Statement inputs to have the same field width. inputView.setFieldLayoutWidth(mMaxStatementFieldsWidth); // New row BEFORE each Statement input. mInlineRowWidth.add(Math.max(rowLeft, mMaxStatementFieldsWidth + ConnectorHelper.STATEMENT_INPUT_INDENT_WIDTH)); rowTop += rowHeight; rowHeight = 0; rowLeft = 0; } mInputLayoutOrigins.get(i).set(rowLeft, rowTop); // Measure input view and update row height and width accordingly. inputView.measure(widthMeasureSpec, heightMeasureSpec); rowHeight = Math.max(rowHeight, inputView.getMeasuredHeight()); // Set row height for the current input view as maximum over all views in this row so // far. A separate, reverse loop below propagates the maximum to earlier inputs in the // same row. inputView.setRowHeight(rowHeight); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { // The block width is that of the widest row. maxRowWidth = Math.max(maxRowWidth, inputView.getMeasuredWidth()); // New row AFTER each Statement input. rowTop += rowHeight; rowLeft = 0; rowHeight = 0; } else { // For Dummy and Value inputs, row width accumulates. Update maximum width // accordingly. rowLeft += inputView.getMeasuredWidth(); maxRowWidth = Math.max(maxRowWidth, rowLeft); } } // Add height of final row. This is non-zero with inline inputs if the final input in the // block is not a Statement input. rowTop += rowHeight; // Third pass - propagate row height maximums backwards. Reset height whenever a Statement // input is encoutered. int maxRowHeight = 0; for (int i = inputViewsSize; i > 0; --i) { InputView inputView = mInputViews.get(i - 1); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { maxRowHeight = 0; } else { maxRowHeight = Math.max(maxRowHeight, inputView.getRowHeight()); inputView.setRowHeight(maxRowHeight); } } // If there was at least one Statement input, make sure block is wide enough to fit at least // an empty Statement connector. If there were non-empty Statement connectors, they were // already taken care of in the loop above. if (mMaxStatementFieldsWidth > 0) { maxRowWidth = Math.max(maxRowWidth, mMaxStatementFieldsWidth + ConnectorHelper.STATEMENT_INPUT_INDENT_WIDTH); } // Push width of last input row. mInlineRowWidth.add(Math.max(rowLeft, mMaxStatementFieldsWidth + ConnectorHelper.STATEMENT_INPUT_INDENT_WIDTH)); // Block width is the computed width of the widest input row, and at least MIN_WIDTH. mBlockViewSize.x = Math.max(MIN_WIDTH, maxRowWidth); mBlockWidth = mBlockViewSize.x; // Height is vertical position of next (non-existent) inputs row, and at least MIN_HEIGHT. mBlockViewSize.y = Math.max(MIN_HEIGHT, rowTop); } /** * Measure view and its children with external inputs. * <p> * This function does not return a value but has the following side effects. Upon return: * <ol> * <li>The {@link InputView#measure(int, int)} method has been called for all inputs in * this block,</li> * <li>{@link #mBlockViewSize} contains the size of the total size of the block view * including all its inputs, and</li> * <li>{@link #mInputLayoutOrigins} contains the layout positions of all inputs within * the block (but note that for external inputs, only the y coordinate of each * position is later used for positioning.)</li> * </ol> * </p> */ private void measureExternalInputs(int widthMeasureSpec, int heightMeasureSpec) { mMaxInputFieldsWidth = MIN_WIDTH; // Initialize max Statement width as zero so presence of Statement inputs can be determined // later; apply minimum size after that. mMaxStatementFieldsWidth = 0; int maxInputChildWidth = 0; int maxStatementChildWidth = 0; // First pass - measure fields and children of all inputs. boolean hasValueInput = false; for (int i = 0; i < mInputViews.size(); i++) { InputView inputView = mInputViews.get(i); inputView.measureFieldsAndInputs(widthMeasureSpec, heightMeasureSpec); switch (inputView.getInput().getType()) { case Input.TYPE_VALUE: { hasValueInput = true; maxInputChildWidth = Math.max(maxInputChildWidth, inputView.getTotalChildWidth()); // fall through } default: case Input.TYPE_DUMMY: { mMaxInputFieldsWidth = Math.max(mMaxInputFieldsWidth, inputView.getTotalFieldWidth()); break; } case Input.TYPE_STATEMENT: { mMaxStatementFieldsWidth = Math.max(mMaxStatementFieldsWidth, inputView.getTotalFieldWidth()); maxStatementChildWidth = Math.max(maxStatementChildWidth, inputView.getTotalChildWidth()); break; } } } // If there was a statement, force all other input fields to be at least as wide as required // by the Statement field plus port width. if (mMaxStatementFieldsWidth > 0) { mMaxStatementFieldsWidth = Math.max(mMaxStatementFieldsWidth, MIN_WIDTH); mMaxInputFieldsWidth = Math.max(mMaxInputFieldsWidth, mMaxStatementFieldsWidth + ConnectorHelper.STATEMENT_INPUT_INDENT_WIDTH); } // Second pass - force all inputs to render fields with the same width and compute positions // for all inputs. int rowTop = 0; for (int i = 0; i < mInputViews.size(); i++) { InputView inputView = mInputViews.get(i); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { // If the first input is a Statement, add vertical space for drawing connector top. if (i == 0) { rowTop += ConnectorHelper.STATEMENT_INPUT_BOTTOM_HEIGHT; } // Force all Statement inputs to have the same field width. inputView.setFieldLayoutWidth(mMaxStatementFieldsWidth); } else { // Force all Dummy and Value inputs to have the same field width. inputView.setFieldLayoutWidth(mMaxInputFieldsWidth); } inputView.measure(widthMeasureSpec, heightMeasureSpec); mInputLayoutOrigins.get(i).set(0, rowTop); // The block height is the sum of all the row heights. rowTop += inputView.getMeasuredHeight(); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { rowTop += ConnectorHelper.STATEMENT_INPUT_BOTTOM_HEIGHT; // Add bottom connector height to logical row height to make handling touch events // easier. inputView.setRowHeight(inputView.getMeasuredHeight() + ConnectorHelper.STATEMENT_INPUT_BOTTOM_HEIGHT); } } // Block width is the width of the longest row. Add space for connector if there is at least // one Value input. mBlockWidth = Math.max(mMaxInputFieldsWidth, mMaxStatementFieldsWidth); if (hasValueInput) { mBlockWidth += ConnectorHelper.SIZE_PERPENDICULAR; } // The width of the block view is the width of the block plus the maximum width of any of // its children. If there are no children, make sure view is at least as wide as the Block, // which accounts for width of unconnected input puts. mBlockViewSize.x = Math.max(mBlockWidth, Math.max(mMaxInputFieldsWidth + maxInputChildWidth, mMaxStatementFieldsWidth + maxStatementChildWidth)); mBlockViewSize.y = Math.max(MIN_HEIGHT, rowTop); } /** * A block is responsible for initializing the views all of its fields and sub-blocks, * meaning both inputs and next blocks. * * @param parentGroup The group the current block and all next blocks live in. */ private void initViews(Context context, int blockStyle, BlockGroup parentGroup) { List<Input> inputs = mBlock.getInputs(); for (int i = 0; i < inputs.size(); i++) { Input in = inputs.get(i); InputView inputView = new InputView(context, blockStyle, in, mHelper); mInputViews.add(inputView); addView(inputView); if (in.getType() != Input.TYPE_DUMMY && in.getConnection().getTargetBlock() != null) { // Blocks connected to inputs live in their own BlockGroups. BlockGroup bg = new BlockGroup(context, mHelper); mHelper.obtainBlockView(in.getConnection().getTargetBlock(), bg, mDragger, mConnectionManager); inputView.setChildView(bg); } } if (mBlock.getNextBlock() != null) { // Next blocks live in the same BlockGroup. mHelper.obtainBlockView(mBlock.getNextBlock(), parentGroup, mDragger, mConnectionManager); } } private void initDrawingObjects(Context context) { mAreaPaint.setColor(mBlock.getColour()); mAreaPaint.setStyle(Paint.Style.FILL); mAreaPaint.setStrokeJoin(Paint.Join.ROUND); mBorderPaint.setColor(OUTLINE_COLOR); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setStrokeWidth(1); mBorderPaint.setStrokeJoin(Paint.Join.ROUND); mHighlightPaint.setColor(HIGHLIGHT_COLOR); mHighlightPaint.setStyle(Paint.Style.STROKE); mHighlightPaint.setStrokeWidth(5); mHighlightPaint.setStrokeJoin(Paint.Join.ROUND); mDrawPath.setFillType(Path.FillType.EVEN_ODD); } /** * Adjust size of an {@link ArrayList} of {@link ViewPoint} objects to match the size of * {@link #mInputViews}. */ private void adjustListSize(ArrayList<ViewPoint> list) { if (list.size() != mInputViews.size()) { list.ensureCapacity(mInputViews.size()); if (list.size() < mInputViews.size()) { for (int i = list.size(); i < mInputViews.size(); i++) { list.add(new ViewPoint()); } } else { while (list.size() > mInputViews.size()) { list.remove(list.size() - 1); } } } } /** * Update path for drawing the block after view size or layout have changed. */ private void updateDrawPath() { // TODO(rohlfingt): refactor path drawing code to be more readable. (Will likely be // superseded by TODO: implement pretty block rendering.) mDrawPath.reset(); // Must reset(), not rewind(), to draw inline input cutouts correctly. adjustListSize(mInputConnectorLocations); int xFrom = mLayoutMarginLeft; int xTo = mLayoutMarginLeft; // For inline inputs, the upper horizontal coordinate of the block boundary varies by // section and changes after each Statement input. For external inputs, it is constant as // computed in measureExternalInputs. int inlineRowIdx = 0; if (mBlock.getInputsInline()) { xTo += mInlineRowWidth.get(inlineRowIdx); } else { xTo += mBlockWidth; } boolean rtl = mHelper.useRtL(); int rtlSign = rtl ? -1 : +1; // In right-to-left mode, mirror horizontal coordinates inside the measured view boundaries. if (rtl) { xFrom = mBlockViewSize.x - xFrom; xTo = mBlockViewSize.x - xTo; } int yTop = 0; int yBottom = mNextBlockVerticalOffset; // Top of the block, including "Previous" connector. mDrawPath.moveTo(xFrom, yTop); if (mBlock.getPreviousConnection() != null) { ConnectorHelper.addPreviousConnectorToPath(mDrawPath, xFrom, yTop, rtlSign); mPreviousConnectorOffset.set(xFrom, yTop); } mDrawPath.lineTo(xTo, yTop); // Right-hand side of the block, including "Input" connectors. for (int i = 0; i < mInputViews.size(); ++i) { InputView inputView = mInputViews.get(i); ViewPoint inputLayoutOrigin = mInputLayoutOrigins.get(i); switch (inputView.getInput().getType()) { default: case Input.TYPE_DUMMY: { break; } case Input.TYPE_VALUE: { if (!mBlock.getInputsInline()) { ConnectorHelper.addValueInputConnectorToPath( mDrawPath, xTo, inputLayoutOrigin.y, rtlSign); mInputConnectorLocations.get(i).set(xTo, inputLayoutOrigin.y); } break; } case Input.TYPE_STATEMENT: { int xOffset = xFrom + rtlSign * inputView.getFieldLayoutWidth(); int connectorHeight = inputView.getTotalChildHeight(); // For external inputs, the horizontal end coordinate of the connector bottom is // the same as the one on top. For inline inputs, however, it is the next entry // in the width-by-row table. int xToBottom = xTo; if (mBlock.getInputsInline()) { ++inlineRowIdx; xToBottom = mLayoutMarginLeft + mInlineRowWidth.get(inlineRowIdx); } ConnectorHelper.addStatementInputConnectorToPath(mDrawPath, xTo, xToBottom, inputLayoutOrigin.y, xOffset, connectorHeight, rtlSign); mInputConnectorLocations.get(i).set(xOffset, inputLayoutOrigin.y); // Set new horizontal end coordinate for subsequent inputs. xTo = xToBottom; break; } } } mDrawPath.lineTo(xTo, yBottom); // Bottom of the block, including "Next" connector. if (mBlock.getNextConnection() != null) { ConnectorHelper.addNextConnectorToPath(mDrawPath, xFrom, yBottom, rtlSign); mNextConnectorOffset.set(xFrom, yBottom); } mDrawPath.lineTo(xFrom, yBottom); // Left-hand side of the block, including "Output" connector. if (mBlock.getOutputConnection() != null) { ConnectorHelper.addOutputConnectorToPath(mDrawPath, xFrom, yTop, rtlSign); mOutputConnectorOffset.set(xFrom, yTop); } mDrawPath.lineTo(xFrom, yTop); // Draw an additional line segment over again to get a final rounded corner. mDrawPath.lineTo(xFrom + ConnectorHelper.OFFSET_FROM_CORNER, yTop); // Add cutout paths for "holes" from open inline Value inputs. if (mBlock.getInputsInline()) { for (int i = 0; i < mInputViews.size(); ++i) { InputView inputView = mInputViews.get(i); if (inputView.getInput().getType() == Input.TYPE_VALUE) { ViewPoint inputLayoutOrigin = mInputLayoutOrigins.get(i); inputView.addInlineCutoutToBlockViewPath(mDrawPath, xFrom + rtlSign * inputLayoutOrigin.x, inputLayoutOrigin.y, rtlSign, mTempConnectionPosition); mInputConnectorLocations.get(i).set( mTempConnectionPosition.x, mTempConnectionPosition.y); } } } updateConnectorLocations(); mDrawPath.close(); } /** * Draw green dots at the model's location of all connections on this block, for debugging. * * @param c The canvas to draw on. */ private void drawConnectorCenters(Canvas c) { List<Connection> connections = mBlock.getAllConnections(); Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); for (int i = 0; i < connections.size(); i++) { Connection conn = connections.get(i); if (conn.inDragMode()) { if (conn.isConnected()) { paint.setColor(Color.RED); } else { paint.setColor(Color.MAGENTA); } } else { if (conn.isConnected()) { paint.setColor(Color.GREEN); } else { paint.setColor(Color.CYAN); } } c.drawCircle( mHelper.workspaceToViewUnits(conn.getPosition().x - mBlock.getPosition().x), mHelper.workspaceToViewUnits(conn.getPosition().y - mBlock.getPosition().y), 10, paint); } } /** * @return Vertical offset for positioning the "Next" block (if one exists). This is relative to * the top of this view's area. */ int getNextBlockVerticalOffset() { return mNextBlockVerticalOffset; } /** * @return Layout margin on the left-hand side of the block (for optional Output connector). */ int getLayoutMarginLeft() { return mLayoutMarginLeft; } }
app/src/main/java/com/google/blockly/ui/BlockView.java
/* * Copyright 2015 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.blockly.ui; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; import com.google.blockly.R; import com.google.blockly.control.ConnectionManager; import com.google.blockly.control.Dragger; import com.google.blockly.model.Block; import com.google.blockly.model.Connection; import com.google.blockly.model.Input; import com.google.blockly.model.WorkspacePoint; import java.util.ArrayList; import java.util.List; /** * Draws a block and handles laying out all its inputs/fields. */ public class BlockView extends FrameLayout { private static final String TAG = "BlockView"; // TODO: Replace these with dimens so they get scaled correctly // Minimum height of a block should be the same as an empty field. private static final int MIN_HEIGHT = InputView.MIN_HEIGHT; // Minimum width of a block should be the same as an empty field. private static final int MIN_WIDTH = InputView.MIN_WIDTH; // Color of block outline. private static final int OUTLINE_COLOR = Color.BLACK; private static final int HIGHLIGHT_COLOR = Color.YELLOW; private final WorkspaceHelper mHelper; private final Block mBlock; private final ConnectionManager mConnectionManager; private final Dragger mDragger; // Objects for drawing the block. private final Path mDrawPath = new Path(); private final Paint mAreaPaint = new Paint(); private final Paint mBorderPaint = new Paint(); private final Paint mHighlightPaint = new Paint(); private final Path mHighlightPath = new Path(); // Child views for the block inputs and their children. private final ArrayList<InputView> mInputViews = new ArrayList<>(); // Reference points for connectors relative to this view (needed for selective highlighting). private final ViewPoint mOutputConnectorOffset = new ViewPoint(); private final ViewPoint mPreviousConnectorOffset = new ViewPoint(); private final ViewPoint mNextConnectorOffset = new ViewPoint(); private final ArrayList<ViewPoint> mInputConnectorLocations = new ArrayList<>(); // Current measured size of this block view. private final ViewPoint mBlockViewSize = new ViewPoint(); // Position of the connection currently being updated, for temporary use during updateDrawPath. private final ViewPoint mTempConnectionPosition = new ViewPoint(); // Layout coordinates for inputs in this Block, so they don't have to be computed repeatedly. private final ArrayList<ViewPoint> mInputLayoutOrigins = new ArrayList<>(); // List of widths of multi-field rows when rendering inline inputs. private final ArrayList<Integer> mInlineRowWidth = new ArrayList<>(); private BlockWorkspaceParams mWorkspaceParams; // Fields for highlighting. private boolean mHighlightBlock; private Connection mHighlightConnection; // Offset of the block origin inside the view's measured area. private int mLayoutMarginLeft; private int mMaxInputFieldsWidth; private int mMaxStatementFieldsWidth; // Vertical offset for positioning the "Next" block (if one exists). private int mNextBlockVerticalOffset; // Width of the core "block", ie, rectangle box without connectors or inputs. private int mBlockWidth; // True while this instance is handling an active drag event. private boolean mHandlingEvent = false; private final WorkspacePoint mTempWorkspacePoint = new WorkspacePoint(); /** * Create a new BlockView for the given block using the workspace's style. * This constructor is for non-interactive display blocks. If this block is part of a * {@link Workspace} or (TODO linkify) Toolbox * {@link BlockView(Context, int, Block, WorkspaceHelper, BlockGroup, View.OnTouchListener)} * should be used instead. * * @param context The context for creating this view. * @param block The {@link Block} represented by this view. * @param helper The helper for loading workspace configs and doing calculations. * @param parentGroup The {@link BlockGroup} this view will live in. * @param connectionManager The {@link ConnectionManager} to update when moving connections. */ public BlockView(Context context, Block block, WorkspaceHelper helper, BlockGroup parentGroup, ConnectionManager connectionManager) { this(context, 0 /* default style */, block, helper, parentGroup, null, connectionManager); } /** * Create a new BlockView for the given block using the specified style. The style must extend * {@link R.style#DefaultBlockStyle}. * * @param context The context for creating this view. * @param blockStyle The resource id for the style to use on this view. * @param block The {@link Block} represented by this view. * @param helper The helper for loading workspace configs and doing calculations. * @param parentGroup The {@link BlockGroup} this view will live in. * @param dragger Helper object that handles dragging of this view. * @param connectionManager The {@link ConnectionManager} to update when moving connections. */ public BlockView(Context context, int blockStyle, Block block, WorkspaceHelper helper, BlockGroup parentGroup, Dragger dragger, ConnectionManager connectionManager) { super(context, null, 0); mBlock = block; mConnectionManager = connectionManager; mHelper = helper; mWorkspaceParams = new BlockWorkspaceParams(mBlock, mHelper); mDragger = dragger; parentGroup.addView(this); block.setView(this); setWillNotDraw(false); initViews(context, blockStyle, parentGroup); initDrawingObjects(context); } /** * @return The {@link InputView} for the {@link Input} at the given index. */ public InputView getInputView(int index) { return mInputViews.get(index); } /** * Select a connection for highlighted drawing. * * @param connection The connection whose port to highlight. This must be a connection * associated with the {@link Block} represented by this {@link BlockView} * instance. */ public void setHighlightConnection(Connection connection) { mHighlightBlock = false; mHighlightConnection = connection; invalidate(); } /** * Set highlighting of the entire block, including all inline Value input ports. */ public void setHighlightEntireBlock() { mHighlightBlock = true; mHighlightConnection = null; invalidate(); } /** * Clear all highlighting and return everything to normal rendering. */ public void clearHighlight() { mHighlightBlock = false; mHighlightConnection = null; invalidate(); } /** * Determine whether a {@link MotionEvent} should be handled by this view based on the * approximate area covered by this views visible parts. * * @param event The {@link MotionEvent} to check. * @return True if the event is a DOWN event and the coordinate of the motion event is on the * visible, non-transparent part of this view; false otherwise. Updates {@link #mHandlingEvent} * to avoid repeating the computation over the course of a move. */ public boolean shouldHandle(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { float eventX = event.getX(); float eventY = event.getY(); boolean rtl = mHelper.useRtL(); // First check whether event is in the general horizontal range of the block outline // (minus children) and exit if it is not. int blockBegin = rtl ? mBlockViewSize.x - mLayoutMarginLeft : mLayoutMarginLeft; int blockEnd = rtl ? mBlockViewSize.x - mBlockWidth : mBlockWidth; if (eventX < blockBegin || eventX > blockEnd) { return false; } // In the ballpark - now check whether event is on a field of any of this block's // inputs. If it is, then the event belongs to this BlockView, otherwise it does not. for (int i = 0; i < mInputViews.size(); ++i) { InputView inputView = mInputViews.get(i); if (inputView.isOnFields( eventX - inputView.getLeft(), eventY - inputView.getTop())) { mHandlingEvent = true; return true; } } } else if (event.getAction() == MotionEvent.ACTION_MOVE) { return mHandlingEvent; } else if (event.getAction() == MotionEvent.ACTION_UP) { mHandlingEvent = false; return true; } return false; } @Override public void onDraw(Canvas c) { c.drawPath(mDrawPath, mAreaPaint); c.drawPath(mDrawPath, mBorderPaint); drawHighlights(c); drawConnectorCenters(c); } @Override public boolean onTouchEvent(MotionEvent event) { return mDragger != null && shouldHandle(event) && mDragger.onTouch(this, event); } /** * Measure all children (i.e., block inputs) and compute their sizes and relative positions * for use in {@link #onLayout}. */ @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { adjustListSize(mInputLayoutOrigins); if (getBlock().getInputsInline()) { measureInlineInputs(widthMeasureSpec, heightMeasureSpec); } else { measureExternalInputs(widthMeasureSpec, heightMeasureSpec); } mNextBlockVerticalOffset = mBlockViewSize.y; if (mBlock.getNextConnection() != null) { mBlockViewSize.y += ConnectorHelper.SIZE_PERPENDICULAR; } if (mBlock.getOutputConnection() != null) { mLayoutMarginLeft = ConnectorHelper.SIZE_PERPENDICULAR; mBlockViewSize.x += mLayoutMarginLeft; } else { mLayoutMarginLeft = 0; } setMeasuredDimension(mBlockViewSize.x, mBlockViewSize.y); } @Override public void onLayout(boolean changed, int left, int top, int right, int bottom) { mHelper.getWorkspaceCoordinates(this, mTempWorkspacePoint); getBlock().setPosition(mTempWorkspacePoint.x, mTempWorkspacePoint.y); // Note that layout must be done regardless of the value of the "changed" parameter. boolean rtl = mHelper.useRtL(); int rtlSign = rtl ? -1 : +1; int xFrom = rtl ? mBlockViewSize.x - mLayoutMarginLeft : mLayoutMarginLeft; for (int i = 0; i < mInputViews.size(); i++) { int rowTop = mInputLayoutOrigins.get(i).y; InputView inputView = mInputViews.get(i); int inputViewWidth = inputView.getMeasuredWidth(); int rowFrom = xFrom + rtlSign * mInputLayoutOrigins.get(i).x; if (rtl) { rowFrom -= inputViewWidth; } inputView.layout(rowFrom, rowTop, rowFrom + inputViewWidth, rowTop + inputView.getMeasuredHeight()); } updateDrawPath(); } /** * @return The block for this view. */ public Block getBlock() { return mBlock; } /** * Correctly set the locations of the connections based on their offsets within the * {@link BlockView} and the position of the {@link BlockView} itself. Can be used when the * block has moved but not changed shape (e.g. during a drag). */ public void updateConnectorLocations() { final WorkspacePoint blockWorkspacePosition = mBlock.getPosition(); if (mBlock.getPreviousConnection() != null) { mHelper.viewToWorkspaceUnits(mPreviousConnectorOffset, mTempWorkspacePoint); mConnectionManager.moveConnectionTo(mBlock.getPreviousConnection(), blockWorkspacePosition, mTempWorkspacePoint); } if (mBlock.getNextConnection() != null) { mHelper.viewToWorkspaceUnits(mNextConnectorOffset, mTempWorkspacePoint); mConnectionManager.moveConnectionTo(mBlock.getNextConnection(), blockWorkspacePosition, mTempWorkspacePoint); } if (mBlock.getOutputConnection() != null) { mHelper.viewToWorkspaceUnits(mOutputConnectorOffset, mTempWorkspacePoint); mConnectionManager.moveConnectionTo(mBlock.getOutputConnection(), blockWorkspacePosition, mTempWorkspacePoint); } for (int i = 0; i < mInputViews.size(); i++) { InputView inputView = mInputViews.get(i); Connection conn = inputView.getInput().getConnection(); if (conn != null) { mHelper.viewToWorkspaceUnits(mInputConnectorLocations.get(i), mTempWorkspacePoint); mConnectionManager.moveConnectionTo(conn, blockWorkspacePosition, mTempWorkspacePoint); if (conn.isConnected()) { conn.getTargetBlock().getView().updateConnectorLocations(); } } } } /** * Draw highlights of block-level connections, or the entire block, if necessary. * * @param c The canvas to draw on. */ private void drawHighlights(Canvas c) { if (mHighlightBlock) { c.drawPath(mDrawPath, mHighlightPaint); } else if (mHighlightConnection != null) { int rtlSign = mHelper.useRtL() ? -1 : +1; if (mHighlightConnection == mBlock.getOutputConnection()) { ConnectorHelper.getOutputConnectorPath(rtlSign).offset( mOutputConnectorOffset.x, mOutputConnectorOffset.y, mHighlightPath); } else if (mHighlightConnection == mBlock.getPreviousConnection()) { ConnectorHelper.getPreviousConnectorPath(rtlSign).offset( mPreviousConnectorOffset.x, mPreviousConnectorOffset.y, mHighlightPath); } else if (mHighlightConnection == mBlock.getNextConnection()) { ConnectorHelper.getNextConnectorPath(rtlSign).offset( mNextConnectorOffset.x, mNextConnectorOffset.y, mHighlightPath); } else { // If the connection to highlight is not one of the three block-level connectors, // then it must be one of the inputs (either a "Next" connector for a Statement or // "Input" connector for a Value input). Figure out which input the connection // belongs to. final Input input = mHighlightConnection.getInput(); for (int i = 0; i < mInputViews.size(); ++i) { if (mInputViews.get(i).getInput() == input) { final ViewPoint offset = mInputConnectorLocations.get(i); if (input.getType() == Input.TYPE_STATEMENT) { ConnectorHelper.getNextConnectorPath(rtlSign) .offset(offset.x, offset.y, mHighlightPath); } else { ConnectorHelper.getValueInputConnectorPath(rtlSign) .offset(offset.x, offset.y, mHighlightPath); } break; // Break out of loop once connection has been found. } } } c.drawPath(mHighlightPath, mHighlightPaint); } } /** * Measure view and its children with inline inputs. * <p> * This function does not return a value but has the following side effects. Upon return: * <ol> * <li>The {@link InputView#measure(int, int)} method has been called for all inputs in * this block,</li> * <li>{@link #mBlockViewSize} contains the size of the total size of the block view * including all its inputs, and</li> * <li>{@link #mInputLayoutOrigins} contains the layout positions of all inputs within * the block.</li> * </ol> * </p> */ private void measureInlineInputs(int widthMeasureSpec, int heightMeasureSpec) { int inputViewsSize = mInputViews.size(); // First pass - measure all fields and inputs; compute maximum width of fields over all // Statement inputs. mMaxStatementFieldsWidth = 0; for (int i = 0; i < inputViewsSize; i++) { InputView inputView = mInputViews.get(i); inputView.measureFieldsAndInputs(widthMeasureSpec, heightMeasureSpec); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { mMaxStatementFieldsWidth = Math.max(mMaxStatementFieldsWidth, inputView.getTotalFieldWidth()); } } // Second pass - compute layout positions and sizes of all inputs. int rowLeft = 0; int rowTop = 0; int rowHeight = 0; int maxRowWidth = 0; mInlineRowWidth.clear(); for (int i = 0; i < inputViewsSize; i++) { InputView inputView = mInputViews.get(i); // If this is a Statement input, force its field width to be the maximum over all // Statements, and begin a new layout row. if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { // If the first input is a Statement, add vertical space for drawing connector top. if (i == 0) { rowTop += ConnectorHelper.STATEMENT_INPUT_BOTTOM_HEIGHT; } // Force all Statement inputs to have the same field width. inputView.setFieldLayoutWidth(mMaxStatementFieldsWidth); // New row BEFORE each Statement input. mInlineRowWidth.add(Math.max(rowLeft, mMaxStatementFieldsWidth + ConnectorHelper.STATEMENT_INPUT_INDENT_WIDTH)); rowTop += rowHeight; rowHeight = 0; rowLeft = 0; } mInputLayoutOrigins.get(i).set(rowLeft, rowTop); // Measure input view and update row height and width accordingly. inputView.measure(widthMeasureSpec, heightMeasureSpec); rowHeight = Math.max(rowHeight, inputView.getMeasuredHeight()); // Set row height for the current input view as maximum over all views in this row so // far. A separate, reverse loop below propagates the maximum to earlier inputs in the // same row. inputView.setRowHeight(rowHeight); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { // The block width is that of the widest row. maxRowWidth = Math.max(maxRowWidth, inputView.getMeasuredWidth()); // New row AFTER each Statement input. rowTop += rowHeight; rowLeft = 0; rowHeight = 0; } else { // For Dummy and Value inputs, row width accumulates. Update maximum width // accordingly. rowLeft += inputView.getMeasuredWidth(); maxRowWidth = Math.max(maxRowWidth, rowLeft); } } // Add height of final row. This is non-zero with inline inputs if the final input in the // block is not a Statement input. rowTop += rowHeight; // Third pass - propagate row height maximums backwards. Reset height whenever a Statement // input is encoutered. int maxRowHeight = 0; for (int i = inputViewsSize; i > 0; --i) { InputView inputView = mInputViews.get(i - 1); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { maxRowHeight = 0; } else { maxRowHeight = Math.max(maxRowHeight, inputView.getRowHeight()); inputView.setRowHeight(maxRowHeight); } } // If there was at least one Statement input, make sure block is wide enough to fit at least // an empty Statement connector. If there were non-empty Statement connectors, they were // already taken care of in the loop above. if (mMaxStatementFieldsWidth > 0) { maxRowWidth = Math.max(maxRowWidth, mMaxStatementFieldsWidth + ConnectorHelper.STATEMENT_INPUT_INDENT_WIDTH); } // Push width of last input row. mInlineRowWidth.add(Math.max(rowLeft, mMaxStatementFieldsWidth + ConnectorHelper.STATEMENT_INPUT_INDENT_WIDTH)); // Block width is the computed width of the widest input row, and at least MIN_WIDTH. mBlockViewSize.x = Math.max(MIN_WIDTH, maxRowWidth); mBlockWidth = mBlockViewSize.x; // Height is vertical position of next (non-existent) inputs row, and at least MIN_HEIGHT. mBlockViewSize.y = Math.max(MIN_HEIGHT, rowTop); } /** * Measure view and its children with external inputs. * <p> * This function does not return a value but has the following side effects. Upon return: * <ol> * <li>The {@link InputView#measure(int, int)} method has been called for all inputs in * this block,</li> * <li>{@link #mBlockViewSize} contains the size of the total size of the block view * including all its inputs, and</li> * <li>{@link #mInputLayoutOrigins} contains the layout positions of all inputs within * the block (but note that for external inputs, only the y coordinate of each * position is later used for positioning.)</li> * </ol> * </p> */ private void measureExternalInputs(int widthMeasureSpec, int heightMeasureSpec) { mMaxInputFieldsWidth = MIN_WIDTH; // Initialize max Statement width as zero so presence of Statement inputs can be determined // later; apply minimum size after that. mMaxStatementFieldsWidth = 0; int maxInputChildWidth = 0; int maxStatementChildWidth = 0; // First pass - measure fields and children of all inputs. boolean hasValueInput = false; for (int i = 0; i < mInputViews.size(); i++) { InputView inputView = mInputViews.get(i); inputView.measureFieldsAndInputs(widthMeasureSpec, heightMeasureSpec); switch (inputView.getInput().getType()) { case Input.TYPE_VALUE: { hasValueInput = true; maxInputChildWidth = Math.max(maxInputChildWidth, inputView.getTotalChildWidth()); // fall through } default: case Input.TYPE_DUMMY: { mMaxInputFieldsWidth = Math.max(mMaxInputFieldsWidth, inputView.getTotalFieldWidth()); break; } case Input.TYPE_STATEMENT: { mMaxStatementFieldsWidth = Math.max(mMaxStatementFieldsWidth, inputView.getTotalFieldWidth()); maxStatementChildWidth = Math.max(maxStatementChildWidth, inputView.getTotalChildWidth()); break; } } } // If there was a statement, force all other input fields to be at least as wide as required // by the Statement field plus port width. if (mMaxStatementFieldsWidth > 0) { mMaxStatementFieldsWidth = Math.max(mMaxStatementFieldsWidth, MIN_WIDTH); mMaxInputFieldsWidth = Math.max(mMaxInputFieldsWidth, mMaxStatementFieldsWidth + ConnectorHelper.STATEMENT_INPUT_INDENT_WIDTH); } // Second pass - force all inputs to render fields with the same width and compute positions // for all inputs. int rowTop = 0; for (int i = 0; i < mInputViews.size(); i++) { InputView inputView = mInputViews.get(i); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { // If the first input is a Statement, add vertical space for drawing connector top. if (i == 0) { rowTop += ConnectorHelper.STATEMENT_INPUT_BOTTOM_HEIGHT; } // Force all Statement inputs to have the same field width. inputView.setFieldLayoutWidth(mMaxStatementFieldsWidth); } else { // Force all Dummy and Value inputs to have the same field width. inputView.setFieldLayoutWidth(mMaxInputFieldsWidth); } inputView.measure(widthMeasureSpec, heightMeasureSpec); mInputLayoutOrigins.get(i).set(0, rowTop); // The block height is the sum of all the row heights. rowTop += inputView.getMeasuredHeight(); if (inputView.getInput().getType() == Input.TYPE_STATEMENT) { rowTop += ConnectorHelper.STATEMENT_INPUT_BOTTOM_HEIGHT; // Add bottom connector height to logical row height to make handling touch events // easier. inputView.setRowHeight(inputView.getMeasuredHeight() + ConnectorHelper.STATEMENT_INPUT_BOTTOM_HEIGHT); } } // Block width is the width of the longest row. Add space for connector if there is at least // one Value input. mBlockWidth = Math.max(mMaxInputFieldsWidth, mMaxStatementFieldsWidth); if (hasValueInput) { mBlockWidth += ConnectorHelper.SIZE_PERPENDICULAR; } // The width of the block view is the width of the block plus the maximum width of any of // its children. If there are no children, make sure view is at least as wide as the Block, // which accounts for width of unconnected input puts. mBlockViewSize.x = Math.max(mBlockWidth, Math.max(mMaxInputFieldsWidth + maxInputChildWidth, mMaxStatementFieldsWidth + maxStatementChildWidth)); mBlockViewSize.y = Math.max(MIN_HEIGHT, rowTop); } /** * A block is responsible for initializing the views all of its fields and sub-blocks, * meaning both inputs and next blocks. * * @param parentGroup The group the current block and all next blocks live in. */ private void initViews(Context context, int blockStyle, BlockGroup parentGroup) { List<Input> inputs = mBlock.getInputs(); for (int i = 0; i < inputs.size(); i++) { Input in = inputs.get(i); InputView inputView = new InputView(context, blockStyle, in, mHelper); mInputViews.add(inputView); addView(inputView); if (in.getType() != Input.TYPE_DUMMY && in.getConnection().getTargetBlock() != null) { // Blocks connected to inputs live in their own BlockGroups. BlockGroup bg = new BlockGroup(context, mHelper); mHelper.obtainBlockView(in.getConnection().getTargetBlock(), bg, mDragger, mConnectionManager); inputView.setChildView(bg); } } if (mBlock.getNextBlock() != null) { // Next blocks live in the same BlockGroup. mHelper.obtainBlockView(mBlock.getNextBlock(), parentGroup, mDragger, mConnectionManager); } } private void initDrawingObjects(Context context) { mAreaPaint.setColor(mBlock.getColour()); mAreaPaint.setStyle(Paint.Style.FILL); mAreaPaint.setStrokeJoin(Paint.Join.ROUND); mBorderPaint.setColor(OUTLINE_COLOR); mBorderPaint.setStyle(Paint.Style.STROKE); mBorderPaint.setStrokeWidth(1); mBorderPaint.setStrokeJoin(Paint.Join.ROUND); mHighlightPaint.setColor(HIGHLIGHT_COLOR); mHighlightPaint.setStyle(Paint.Style.STROKE); mHighlightPaint.setStrokeWidth(5); mHighlightPaint.setStrokeJoin(Paint.Join.ROUND); mDrawPath.setFillType(Path.FillType.EVEN_ODD); } /** * Adjust size of an {@link ArrayList} of {@link ViewPoint} objects to match the size of * {@link #mInputViews}. */ private void adjustListSize(ArrayList<ViewPoint> list) { if (list.size() != mInputViews.size()) { list.ensureCapacity(mInputViews.size()); if (list.size() < mInputViews.size()) { for (int i = list.size(); i < mInputViews.size(); i++) { list.add(new ViewPoint()); } } else { while (list.size() > mInputViews.size()) { list.remove(list.size() - 1); } } } } /** * Update path for drawing the block after view size or layout have changed. */ private void updateDrawPath() { Log.d(TAG, "Updating draw path and repositioning connections"); // TODO(rohlfingt): refactor path drawing code to be more readable. (Will likely be // superseded by TODO: implement pretty block rendering.) mDrawPath.reset(); // Must reset(), not rewind(), to draw inline input cutouts correctly. adjustListSize(mInputConnectorLocations); int xFrom = mLayoutMarginLeft; int xTo = mLayoutMarginLeft; // For inline inputs, the upper horizontal coordinate of the block boundary varies by // section and changes after each Statement input. For external inputs, it is constant as // computed in measureExternalInputs. int inlineRowIdx = 0; if (mBlock.getInputsInline()) { xTo += mInlineRowWidth.get(inlineRowIdx); } else { xTo += mBlockWidth; } boolean rtl = mHelper.useRtL(); int rtlSign = rtl ? -1 : +1; // In right-to-left mode, mirror horizontal coordinates inside the measured view boundaries. if (rtl) { xFrom = mBlockViewSize.x - xFrom; xTo = mBlockViewSize.x - xTo; } int yTop = 0; int yBottom = mNextBlockVerticalOffset; // Top of the block, including "Previous" connector. mDrawPath.moveTo(xFrom, yTop); if (mBlock.getPreviousConnection() != null) { ConnectorHelper.addPreviousConnectorToPath(mDrawPath, xFrom, yTop, rtlSign); mPreviousConnectorOffset.set(xFrom, yTop); } mDrawPath.lineTo(xTo, yTop); // Right-hand side of the block, including "Input" connectors. for (int i = 0; i < mInputViews.size(); ++i) { InputView inputView = mInputViews.get(i); ViewPoint inputLayoutOrigin = mInputLayoutOrigins.get(i); switch (inputView.getInput().getType()) { default: case Input.TYPE_DUMMY: { break; } case Input.TYPE_VALUE: { if (!mBlock.getInputsInline()) { ConnectorHelper.addValueInputConnectorToPath( mDrawPath, xTo, inputLayoutOrigin.y, rtlSign); mInputConnectorLocations.get(i).set(xTo, inputLayoutOrigin.y); } break; } case Input.TYPE_STATEMENT: { int xOffset = xFrom + rtlSign * inputView.getFieldLayoutWidth(); int connectorHeight = inputView.getTotalChildHeight(); // For external inputs, the horizontal end coordinate of the connector bottom is // the same as the one on top. For inline inputs, however, it is the next entry // in the width-by-row table. int xToBottom = xTo; if (mBlock.getInputsInline()) { ++inlineRowIdx; xToBottom = mLayoutMarginLeft + mInlineRowWidth.get(inlineRowIdx); } ConnectorHelper.addStatementInputConnectorToPath(mDrawPath, xTo, xToBottom, inputLayoutOrigin.y, xOffset, connectorHeight, rtlSign); mInputConnectorLocations.get(i).set(xOffset, inputLayoutOrigin.y); // Set new horizontal end coordinate for subsequent inputs. xTo = xToBottom; break; } } } mDrawPath.lineTo(xTo, yBottom); // Bottom of the block, including "Next" connector. if (mBlock.getNextConnection() != null) { ConnectorHelper.addNextConnectorToPath(mDrawPath, xFrom, yBottom, rtlSign); mNextConnectorOffset.set(xFrom, yBottom); } mDrawPath.lineTo(xFrom, yBottom); // Left-hand side of the block, including "Output" connector. if (mBlock.getOutputConnection() != null) { ConnectorHelper.addOutputConnectorToPath(mDrawPath, xFrom, yTop, rtlSign); mOutputConnectorOffset.set(xFrom, yTop); } mDrawPath.lineTo(xFrom, yTop); // Draw an additional line segment over again to get a final rounded corner. mDrawPath.lineTo(xFrom + ConnectorHelper.OFFSET_FROM_CORNER, yTop); // Add cutout paths for "holes" from open inline Value inputs. if (mBlock.getInputsInline()) { for (int i = 0; i < mInputViews.size(); ++i) { InputView inputView = mInputViews.get(i); if (inputView.getInput().getType() == Input.TYPE_VALUE) { ViewPoint inputLayoutOrigin = mInputLayoutOrigins.get(i); inputView.addInlineCutoutToBlockViewPath(mDrawPath, xFrom + rtlSign * inputLayoutOrigin.x, inputLayoutOrigin.y, rtlSign, mTempConnectionPosition); mInputConnectorLocations.get(i).set( mTempConnectionPosition.x, mTempConnectionPosition.y); } } } updateConnectorLocations(); mDrawPath.close(); } /** * Draw green dots at the model's location of all connections on this block, for debugging. * * @param c The canvas to draw on. */ private void drawConnectorCenters(Canvas c) { List<Connection> connections = mBlock.getAllConnections(); Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); for (int i = 0; i < connections.size(); i++) { Connection conn = connections.get(i); if (conn.inDragMode()) { if (conn.isConnected()) { paint.setColor(Color.RED); } else { paint.setColor(Color.MAGENTA); } } else { if (conn.isConnected()) { paint.setColor(Color.GREEN); } else { paint.setColor(Color.CYAN); } } c.drawCircle( mHelper.workspaceToViewUnits(conn.getPosition().x - mBlock.getPosition().x), mHelper.workspaceToViewUnits(conn.getPosition().y - mBlock.getPosition().y), 10, paint); } } /** * @return Vertical offset for positioning the "Next" block (if one exists). This is relative to * the top of this view's area. */ int getNextBlockVerticalOffset() { return mNextBlockVerticalOffset; } /** * @return Layout margin on the left-hand side of the block (for optional Output connector). */ int getLayoutMarginLeft() { return mLayoutMarginLeft; } }
Removed obsolete Log()
app/src/main/java/com/google/blockly/ui/BlockView.java
Removed obsolete Log()
<ide><path>pp/src/main/java/com/google/blockly/ui/BlockView.java <ide> import android.graphics.Color; <ide> import android.graphics.Paint; <ide> import android.graphics.Path; <del>import android.util.Log; <ide> import android.view.MotionEvent; <ide> import android.view.View; <ide> import android.widget.FrameLayout; <ide> * Update path for drawing the block after view size or layout have changed. <ide> */ <ide> private void updateDrawPath() { <del> Log.d(TAG, "Updating draw path and repositioning connections"); <ide> // TODO(rohlfingt): refactor path drawing code to be more readable. (Will likely be <ide> // superseded by TODO: implement pretty block rendering.) <ide> mDrawPath.reset(); // Must reset(), not rewind(), to draw inline input cutouts correctly.
Java
apache-2.0
d3f2549011e7dc6af802d74375f9745fc505d8e0
0
kelemen/JTrim,kelemen/JTrim
package org.jtrim.access; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jtrim.cancel.CancellationToken; import org.jtrim.collections.RefCollection; import org.jtrim.collections.RefLinkedList; import org.jtrim.concurrent.CancelableTask; import org.jtrim.concurrent.CleanupTask; import org.jtrim.concurrent.TaskExecutor; import org.jtrim.concurrent.Tasks; import org.jtrim.event.EventDispatcher; import org.jtrim.event.ListenerRef; import org.jtrim.event.OneShotListenerManager; import org.jtrim.utils.ExceptionHelper; /** * Defines an {@link AccessToken} that will execute submitted tasks only after * a specified set of {@code AccessToken}s terminate. To create new instances of * this class, call the {@link #newToken(AccessToken, Collection) newToken} * factory method. * <P> * This class was designed to use when implementing the * {@link AccessManager#getScheduledAccess(AccessRequest)} method. To implement * that method, you must collect all the {@code AccessToken}s that conflicts * the requested tokens and pass it to this scheduled token. Note that you must * also ensure that no other access tokens will be created which conflict with * the newly created token. * * <h3>Thread safety</h3> * Methods of this class are completely thread-safe without any further * synchronization. * * <h4>Synchronization transparency</h4> * Unless documented otherwise the methods of this class are not * <I>synchronization transparent</I> but will not wait for asynchronous * tasks to complete. * * @param <IDType> the type of the access ID (see {@link #getAccessID()}) * * @see #newToken(AccessToken, Collection) newToken * * @author Kelemen Attila */ public final class ScheduledAccessToken<IDType> extends DelegatedAccessToken<IDType> { // Lock order: ScheduledExecutor.taskLock, mainLock private final AccessToken<IDType> subToken; private final Lock mainLock; private volatile boolean shuttingDown; private long queuedExecutorCount; private final RefCollection<AccessToken<IDType>> blockingTokens; private final OneShotListenerManager<Runnable, Void> allowSubmitManager; private ScheduledAccessToken(final AccessToken<IDType> token) { super(AccessTokens.createToken(token.getAccessID())); this.subToken = token; this.mainLock = new ReentrantLock(); this.blockingTokens = new RefLinkedList<>(); this.allowSubmitManager = new OneShotListenerManager<>(); this.shuttingDown = false; } /** * Creates a new scheduled token with the specified conflicting tokens and * base token. Tasks will only be submitted to the base token if * all the conflicting tokens were terminated. * <P> * The specified conflicting tokens will not be shared with clients of * this class, so they cannot be abused. * * @param <IDType> the type of the access ID (see {@link #getAccessID()}) * @param token the token to which tasks submitted to this scheduled token * will be submitted to. This token will be shutted down if the created * scheduled token was shutted down. This argument cannot be {@code null}. * @param blockingTokens the conflicting tokens. Tasks will not be submitted * to the base access token until any of these tokens are active * (i.e.: not terminated). This argument or its elements cannot be * {@code null} but can be an empty set of tokens. * @return a new scheduled token with the specified conflicting tokens and * base token. This method never returns {@code null}. * * @throws NullPointerException thrown if any of the arguments or one of the * conflicting tokens are {@code null} */ public static <IDType> ScheduledAccessToken<IDType> newToken( AccessToken<IDType> token, Collection<? extends AccessToken<IDType>> blockingTokens) { ExceptionHelper.checkNotNullArgument(token, "token"); ExceptionHelper.checkNotNullElements(blockingTokens, "blockingTokens"); ScheduledAccessToken<IDType> result = new ScheduledAccessToken<>(token); result.startWaitForBlockingTokens(blockingTokens); return result; } // Must be called right after creating ScheduledAccessToken and must be // called exactly once. private void startWaitForBlockingTokens( Collection<? extends AccessToken<IDType>> tokens) { wrappedToken.addReleaseListener(new Runnable() { @Override public void run() { subToken.release(); } }); if (tokens.isEmpty()) { enableSubmitTasks(); return; } for (AccessToken<IDType> blockingToken: tokens) { final RefCollection.ElementRef<?> tokenRef; tokenRef = blockingTokens.addGetReference(blockingToken); blockingToken.addReleaseListener(new Runnable() { @Override public void run() { boolean allReleased; mainLock.lock(); try { tokenRef.remove(); allReleased = blockingTokens.isEmpty(); } finally { mainLock.unlock(); } if (allReleased) { enableSubmitTasks(); } } }); } } private void enableSubmitTasks() { allowSubmitManager.onEvent(RunnableDispatcher.INSTANCE, null); } /** * {@inheritDoc } * <P> * <B>Implementation note</B>: The tasks submitted to the returned executor * will also run in the context of the token specified when creating this * {@code ScheduledAccessToken}. */ @Override public TaskExecutor createExecutor(TaskExecutor executor) { TaskExecutor subTokenExecutor = subToken.createExecutor(executor); TaskExecutor wrappedExecutor = wrappedToken.createExecutor(subTokenExecutor); ScheduledExecutor scheduledExecutor = new ScheduledExecutor(wrappedExecutor); return scheduledExecutor; } /** * Returns the string representation of this access token in no * particular format. * <P> * This method is intended to be used for debugging only. * * @return the string representation of this object in no particular format. * This method never returns {@code null}. */ @Override public String toString() { return "ScheduledAccessToken{" + wrappedToken + '}'; } private class ScheduledExecutor implements TaskExecutor { private final TaskExecutor executor; private final Lock taskLock; private final Deque<QueuedTask> scheduledTasks; private final AtomicBoolean listeningForTokens; private volatile boolean allowSubmit; public ScheduledExecutor(TaskExecutor executor) { this.executor = executor; this.taskLock = new ReentrantLock(); this.scheduledTasks = new LinkedList<>(); this.allowSubmit = false; this.listeningForTokens = new AtomicBoolean(false); } private void submitAll(List<QueuedTask> toSubmit) { Throwable toThrow = null; while (!toSubmit.isEmpty()) { QueuedTask queuedTask = toSubmit.remove(0); try { queuedTask.execute(executor); } catch (Throwable ex) { if (toThrow == null) toThrow = ex; else toThrow.addSuppressed(ex); } } if (toThrow != null) { ExceptionHelper.rethrow(toThrow); } } private void startSubmitting() { List<QueuedTask> toSubmit; Throwable toThrow = null; while (true) { boolean releaseNow = false; taskLock.lock(); try { if (scheduledTasks.isEmpty()) { allowSubmit = true; break; } toSubmit = new ArrayList<>(scheduledTasks); scheduledTasks.clear(); queuedExecutorCount--; releaseNow = shuttingDown && queuedExecutorCount == 0; } finally { taskLock.unlock(); } try { if (releaseNow) { wrappedToken.release(); } submitAll(toSubmit); } catch (Throwable ex) { if (toThrow == null) toThrow = ex; else toThrow.addSuppressed(ex); } } if (toThrow != null) { ExceptionHelper.rethrow(toThrow); } } private void startListeningForTokens() { allowSubmitManager.registerOrNotifyListener(new Runnable() { @Override public void run() { startSubmitting(); } }); } private void addToQueue(QueuedTask queuedTask) { boolean submitNow; taskLock.lock(); try { submitNow = allowSubmit; if (!submitNow) { if (scheduledTasks.isEmpty()) { mainLock.lock(); try { if (shuttingDown) { queuedTask.cancel(); } queuedExecutorCount++; } finally { mainLock.unlock(); } } scheduledTasks.add(queuedTask); } } finally { taskLock.unlock(); } if (submitNow) { queuedTask.execute(executor); } } @Override public void execute( CancellationToken cancelToken, CancelableTask task, final CleanupTask cleanupTask) { // This check is not required for correctness. if (allowSubmit) { executor.execute(cancelToken, task, cleanupTask); return; } Throwable toThrow = null; if (!listeningForTokens.getAndSet(true)) { try { startListeningForTokens(); } catch (Throwable ex) { toThrow = ex; } // This check is not required for correctness. if (allowSubmit) { if (toThrow == null) { executor.execute(cancelToken, task, cleanupTask); } else { try { executor.execute(cancelToken, task, cleanupTask); } catch (Throwable ex) { ex.addSuppressed(toThrow); throw ex; } } return; } } try { final AtomicReference<CancelableTask> taskRef = new AtomicReference<>(task); final ListenerRef cancelRef = cancelToken.addCancellationListener(new Runnable() { @Override public void run() { taskRef.set(null); } }); CleanupTask wrappedCleanup = new CleanupTask() { @Override public void cleanup(boolean canceled, Throwable error) throws Exception { try { cancelRef.unregister(); } finally { if (cleanupTask != null) { cleanupTask.cleanup(canceled, error); } } } }; addToQueue(new QueuedTask(cancelToken, taskRef, wrappedCleanup)); } catch (Throwable ex) { if (toThrow != null) { ex.addSuppressed(toThrow); toThrow = ex; } else { toThrow = ex; } } if (toThrow != null) { ExceptionHelper.rethrow(toThrow); } } } private static class QueuedTask { private final CancellationToken cancelToken; private final AtomicReference<CancelableTask> taskRef; private final CleanupTask cleanupTask; public QueuedTask( CancellationToken cancelToken, AtomicReference<CancelableTask> taskRef, CleanupTask cleanupTask) { this.cancelToken = cancelToken; this.taskRef = taskRef; this.cleanupTask = cleanupTask; } public void cancel() { taskRef.set(null); } public void execute(TaskExecutor executor) { CancelableTask task = taskRef.get(); if (task == null) { if (cleanupTask == null) { return; } task = Tasks.noOpCancelableTask(); } executor.execute(cancelToken, task, cleanupTask); } } private enum RunnableDispatcher implements EventDispatcher<Runnable, Void> { INSTANCE; @Override public void onEvent(Runnable eventListener, Void arg) { eventListener.run(); } } }
jtrim-gui/src/main/java/org/jtrim/access/ScheduledAccessToken.java
package org.jtrim.access; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jtrim.cancel.CancellationToken; import org.jtrim.collections.RefCollection; import org.jtrim.collections.RefLinkedList; import org.jtrim.concurrent.CancelableTask; import org.jtrim.concurrent.CleanupTask; import org.jtrim.concurrent.TaskExecutor; import org.jtrim.concurrent.Tasks; import org.jtrim.event.EventDispatcher; import org.jtrim.event.ListenerRef; import org.jtrim.event.OneShotListenerManager; import org.jtrim.utils.ExceptionHelper; /** * Defines an {@link AccessToken} that will execute submitted tasks only after * a specified set of {@code AccessToken}s terminate. To create new instances of * this class, call the {@link #newToken(AccessToken, Collection) newToken} * factory method. * <P> * This class was designed to use when implementing the * {@link AccessManager#getScheduledAccess(AccessRequest)} method. To implement * that method, you must collect all the {@code AccessToken}s that conflicts * the requested tokens and pass it to this scheduled token. Note that you must * also ensure that no other access tokens will be created which conflict with * the newly created token. * * <h3>Thread safety</h3> * Methods of this class are completely thread-safe without any further * synchronization. * * <h4>Synchronization transparency</h4> * Unless documented otherwise the methods of this class are not * <I>synchronization transparent</I> but will not wait for asynchronous * tasks to complete. * * @param <IDType> the type of the access ID (see {@link #getAccessID()}) * * @see #newToken(AccessToken, Collection) newToken * * @author Kelemen Attila */ public final class ScheduledAccessToken<IDType> extends DelegatedAccessToken<IDType> { // Lock order: ScheduledExecutor.taskLock, mainLock private final AccessToken<IDType> subToken; private final Lock mainLock; private volatile boolean shuttingDown; private long queuedExecutorCount; private final RefCollection<AccessToken<IDType>> blockingTokens; private final OneShotListenerManager<Runnable, Void> allowSubmitManager; private ScheduledAccessToken(final AccessToken<IDType> token) { super(AccessTokens.createToken(token.getAccessID())); this.subToken = token; this.mainLock = new ReentrantLock(); this.blockingTokens = new RefLinkedList<>(); this.allowSubmitManager = new OneShotListenerManager<>(); this.shuttingDown = false; } /** * Creates a new scheduled token with the specified conflicting tokens and * base token. Tasks will only be submitted to the base token if * all the conflicting tokens were terminated. * <P> * The specified conflicting tokens will not be shared with clients of * this class, so they cannot be abused. * * @param <IDType> the type of the access ID (see {@link #getAccessID()}) * @param token the token to which tasks submitted to this scheduled token * will be submitted to. This token will be shutted down if the created * scheduled token was shutted down. This argument cannot be {@code null}. * @param blockingTokens the conflicting tokens. Tasks will not be submitted * to the base access token until any of these tokens are active * (i.e.: not terminated). This argument or its elements cannot be * {@code null} but can be an empty set of tokens. * @return a new scheduled token with the specified conflicting tokens and * base token. This method never returns {@code null}. * * @throws NullPointerException thrown if any of the arguments or one of the * conflicting tokens are {@code null} */ public static <IDType> ScheduledAccessToken<IDType> newToken( AccessToken<IDType> token, Collection<? extends AccessToken<IDType>> blockingTokens) { ExceptionHelper.checkNotNullArgument(token, "token"); ExceptionHelper.checkNotNullElements(blockingTokens, "blockingTokens"); ScheduledAccessToken<IDType> result = new ScheduledAccessToken<>(token); result.startWaitForBlockingTokens(blockingTokens); return result; } // Must be called right after creating ScheduledAccessToken and must be // called exactly once. private void startWaitForBlockingTokens( Collection<? extends AccessToken<IDType>> tokens) { wrappedToken.addReleaseListener(new Runnable() { @Override public void run() { subToken.release(); } }); if (tokens.isEmpty()) { enableSubmitTasks(); return; } for (AccessToken<IDType> blockingToken: tokens) { final RefCollection.ElementRef<?> tokenRef; tokenRef = blockingTokens.addGetReference(blockingToken); blockingToken.addReleaseListener(new Runnable() { @Override public void run() { boolean allReleased; mainLock.lock(); try { tokenRef.remove(); allReleased = blockingTokens.isEmpty(); } finally { mainLock.unlock(); } if (allReleased) { enableSubmitTasks(); } } }); } } private void enableSubmitTasks() { allowSubmitManager.onEvent(RunnableDispatcher.INSTANCE, null); } /** * {@inheritDoc } * <P> * <B>Implementation note</B>: The tasks submitted to the returned executor * will also run in the context of the token specified when creating this * {@code ScheduledAccessToken}. */ @Override public TaskExecutor createExecutor(TaskExecutor executor) { TaskExecutor subTokenExecutor = subToken.createExecutor(executor); TaskExecutor wrappedExecutor = wrappedToken.createExecutor(subTokenExecutor); ScheduledExecutor scheduledExecutor = new ScheduledExecutor(wrappedExecutor); return scheduledExecutor; } /** * Returns the string representation of this access token in no * particular format. * <P> * This method is intended to be used for debugging only. * * @return the string representation of this object in no particular format. * This method never returns {@code null}. */ @Override public String toString() { return "ScheduledAccessToken{" + wrappedToken + '}'; } private class ScheduledExecutor implements TaskExecutor { private final TaskExecutor executor; private final Lock taskLock; private final Deque<QueuedTask> scheduledTasks; private final AtomicBoolean listeningForTokens; private volatile boolean allowSubmit; public ScheduledExecutor(TaskExecutor executor) { this.executor = executor; this.taskLock = new ReentrantLock(); this.scheduledTasks = new LinkedList<>(); this.allowSubmit = false; this.listeningForTokens = new AtomicBoolean(false); } private void submitAll(List<QueuedTask> toSubmit) { Throwable toThrow = null; while (!toSubmit.isEmpty()) { QueuedTask queuedTask = toSubmit.remove(0); try { executor.execute( queuedTask.cancelToken, queuedTask.getTask(), queuedTask.cleanupTask); } catch (Throwable ex) { if (toThrow == null) toThrow = ex; else toThrow.addSuppressed(ex); } } if (toThrow != null) { ExceptionHelper.rethrow(toThrow); } } private void startSubmitting() { List<QueuedTask> toSubmit; Throwable toThrow = null; while (true) { boolean releaseNow = false; taskLock.lock(); try { if (scheduledTasks.isEmpty()) { allowSubmit = true; break; } toSubmit = new ArrayList<>(scheduledTasks); scheduledTasks.clear(); queuedExecutorCount--; releaseNow = shuttingDown && queuedExecutorCount == 0; } finally { taskLock.unlock(); } try { if (releaseNow) { wrappedToken.release(); } submitAll(toSubmit); } catch (Throwable ex) { if (toThrow == null) toThrow = ex; else toThrow.addSuppressed(ex); } } if (toThrow != null) { ExceptionHelper.rethrow(toThrow); } } private void startListeningForTokens() { allowSubmitManager.registerOrNotifyListener(new Runnable() { @Override public void run() { startSubmitting(); } }); } private void addToQueue(QueuedTask queuedTask) { boolean submitNow; taskLock.lock(); try { submitNow = allowSubmit; if (!submitNow) { if (scheduledTasks.isEmpty()) { mainLock.lock(); try { if (shuttingDown) { queuedTask.taskRef.set(null); } queuedExecutorCount++; } finally { mainLock.unlock(); } } scheduledTasks.add(queuedTask); } } finally { taskLock.unlock(); } if (submitNow) { executor.execute( queuedTask.cancelToken, queuedTask.getTask(), queuedTask.cleanupTask); } } @Override public void execute( CancellationToken cancelToken, CancelableTask task, final CleanupTask cleanupTask) { // This check is not required for correctness. if (allowSubmit) { executor.execute(cancelToken, task, cleanupTask); return; } Throwable toThrow = null; if (!listeningForTokens.getAndSet(true)) { try { startListeningForTokens(); } catch (Throwable ex) { toThrow = ex; } // This check is not required for correctness. if (allowSubmit) { if (toThrow == null) { executor.execute(cancelToken, task, cleanupTask); } else { try { executor.execute(cancelToken, task, cleanupTask); } catch (Throwable ex) { ex.addSuppressed(toThrow); throw ex; } } return; } } try { final AtomicReference<CancelableTask> taskRef = new AtomicReference<>(task); final ListenerRef cancelRef = cancelToken.addCancellationListener(new Runnable() { @Override public void run() { taskRef.set(null); } }); CleanupTask wrappedCleanup = new CleanupTask() { @Override public void cleanup(boolean canceled, Throwable error) throws Exception { try { cancelRef.unregister(); } finally { if (cleanupTask != null) { cleanupTask.cleanup(canceled, error); } } } }; addToQueue(new QueuedTask(cancelToken, taskRef, wrappedCleanup)); } catch (Throwable ex) { if (toThrow != null) { ex.addSuppressed(toThrow); toThrow = ex; } else { toThrow = ex; } } if (toThrow != null) { ExceptionHelper.rethrow(toThrow); } } } private static class QueuedTask { public final CancellationToken cancelToken; public final AtomicReference<CancelableTask> taskRef; public final CleanupTask cleanupTask; public QueuedTask( CancellationToken cancelToken, AtomicReference<CancelableTask> taskRef, CleanupTask cleanupTask) { this.cancelToken = cancelToken; this.taskRef = taskRef; this.cleanupTask = cleanupTask; } public CancelableTask getTask() { CancelableTask task = taskRef.get(); return task != null ? task : Tasks.noOpCancelableTask(); } } private enum RunnableDispatcher implements EventDispatcher<Runnable, Void> { INSTANCE; @Override public void onEvent(Runnable eventListener, Void arg) { eventListener.run(); } } }
Minor optimization in ScheduledAccessToken.
jtrim-gui/src/main/java/org/jtrim/access/ScheduledAccessToken.java
Minor optimization in ScheduledAccessToken.
<ide><path>trim-gui/src/main/java/org/jtrim/access/ScheduledAccessToken.java <ide> QueuedTask queuedTask = toSubmit.remove(0); <ide> <ide> try { <del> executor.execute( <del> queuedTask.cancelToken, <del> queuedTask.getTask(), <del> queuedTask.cleanupTask); <add> queuedTask.execute(executor); <ide> } catch (Throwable ex) { <ide> if (toThrow == null) toThrow = ex; <ide> else toThrow.addSuppressed(ex); <ide> mainLock.lock(); <ide> try { <ide> if (shuttingDown) { <del> queuedTask.taskRef.set(null); <add> queuedTask.cancel(); <ide> } <ide> queuedExecutorCount++; <ide> } finally { <ide> } <ide> <ide> if (submitNow) { <del> executor.execute( <del> queuedTask.cancelToken, <del> queuedTask.getTask(), <del> queuedTask.cleanupTask); <add> queuedTask.execute(executor); <ide> } <ide> } <ide> <ide> } <ide> <ide> private static class QueuedTask { <del> public final CancellationToken cancelToken; <del> public final AtomicReference<CancelableTask> taskRef; <del> public final CleanupTask cleanupTask; <add> private final CancellationToken cancelToken; <add> private final AtomicReference<CancelableTask> taskRef; <add> private final CleanupTask cleanupTask; <ide> <ide> public QueuedTask( <ide> CancellationToken cancelToken, <ide> this.cleanupTask = cleanupTask; <ide> } <ide> <del> public CancelableTask getTask() { <add> public void cancel() { <add> taskRef.set(null); <add> } <add> <add> public void execute(TaskExecutor executor) { <ide> CancelableTask task = taskRef.get(); <del> return task != null ? task : Tasks.noOpCancelableTask(); <add> if (task == null) { <add> if (cleanupTask == null) { <add> return; <add> } <add> task = Tasks.noOpCancelableTask(); <add> } <add> executor.execute(cancelToken, task, cleanupTask); <ide> } <ide> } <ide>
Java
apache-2.0
7762036bf864b49122d555017be4ec91dfc4edfd
0
ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf
/* * $Log: Adapter.java,v $ * Revision 1.49 2008-09-22 13:28:45 europe\L190409 * use CounterStatistics for counters * changed references to Hashtable to Map * output statistics in order of Pipes * * Revision 1.48 2008/09/04 12:02:27 Gerrit van Brakel <[email protected]> * collect interval statistics * * Revision 1.47 2008/08/27 15:54:07 Gerrit van Brakel <[email protected]> * added reset option to statisticsdump * * Revision 1.46 2008/08/12 15:31:13 Gerrit van Brakel <[email protected]> * moved collection of receiver statistics to receiver * * Revision 1.45 2008/08/07 11:34:07 Gerrit van Brakel <[email protected]> * removed references to old monitoring code * * Revision 1.44 2008/08/07 07:54:55 Gerrit van Brakel <[email protected]> * modified for flexibile monitoring * * Revision 1.43 2008/06/19 11:08:59 Gerrit van Brakel <[email protected]> * GALM message when exception caught starting adapter * * Revision 1.42 2008/06/18 12:27:43 Gerrit van Brakel <[email protected]> * discern between severe errors and warnings (for monitoring) * * Revision 1.41 2008/05/21 10:56:09 Gerrit van Brakel <[email protected]> * modified monitorAdapter interface * fixed NDC handling * * Revision 1.40 2008/05/14 09:33:30 Gerrit van Brakel <[email protected]> * simplified methodnames of StatisticsKeeperIterationHandler * now implements interface HasStatistics * * Revision 1.39 2008/03/28 14:20:42 Gerrit van Brakel <[email protected]> * simplify error messages * * Revision 1.38 2008/03/27 11:09:41 Gerrit van Brakel <[email protected]> * avoid nested non-informative NDCs * * Revision 1.37 2008/01/03 15:40:19 Gerrit van Brakel <[email protected]> * renamed start and stop threads * do not wait at end of start thread * * Revision 1.36 2007/12/28 12:01:00 Gerrit van Brakel <[email protected]> * log error messages in request-reply logging * * Revision 1.35 2007/12/12 09:08:41 Gerrit van Brakel <[email protected]> * added message class to monitor event from error * * Revision 1.34 2007/12/10 10:00:02 Gerrit van Brakel <[email protected]> * added monitoring * * Revision 1.33 2007/10/10 09:35:28 Gerrit van Brakel <[email protected]> * Direct copy from Ibis-EJB: * spring enabled version * * Revision 1.32 2007/10/08 12:15:38 Gerrit van Brakel <[email protected]> * corrected date formatting * * Revision 1.31 2007/07/24 08:05:22 Gerrit van Brakel <[email protected]> * added targetDesignDocument attribute * * Revision 1.30 2007/07/10 07:11:45 Gerrit van Brakel <[email protected]> * logging improvements * * Revision 1.29 2007/06/26 12:05:34 Gerrit van Brakel <[email protected]> * tuned logging * * Revision 1.28 2007/05/02 11:23:52 Gerrit van Brakel <[email protected]> * added attribute 'active' * * Revision 1.27 2007/03/14 12:22:10 Gerrit van Brakel <[email protected]> * log results in case of exception, too * * Revision 1.26 2007/02/12 13:44:09 Gerrit van Brakel <[email protected]> * Logger from LogUtil * * Revision 1.25 2006/09/14 14:58:00 Gerrit van Brakel <[email protected]> * added getPipeLine() * * Revision 1.24 2006/09/07 08:35:50 Gerrit van Brakel <[email protected]> * added requestReplyLogging * * Revision 1.23 2006/08/22 12:50:17 Gerrit van Brakel <[email protected]> * moved code for userTransaction to JtaUtil * * Revision 1.22 2006/02/09 07:55:15 Gerrit van Brakel <[email protected]> * name, upSince and lastMessageDate in statistics-summary * * Revision 1.21 2005/12/28 08:34:46 Gerrit van Brakel <[email protected]> * introduced StatisticsKeeper-iteration * * Revision 1.20 2005/10/26 13:16:14 Gerrit van Brakel <[email protected]> * added second default for UserTransactionUrl * * Revision 1.19 2005/10/17 08:51:23 Gerrit van Brakel <[email protected]> * made getMessageKeeper synchronized * * Revision 1.18 2005/08/17 08:12:45 Peter Leeuwenburgh <[email protected]> * NDC updated * * Revision 1.17 2005/08/16 12:33:30 Gerrit van Brakel <[email protected]> * added NDC with correlationId * * Revision 1.16 2005/07/05 12:27:52 Gerrit van Brakel <[email protected]> * added possibility to end processing with an exception * * Revision 1.15 2005/01/13 08:55:15 Gerrit van Brakel <[email protected]> * Make threadContext-attributes available in PipeLineSession * * Revision 1.14 2004/09/08 14:14:41 Gerrit van Brakel <[email protected]> * adjusted error logging * * Revision 1.13 2004/08/19 07:16:21 unknown <[email protected]> * Resolved problem of hanging adapter if stopRunning was called just after the * adapter was set to started * * Revision 1.12 2004/07/06 07:00:44 Gerrit van Brakel <[email protected]> * configure now throws less exceptions * * Revision 1.11 2004/06/30 10:02:23 Gerrit van Brakel <[email protected]> * improved error reporting * * Revision 1.10 2004/06/16 13:08:11 Johan Verrips <[email protected]> * Added configuration error when no pipeline was configured * * Revision 1.9 2004/06/16 12:34:46 Johan Verrips <[email protected]> * Added AutoStart functionality on Adapter * * Revision 1.8 2004/04/28 08:31:41 Johan Verrips <[email protected]> * Added getRunStateAsString function * * Revision 1.7 2004/04/13 11:37:13 Johan Verrips <[email protected]> * When the Adapter was in state "ERROR", it could not be stopped anymore. Fixed it. * * Revision 1.6 2004/04/06 14:52:52 Johan Verrips <[email protected]> * Updated handling of errors in receiver.configure() * * Revision 1.5 2004/03/30 07:29:53 Gerrit van Brakel <[email protected]> * updated javadoc * * Revision 1.4 2004/03/26 10:42:45 Johan Verrips <[email protected]> * added @version tag in javadoc * */ package nl.nn.adapterframework.core; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter; import nl.nn.adapterframework.receivers.ReceiverBase; import nl.nn.adapterframework.util.DateUtils; import nl.nn.adapterframework.util.HasStatistics; import nl.nn.adapterframework.util.LogUtil; import nl.nn.adapterframework.util.MessageKeeper; import nl.nn.adapterframework.util.RunStateEnum; import nl.nn.adapterframework.util.RunStateManager; import nl.nn.adapterframework.util.CounterStatistic; import nl.nn.adapterframework.util.StatisticsKeeper; import nl.nn.adapterframework.util.StatisticsKeeperIterationHandler; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.springframework.beans.factory.NamedBean; import org.springframework.core.task.TaskExecutor; /** * The Adapter is the central manager in the IBIS Adapterframework, that has knowledge * and uses {@link IReceiver IReceivers} and a {@link PipeLine}. * * <b>responsibility</b><br/> * <ul> * <li>keeping and gathering statistics</li> * <li>processing messages, retrieved from IReceivers</li> * <li>starting and stoppping IReceivers</li> * <li>delivering error messages in a specified format</li> * </ul> * All messages from IReceivers pass through the adapter (multi threaded). * Multiple receivers may be attached to one adapter.<br/> * <br/> * The actual processing of messages is delegated to the {@link PipeLine} * object, which returns a {@link PipeLineResult}. If an error occurs during * the pipeline execution, the state in the <code>PipeLineResult</code> is set * to the state specified by <code>setErrorState</code>, which defaults to "ERROR". * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>className</td><td>nl.nn.adapterframework.pipes.AbstractPipe</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the Adapter</td><td>&nbsp;</td></tr> * <tr><td>{@link #setDescription(String) description}</td><td>description of the Adapter</td><td>&nbsp;</td></tr> * <tr><td>{@link #setAutoStart(boolean) autoStart}</td><td>controls whether Adapters starts when configuration loads</td><td>true</td></tr> * <tr><td>{@link #setActive(boolean) active}</td> <td>controls whether Adapter is included in configuration. When set <code>false</code> or set to something else as "true", (even set to the empty string), the receiver is not included in the configuration</td><td>true</td></tr> * <tr><td>{@link #setErrorMessageFormatter(String) errorMessageFormatter}</td><td>&nbsp;</td><td>&nbsp;</td></tr> * <tr><td>{@link #setErrorState(String) errorState}</td><td>If an error occurs during * the pipeline execution, the state in the <code>PipeLineResult</code> is set to this state</td><td>ERROR</td></tr> * <tr><td>{@link #setMessageKeeperSize(int) messageKeeperSize}</td><td>number of message displayed in IbisConsole</td><td>10</td></tr> * <tr><td>{@link #setRequestReplyLogging(boolean) requestReplyLogging}</td><td>when <code>true</code>, the request and reply messages will be logged for each request processed</td><td>false</td></tr> * </table></td><td>&nbsp;</td></tr> * </table> * * @version Id * @author Johan Verrips * @see nl.nn.adapterframework.core.IReceiver * @see nl.nn.adapterframework.core.PipeLine * @see nl.nn.adapterframework.util.StatisticsKeeper * @see nl.nn.adapterframework.util.DateUtils * @see nl.nn.adapterframework.util.MessageKeeper * @see nl.nn.adapterframework.core.PipeLineResult * */ public class Adapter implements IAdapter, NamedBean { public static final String version = "$RCSfile: Adapter.java,v $ $Revision: 1.49 $ $Date: 2008-09-22 13:28:45 $"; private Logger log = LogUtil.getLogger(this); private String name; private String targetDesignDocument; private boolean active=true; private Vector receivers = new Vector(); private long lastMessageDate = 0; private PipeLine pipeline; private int numOfMessagesInProcess = 0; private CounterStatistic numOfMessagesProcessed = new CounterStatistic(0); private CounterStatistic numOfMessagesInError = new CounterStatistic(0); private StatisticsKeeper statsMessageProcessingDuration = null; private long statsUpSince = System.currentTimeMillis(); private IErrorMessageFormatter errorMessageFormatter; private RunStateManager runState = new RunStateManager(); private boolean configurationSucceeded = false; private String description; private MessageKeeper messageKeeper; //instantiated in configure() private int messageKeeperSize = 10; //default length private boolean autoStart = true; private boolean requestReplyLogging = false; // state to put in PipeLineResult when a PipeRunException occurs; private String errorState = "ERROR"; private TaskExecutor taskExecutor; /** * Indicates wether the configuration succeeded. * @return boolean */ public boolean configurationSucceeded() { return configurationSucceeded; } /* * This function is called by Configuration.registerAdapter, * to make configuration information available to the Adapter. <br/><br/> * This method also performs * a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes. * @see nl.nn.adapterframework.core.Pipeline#configurePipes */ public void configure() throws ConfigurationException { configurationSucceeded = false; log.debug("configuring adapter [" + getName() + "]"); MessageKeeper messageKeeper = getMessageKeeper(); statsMessageProcessingDuration = new StatisticsKeeper(getName()); if (pipeline == null) { String msg = "No pipeline configured for adapter [" + getName() + "]"; messageKeeper.add(msg); throw new ConfigurationException(msg); } try { pipeline.setAdapter(this); pipeline.configurePipes(); messageKeeper.add("pipeline successfully configured"); Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); log.info("Adapter [" + name + "] is initializing receiver [" + receiver.getName() + "]"); receiver.setAdapter(this); try { receiver.configure(); messageKeeper.add("receiver [" + receiver.getName() + "] successfully configured"); } catch (ConfigurationException e) { error(true, "error initializing receiver [" + receiver.getName() + "]",e); } } configurationSucceeded = true; } catch (ConfigurationException e) { error(true, "error initializing pipeline", e); } } /** * sends a warning to the log and to the messagekeeper of the adapter */ protected void warn(String msg) { log.warn("Adapter [" + getName() + "] "+msg); getMessageKeeper().add("WARNING: " + msg); } /** * sends a warning to the log and to the messagekeeper of the adapter */ protected void error(boolean critical, String msg, Throwable t) { log.error("Adapter [" + getName() + "] "+msg, t); getMessageKeeper().add("ERROR: " + msg+": "+t.getMessage()); // String prefix=critical?"ADPTERROR ":"ADPTWARN "; // fireMonitorEvent(EventTypeEnum.TECHNICAL,critical?SeverityEnum.CRITICAL:SeverityEnum.WARNING, prefix+msg,t); } /** * Increase the number of messages in process */ private void incNumOfMessagesInProcess(long startTime) { synchronized (statsMessageProcessingDuration) { numOfMessagesInProcess++; lastMessageDate = startTime; } } /** * Decrease the number of messages in process */ private synchronized void decNumOfMessagesInProcess(long duration) { synchronized (statsMessageProcessingDuration) { numOfMessagesInProcess--; numOfMessagesProcessed.increase(); statsMessageProcessingDuration.addValue(duration); notifyAll(); } } /** * The number of messages for which processing ended unsuccessfully. */ private void incNumOfMessagesInError() { synchronized (statsMessageProcessingDuration) { numOfMessagesInError.increase(); } } public synchronized String formatErrorMessage( String errorMessage, Throwable t, String originalMessage, String messageID, INamedObject objectInError, long receivedTime) { if (errorMessageFormatter == null) { errorMessageFormatter = new ErrorMessageFormatter(); } // you never can trust an implementation, so try/catch! try { String formattedErrorMessage= errorMessageFormatter.format( errorMessage, t, objectInError, originalMessage, messageID, receivedTime); if (isRequestReplyLogging()) { log.info("Adapter [" + getName() + "] messageId[" + messageID + "] formatted errormessage, result [" + formattedErrorMessage + "]"); } else { if (log.isDebugEnabled()) { log.info("Adapter [" + getName() + "] messageId[" + messageID + "] formatted errormessage, result [" + formattedErrorMessage + "]"); } } return formattedErrorMessage; } catch (Exception e) { String msg = "got error while formatting errormessage, original errorMessage [" + errorMessage + "]"; msg = msg + " from [" + (objectInError == null ? "unknown-null" : objectInError.getName()) + "]"; error(false, "got error while formatting errormessage", e); return errorMessage; } } /** * retrieve the date and time of the last message. */ public String getLastMessageDate() { String result = ""; if (lastMessageDate != 0) result = DateUtils.format(new Date(lastMessageDate), DateUtils.FORMAT_FULL_GENERIC); else result = "-"; return result; } /** * the MessageKeeper is for keeping the last <code>messageKeeperSize</code> * messages available, for instance for displaying it in the webcontrol * @see nl.nn.adapterframework.util.MessageKeeper */ public synchronized MessageKeeper getMessageKeeper() { if (messageKeeper == null) messageKeeper = new MessageKeeper(messageKeeperSize < 1 ? 1 : messageKeeperSize); return messageKeeper; } public void forEachStatisticsKeeper(StatisticsKeeperIterationHandler hski, int action) { Object root=hski.start(); forEachStatisticsKeeperBody(hski,root,action); hski.end(root); } private void doForEachStatisticsKeeperBody(StatisticsKeeperIterationHandler hski, Object adapterData, int action) { hski.handleScalar(adapterData,"messagesInProcess", getNumOfMessagesInProcess()); hski.handleScalar(adapterData,"messagesProcessed", getNumOfMessagesProcessed()); hski.handleScalar(adapterData,"messagesInError", getNumOfMessagesInError()); hski.handleScalar(adapterData,"messagesProcessedThisInterval", numOfMessagesProcessed.getIntervalValue()); hski.handleScalar(adapterData,"messagesInErrorThisInterval", numOfMessagesInError.getIntervalValue()); hski.handleStatisticsKeeper(adapterData, statsMessageProcessingDuration); statsMessageProcessingDuration.performAction(action); numOfMessagesProcessed.performAction(action); numOfMessagesInError.performAction(action); Object recsData=hski.openGroup(adapterData,getName(),"receivers"); Iterator recIt=getReceiverIterator(); if (recIt.hasNext()) { while (recIt.hasNext()) { IReceiver receiver=(IReceiver) recIt.next(); receiver.iterateOverStatistics(hski,recsData,action); } } hski.closeGroup(recsData); Object pipelineData=hski.openGroup(adapterData,getName(),"pipeline"); Map pipelineStatistics = getPipeLineStatistics(); Object pipestatData=hski.openGroup(pipelineData,getName(),"pipeStats"); for(Iterator it=getPipeLine().getPipes().iterator();it.hasNext();) { IPipe pipe = (IPipe)it.next(); String pipeName = pipe.getName(); StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName); hski.handleStatisticsKeeper(pipestatData,pstat); pstat.performAction(action); if (pipe instanceof HasStatistics) { ((HasStatistics) pipe).iterateOverStatistics(hski, pipestatData,action); } } hski.closeGroup(pipestatData); pipelineStatistics = getWaitingStatistics(); if (pipelineStatistics.size()>0) { pipestatData=hski.openGroup(pipelineData,getName(),"idleStats"); for(Iterator it=getPipeLine().getPipes().iterator();it.hasNext();) { IPipe pipe = (IPipe)it.next(); String pipeName = pipe.getName(); StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName); hski.handleStatisticsKeeper(pipestatData,pstat); pstat.performAction(action); } hski.closeGroup(pipestatData); } hski.closeGroup(pipelineData); } public void forEachStatisticsKeeperBody(StatisticsKeeperIterationHandler hski, Object data, int action) { Object adapterData=hski.openGroup(data,getName(),"adapter"); hski.handleScalar(adapterData,"name", getName()); hski.handleScalar(adapterData,"upSince", getStatsUpSince()); hski.handleScalar(adapterData,"lastMessageDate", getLastMessageDate()); if (action!=HasStatistics.STATISTICS_ACTION_NONE) { synchronized (statsMessageProcessingDuration) { doForEachStatisticsKeeperBody(hski,adapterData,action); } } else { doForEachStatisticsKeeperBody(hski,adapterData,action); } hski.closeGroup(adapterData); } /** * the functional name of this adapter * @return the name of the adapter */ public String getName() { return name; } /** * The number of messages for which processing ended unsuccessfully. */ public long getNumOfMessagesInError() { synchronized (statsMessageProcessingDuration) { return numOfMessagesInError.getValue(); } } public int getNumOfMessagesInProcess() { synchronized (statsMessageProcessingDuration) { return numOfMessagesInProcess; } } /** * Total of messages processed * @return long total messages processed */ public long getNumOfMessagesProcessed() { synchronized (statsMessageProcessingDuration) { return numOfMessagesProcessed.getValue(); } } public Map getPipeLineStatistics() { return pipeline.getPipeStatistics(); } public IReceiver getReceiverByName(String receiverName) { Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); if (receiver.getName().equalsIgnoreCase(receiverName)) { return receiver; } } return null; } public Iterator getReceiverIterator() { return receivers.iterator(); } public PipeLine getPipeLine() { return pipeline; } public RunStateEnum getRunState() { return runState.getRunState(); } public String getRunStateAsString() { return runState.getRunState().toString(); } /** * Return the total processing duration as a StatisticsKeeper * @see nl.nn.adapterframework.util.StatisticsKeeper * @return nl.nn.adapterframework.util.StatisticsKeeper */ public StatisticsKeeper getStatsMessageProcessingDuration() { return statsMessageProcessingDuration; } /** * return the date and time since active * Creation date: (19-02-2003 12:16:53) * @return String Date */ public String getStatsUpSince() { return DateUtils.format(new Date(statsUpSince), DateUtils.FORMAT_FULL_GENERIC); } /** * Retrieve the waiting statistics as a <code>Hashtable</code> */ public Map getWaitingStatistics() { return pipeline.getPipeWaitingStatistics(); } /** * * Process the receiving of a message * After all Pipes have been run in the PipeLineProcessor, the Object.toString() function * is called. The result is returned to the Receiver. * */ public PipeLineResult processMessage(String messageId, String message) { PipeLineSession pls=new PipeLineSession(); Date now=new Date(); PipeLineSession.setListenerParameters(pls,messageId,null,now,now); return processMessage(messageId, message, pls); } public PipeLineResult processMessage(String messageId, String message, PipeLineSession pipeLineSession) { long startTime = System.currentTimeMillis(); try { return processMessageWithExceptions(messageId, message, pipeLineSession); } catch (Throwable t) { PipeLineResult result = new PipeLineResult(); result.setState(getErrorState()); String msg = "Illegal exception ["+t.getClass().getName()+"]"; INamedObject objectInError = null; if (t instanceof ListenerException) { Throwable cause = ((ListenerException) t).getCause(); if (cause instanceof PipeRunException) { PipeRunException pre = (PipeRunException) cause; msg = "error during pipeline processing"; objectInError = pre.getPipeInError(); } else if (cause instanceof ManagedStateException) { msg = "illegal state"; objectInError = this; } } result.setResult(formatErrorMessage(msg, t, message, messageId, objectInError, startTime)); if (isRequestReplyLogging()) { log.info("Adapter [" + getName() + "] messageId [" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } else { if (log.isDebugEnabled()) { log.debug("Adapter [" + getName() + "] messageId [" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } } return result; } } public PipeLineResult processMessageWithExceptions(String messageId, String message, PipeLineSession pipeLineSession) throws ListenerException { PipeLineResult result = new PipeLineResult(); long startTime = System.currentTimeMillis(); // prevent executing a stopped adapter // the receivers should implement this, but you never now.... RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STARTED) && !currentRunState.equals(RunStateEnum.STOPPING)) { String msgAdapterNotOpen = "Adapter [" + getName() + "] in state [" + currentRunState + "], cannot process message"; throw new ListenerException(new ManagedStateException(msgAdapterNotOpen)); } incNumOfMessagesInProcess(startTime); String lastNDC=NDC.peek(); String newNDC="cid [" + messageId + "]"; boolean ndcChanged=!newNDC.equals(lastNDC); if (ndcChanged) { NDC.push(newNDC); } if (isRequestReplyLogging()) { if (log.isInfoEnabled()) log.info("Adapter [" + name + "] received message [" + message + "] with messageId [" + messageId + "]"); } else { if (log.isDebugEnabled()) { log.debug("Adapter [" + name + "] received message [" + message + "] with messageId [" + messageId + "]"); } else { log.info("Adapter [" + name + "] received message with messageId [" + messageId + "]"); } } try { result = pipeline.process(messageId, message,pipeLineSession); if (isRequestReplyLogging()) { log.info("Adapter [" + getName() + "] messageId[" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } else { if (log.isDebugEnabled()) { log.debug("Adapter [" + getName() + "] messageId[" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } } return result; } catch (Throwable t) { ListenerException e; if (t instanceof ListenerException) { e = (ListenerException) t; } else { e = new ListenerException(t); } incNumOfMessagesInError(); error(false, "error processing message with messageId [" + messageId+"]: ",e); throw e; } finally { long endTime = System.currentTimeMillis(); long duration = endTime - startTime; //reset the InProcess fields, and increase processedMessagesCount decNumOfMessagesInProcess(duration); if (log.isDebugEnabled()) { // for performance reasons log.debug("Adapter: [" + getName() + "] STAT: Finished processing message with messageId [" + messageId + "] exit-state [" + result.getState() + "] started " + DateUtils.format(new Date(startTime), DateUtils.FORMAT_FULL_GENERIC) + " finished " + DateUtils.format(new Date(endTime), DateUtils.FORMAT_FULL_GENERIC) + " total duration: " + duration + " msecs"); } else { log.info("Adapter [" + getName() + "] completed message with messageId [" + messageId + "] with exit-state [" + result.getState() + "]"); } if (ndcChanged) { NDC.pop(); } } } /** * Register a PipeLine at this adapter. On registering, the adapter performs * a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes. * @param pipeline * @throws ConfigurationException * @see PipeLine */ public void registerPipeLine(PipeLine pipeline) throws ConfigurationException { this.pipeline = pipeline; pipeline.setAdapter(this); log.debug("Adapter [" + name + "] registered pipeline [" + pipeline.toString() + "]"); } /** * Register a receiver for this Adapter * @param receiver * @see IReceiver */ public void registerReceiver(IReceiver receiver) { boolean receiverActive=true; if (receiver instanceof ReceiverBase) { receiverActive=((ReceiverBase)receiver).isActive(); } if (receiverActive) { receivers.add(receiver); log.debug("Adapter [" + name + "] registered receiver [" + receiver.getName() + "] with properties [" + receiver.toString() + "]"); } else { log.debug("Adapter [" + name + "] did not register inactive receiver [" + receiver.getName() + "] with properties [" + receiver.toString() + "]"); } } /** * some functional description of the <code>Adapter</code>/ */ public void setDescription(String description) { this.description = description; } public String getDescription() { return this.description; } /** * Register a <code>ErrorMessageFormatter</code> as the formatter * for this <code>adapter</code> * @param errorMessageFormatter * @see IErrorMessageFormatter */ public void setErrorMessageFormatter(IErrorMessageFormatter errorMessageFormatter) { this.errorMessageFormatter = errorMessageFormatter; } /** * state to put in PipeLineResult when a PipeRunException occurs * @param newErrorState java.lang.String * @see PipeLineResult */ public void setErrorState(java.lang.String newErrorState) { errorState = newErrorState; } /** * state to put in PipeLineResult when a PipeRunException occurs. */ public String getErrorState() { return errorState; } /** * Set the number of messages that are kept on the screen. * @param size * @see nl.nn.adapterframework.util.MessageKeeper */ public void setMessageKeeperSize(int size) { this.messageKeeperSize = size; } /** * the functional name of this adapter */ public void setName(String name) { this.name = name; } /** * Start the adapter. The thread-name will be set tot the adapter's name. * The run method, called by t.start(), will call the startRunning method * of the IReceiver. The Adapter will be a new thread, as this interface * extends the <code>Runnable</code> interface. The actual starting is done * in the <code>run</code> method. * @see IReceiver#startRunning() * @see Adapter#run */ public void startRunning() { taskExecutor.execute(new Runnable() { public void run() { Thread.currentThread().setName("starting Adapter "+getName()); try { if (!configurationSucceeded) { log.error( "configuration of adapter [" + getName() + "] did not succeed, therefore starting the adapter is not possible"); warn("configuration did not succeed. Starting the adapter is not possible"); runState.setRunState(RunStateEnum.ERROR); return; } synchronized (runState) { RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STOPPED)) { String msg = "currently in state [" + currentRunState + "], ignoring start() command"; warn(msg); return; } // start the pipeline runState.setRunState(RunStateEnum.STARTING); } try { log.debug("Adapter [" + getName() + "] is starting pipeline"); pipeline.start(); } catch (PipeStartException pre) { error(true, "got error starting PipeLine", pre); runState.setRunState(RunStateEnum.ERROR); return; } // as from version 3.0 the adapter is started, // regardless of receivers are correctly started. runState.setRunState(RunStateEnum.STARTED); getMessageKeeper().add("Adapter up and running"); log.info("Adapter [" + getName() + "] up and running"); // starting receivers Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); if (receiver.getRunState() != RunStateEnum.ERROR) { log.info("Adapter [" + getName() + "] is starting receiver [" + receiver.getName() + "]"); receiver.startRunning(); } else log.warn("Adapter [" + getName() + "] will NOT start receiver [" + receiver.getName() + "] as it is in state ERROR"); } //while // // wait until the stopRunning is called // waitForRunState(RunStateEnum.STOPPING); } catch (Throwable t) { error(true, "got error starting Adapter", t); log.error("error running adapter [" + getName() + "]", t); runState.setRunState(RunStateEnum.ERROR); } } // End Runnable.run() }); // End Runnable } // End startRunning() /** * Stop the <code>Adapter</code> and close all elements like receivers, * Pipeline, pipes etc. * The adapter * will call the <code>IReceiver</code> to <code>stopListening</code> * <p>Also the <code>PipeLine.close()</code> method will be called, * closing alle registered pipes. </p> * @see IReceiver#stopRunning * @see PipeLine#stop */ public void stopRunning() { synchronized (runState) { RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STARTED) && (!currentRunState.equals(RunStateEnum.ERROR))) { warn("in state [" + currentRunState + "] while stopAdapter() command is issued, ignoring command"); return; } if (currentRunState.equals(RunStateEnum.ERROR)) { runState.setRunState(RunStateEnum.STOPPED); return; } runState.setRunState(RunStateEnum.STOPPING); } taskExecutor.execute(new Runnable() { public void run() { Thread.currentThread().setName("stopping Adapter " +getName()); try { log.debug("Adapter [" + name + "] is stopping receivers"); Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); try { receiver.stopRunning(); log.info("Adapter [" + name + "] successfully stopped receiver [" + receiver.getName() + "]"); } catch (Exception e) { error(false, "received error while stopping receiver [" + receiver.getName() + "], ignoring this, so watch out.", e); } } // stop the adapter log.debug("***stopping adapter"); it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); receiver.waitForRunState(RunStateEnum.STOPPED); log.info("Adapter [" + getName() + "] stopped [" + receiver.getName() + "]"); } int currentNumOfMessagesInProcess = getNumOfMessagesInProcess(); if (currentNumOfMessagesInProcess > 0) { String msg = "Adapter [" + name + "] is being stopped while still processing " + currentNumOfMessagesInProcess + " messages, waiting for them to finish"; warn(msg); } waitForNoMessagesInProcess(); log.debug("Adapter [" + name + "] is stopping pipeline"); pipeline.stop(); runState.setRunState(RunStateEnum.STOPPED); getMessageKeeper().add("Adapter stopped"); } catch (Throwable e) { log.error("error running adapter [" + getName() + "] [" + ToStringBuilder.reflectionToString(e) + "]", e); runState.setRunState(RunStateEnum.ERROR); } } // End of run() }); // End of Runnable } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[name=" + name + "]"); sb.append("[version=" + version + "]"); sb.append("[targetDesignDocument=" + targetDesignDocument + "]"); Iterator it = receivers.iterator(); sb.append("[receivers="); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); sb.append(" " + receiver.getName()); } sb.append("]"); sb.append( "[pipeLine=" + ((pipeline != null) ? pipeline.toString() : "none registered") + "]" + "[started=" + getRunState() + "]"); return sb.toString(); } public void waitForNoMessagesInProcess() throws InterruptedException { synchronized (statsMessageProcessingDuration) { while (getNumOfMessagesInProcess() > 0) { wait(); } } } public void waitForRunState(RunStateEnum requestedRunState) throws InterruptedException { runState.waitForRunState(requestedRunState); } public boolean waitForRunState(RunStateEnum requestedRunState, long maxWait) throws InterruptedException { return runState.waitForRunState(requestedRunState, maxWait); } /** * AutoStart indicates that the adapter should be started when the configuration * is started. AutoStart defaults to <code>true</code> * @since 4.1.1 */ public void setAutoStart(boolean autoStart) { this.autoStart = autoStart; } public boolean isAutoStart() { return autoStart; } public void setRequestReplyLogging(boolean requestReplyLogging) { this.requestReplyLogging = requestReplyLogging; } public boolean isRequestReplyLogging() { return requestReplyLogging; } public void setActive(boolean b) { active = b; } public boolean isActive() { return active; } public void setTargetDesignDocument(String string) { targetDesignDocument = string; } public String getTargetDesignDocument() { return targetDesignDocument; } public void setTaskExecutor(TaskExecutor executor) { taskExecutor = executor; } public TaskExecutor getTaskExecutor() { return taskExecutor; } /* (non-Javadoc) * @see org.springframework.beans.factory.NamedBean#getBeanName() */ public String getBeanName() { return name; } }
JavaSource/nl/nn/adapterframework/core/Adapter.java
/* * $Log: Adapter.java,v $ * Revision 1.48 2008-09-04 12:02:27 europe\L190409 * collect interval statistics * * Revision 1.47 2008/08/27 15:54:07 Gerrit van Brakel <[email protected]> * added reset option to statisticsdump * * Revision 1.46 2008/08/12 15:31:13 Gerrit van Brakel <[email protected]> * moved collection of receiver statistics to receiver * * Revision 1.45 2008/08/07 11:34:07 Gerrit van Brakel <[email protected]> * removed references to old monitoring code * * Revision 1.44 2008/08/07 07:54:55 Gerrit van Brakel <[email protected]> * modified for flexibile monitoring * * Revision 1.43 2008/06/19 11:08:59 Gerrit van Brakel <[email protected]> * GALM message when exception caught starting adapter * * Revision 1.42 2008/06/18 12:27:43 Gerrit van Brakel <[email protected]> * discern between severe errors and warnings (for monitoring) * * Revision 1.41 2008/05/21 10:56:09 Gerrit van Brakel <[email protected]> * modified monitorAdapter interface * fixed NDC handling * * Revision 1.40 2008/05/14 09:33:30 Gerrit van Brakel <[email protected]> * simplified methodnames of StatisticsKeeperIterationHandler * now implements interface HasStatistics * * Revision 1.39 2008/03/28 14:20:42 Gerrit van Brakel <[email protected]> * simplify error messages * * Revision 1.38 2008/03/27 11:09:41 Gerrit van Brakel <[email protected]> * avoid nested non-informative NDCs * * Revision 1.37 2008/01/03 15:40:19 Gerrit van Brakel <[email protected]> * renamed start and stop threads * do not wait at end of start thread * * Revision 1.36 2007/12/28 12:01:00 Gerrit van Brakel <[email protected]> * log error messages in request-reply logging * * Revision 1.35 2007/12/12 09:08:41 Gerrit van Brakel <[email protected]> * added message class to monitor event from error * * Revision 1.34 2007/12/10 10:00:02 Gerrit van Brakel <[email protected]> * added monitoring * * Revision 1.33 2007/10/10 09:35:28 Gerrit van Brakel <[email protected]> * Direct copy from Ibis-EJB: * spring enabled version * * Revision 1.32 2007/10/08 12:15:38 Gerrit van Brakel <[email protected]> * corrected date formatting * * Revision 1.31 2007/07/24 08:05:22 Gerrit van Brakel <[email protected]> * added targetDesignDocument attribute * * Revision 1.30 2007/07/10 07:11:45 Gerrit van Brakel <[email protected]> * logging improvements * * Revision 1.29 2007/06/26 12:05:34 Gerrit van Brakel <[email protected]> * tuned logging * * Revision 1.28 2007/05/02 11:23:52 Gerrit van Brakel <[email protected]> * added attribute 'active' * * Revision 1.27 2007/03/14 12:22:10 Gerrit van Brakel <[email protected]> * log results in case of exception, too * * Revision 1.26 2007/02/12 13:44:09 Gerrit van Brakel <[email protected]> * Logger from LogUtil * * Revision 1.25 2006/09/14 14:58:00 Gerrit van Brakel <[email protected]> * added getPipeLine() * * Revision 1.24 2006/09/07 08:35:50 Gerrit van Brakel <[email protected]> * added requestReplyLogging * * Revision 1.23 2006/08/22 12:50:17 Gerrit van Brakel <[email protected]> * moved code for userTransaction to JtaUtil * * Revision 1.22 2006/02/09 07:55:15 Gerrit van Brakel <[email protected]> * name, upSince and lastMessageDate in statistics-summary * * Revision 1.21 2005/12/28 08:34:46 Gerrit van Brakel <[email protected]> * introduced StatisticsKeeper-iteration * * Revision 1.20 2005/10/26 13:16:14 Gerrit van Brakel <[email protected]> * added second default for UserTransactionUrl * * Revision 1.19 2005/10/17 08:51:23 Gerrit van Brakel <[email protected]> * made getMessageKeeper synchronized * * Revision 1.18 2005/08/17 08:12:45 Peter Leeuwenburgh <[email protected]> * NDC updated * * Revision 1.17 2005/08/16 12:33:30 Gerrit van Brakel <[email protected]> * added NDC with correlationId * * Revision 1.16 2005/07/05 12:27:52 Gerrit van Brakel <[email protected]> * added possibility to end processing with an exception * * Revision 1.15 2005/01/13 08:55:15 Gerrit van Brakel <[email protected]> * Make threadContext-attributes available in PipeLineSession * * Revision 1.14 2004/09/08 14:14:41 Gerrit van Brakel <[email protected]> * adjusted error logging * * Revision 1.13 2004/08/19 07:16:21 unknown <[email protected]> * Resolved problem of hanging adapter if stopRunning was called just after the * adapter was set to started * * Revision 1.12 2004/07/06 07:00:44 Gerrit van Brakel <[email protected]> * configure now throws less exceptions * * Revision 1.11 2004/06/30 10:02:23 Gerrit van Brakel <[email protected]> * improved error reporting * * Revision 1.10 2004/06/16 13:08:11 Johan Verrips <[email protected]> * Added configuration error when no pipeline was configured * * Revision 1.9 2004/06/16 12:34:46 Johan Verrips <[email protected]> * Added AutoStart functionality on Adapter * * Revision 1.8 2004/04/28 08:31:41 Johan Verrips <[email protected]> * Added getRunStateAsString function * * Revision 1.7 2004/04/13 11:37:13 Johan Verrips <[email protected]> * When the Adapter was in state "ERROR", it could not be stopped anymore. Fixed it. * * Revision 1.6 2004/04/06 14:52:52 Johan Verrips <[email protected]> * Updated handling of errors in receiver.configure() * * Revision 1.5 2004/03/30 07:29:53 Gerrit van Brakel <[email protected]> * updated javadoc * * Revision 1.4 2004/03/26 10:42:45 Johan Verrips <[email protected]> * added @version tag in javadoc * */ package nl.nn.adapterframework.core; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter; import nl.nn.adapterframework.receivers.ReceiverBase; import nl.nn.adapterframework.util.DateUtils; import nl.nn.adapterframework.util.HasStatistics; import nl.nn.adapterframework.util.LogUtil; import nl.nn.adapterframework.util.MessageKeeper; import nl.nn.adapterframework.util.RunStateEnum; import nl.nn.adapterframework.util.RunStateManager; import nl.nn.adapterframework.util.StatisticsKeeper; import nl.nn.adapterframework.util.StatisticsKeeperIterationHandler; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.springframework.beans.factory.NamedBean; import org.springframework.core.task.TaskExecutor; /** * The Adapter is the central manager in the IBIS Adapterframework, that has knowledge * and uses {@link IReceiver IReceivers} and a {@link PipeLine}. * * <b>responsibility</b><br/> * <ul> * <li>keeping and gathering statistics</li> * <li>processing messages, retrieved from IReceivers</li> * <li>starting and stoppping IReceivers</li> * <li>delivering error messages in a specified format</li> * </ul> * All messages from IReceivers pass through the adapter (multi threaded). * Multiple receivers may be attached to one adapter.<br/> * <br/> * The actual processing of messages is delegated to the {@link PipeLine} * object, which returns a {@link PipeLineResult}. If an error occurs during * the pipeline execution, the state in the <code>PipeLineResult</code> is set * to the state specified by <code>setErrorState</code>, which defaults to "ERROR". * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>className</td><td>nl.nn.adapterframework.pipes.AbstractPipe</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) name}</td><td>name of the Adapter</td><td>&nbsp;</td></tr> * <tr><td>{@link #setDescription(String) description}</td><td>description of the Adapter</td><td>&nbsp;</td></tr> * <tr><td>{@link #setAutoStart(boolean) autoStart}</td><td>controls whether Adapters starts when configuration loads</td><td>true</td></tr> * <tr><td>{@link #setActive(boolean) active}</td> <td>controls whether Adapter is included in configuration. When set <code>false</code> or set to something else as "true", (even set to the empty string), the receiver is not included in the configuration</td><td>true</td></tr> * <tr><td>{@link #setErrorMessageFormatter(String) errorMessageFormatter}</td><td>&nbsp;</td><td>&nbsp;</td></tr> * <tr><td>{@link #setErrorState(String) errorState}</td><td>If an error occurs during * the pipeline execution, the state in the <code>PipeLineResult</code> is set to this state</td><td>ERROR</td></tr> * <tr><td>{@link #setMessageKeeperSize(int) messageKeeperSize}</td><td>number of message displayed in IbisConsole</td><td>10</td></tr> * <tr><td>{@link #setRequestReplyLogging(boolean) requestReplyLogging}</td><td>when <code>true</code>, the request and reply messages will be logged for each request processed</td><td>false</td></tr> * </table></td><td>&nbsp;</td></tr> * </table> * * @version Id * @author Johan Verrips * @see nl.nn.adapterframework.core.IReceiver * @see nl.nn.adapterframework.core.PipeLine * @see nl.nn.adapterframework.util.StatisticsKeeper * @see nl.nn.adapterframework.util.DateUtils * @see nl.nn.adapterframework.util.MessageKeeper * @see nl.nn.adapterframework.core.PipeLineResult * */ public class Adapter implements IAdapter, NamedBean { public static final String version = "$RCSfile: Adapter.java,v $ $Revision: 1.48 $ $Date: 2008-09-04 12:02:27 $"; private Logger log = LogUtil.getLogger(this); private String name; private String targetDesignDocument; private boolean active=true; private Vector receivers = new Vector(); private long lastMessageDate = 0; private PipeLine pipeline; private int numOfMessagesInProcess = 0; private long numOfMessagesProcessed = 0; private long numOfMessagesProcessedMarked = 0; private long numOfMessagesInError = 0; private long numOfMessagesInErrorMarked = 0; private StatisticsKeeper statsMessageProcessingDuration = null; private long statsUpSince = System.currentTimeMillis(); private IErrorMessageFormatter errorMessageFormatter; private RunStateManager runState = new RunStateManager(); private boolean configurationSucceeded = false; private String description; private MessageKeeper messageKeeper; //instantiated in configure() private int messageKeeperSize = 10; //default length private boolean autoStart = true; private boolean requestReplyLogging = false; // state to put in PipeLineResult when a PipeRunException occurs; private String errorState = "ERROR"; private TaskExecutor taskExecutor; /** * Indicates wether the configuration succeeded. * @return boolean */ public boolean configurationSucceeded() { return configurationSucceeded; } /* * This function is called by Configuration.registerAdapter, * to make configuration information available to the Adapter. <br/><br/> * This method also performs * a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes. * @see nl.nn.adapterframework.core.Pipeline#configurePipes */ public void configure() throws ConfigurationException { configurationSucceeded = false; log.debug("configuring adapter [" + getName() + "]"); MessageKeeper messageKeeper = getMessageKeeper(); statsMessageProcessingDuration = new StatisticsKeeper(getName()); if (pipeline == null) { String msg = "No pipeline configured for adapter [" + getName() + "]"; messageKeeper.add(msg); throw new ConfigurationException(msg); } try { pipeline.setAdapter(this); pipeline.configurePipes(); messageKeeper.add("pipeline successfully configured"); Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); log.info("Adapter [" + name + "] is initializing receiver [" + receiver.getName() + "]"); receiver.setAdapter(this); try { receiver.configure(); messageKeeper.add("receiver [" + receiver.getName() + "] successfully configured"); } catch (ConfigurationException e) { error(true, "error initializing receiver [" + receiver.getName() + "]",e); } } configurationSucceeded = true; } catch (ConfigurationException e) { error(true, "error initializing pipeline", e); } } /** * sends a warning to the log and to the messagekeeper of the adapter */ protected void warn(String msg) { log.warn("Adapter [" + getName() + "] "+msg); getMessageKeeper().add("WARNING: " + msg); } /** * sends a warning to the log and to the messagekeeper of the adapter */ protected void error(boolean critical, String msg, Throwable t) { log.error("Adapter [" + getName() + "] "+msg, t); getMessageKeeper().add("ERROR: " + msg+": "+t.getMessage()); // String prefix=critical?"ADPTERROR ":"ADPTWARN "; // fireMonitorEvent(EventTypeEnum.TECHNICAL,critical?SeverityEnum.CRITICAL:SeverityEnum.WARNING, prefix+msg,t); } /** * Increase the number of messages in process */ private void incNumOfMessagesInProcess(long startTime) { synchronized (statsMessageProcessingDuration) { numOfMessagesInProcess++; lastMessageDate = startTime; } } /** * Decrease the number of messages in process */ private synchronized void decNumOfMessagesInProcess(long duration) { synchronized (statsMessageProcessingDuration) { numOfMessagesInProcess--; numOfMessagesProcessed++; statsMessageProcessingDuration.addValue(duration); notifyAll(); } } /** * The number of messages for which processing ended unsuccessfully. */ private void incNumOfMessagesInError() { synchronized (statsMessageProcessingDuration) { numOfMessagesInError++; } } public synchronized String formatErrorMessage( String errorMessage, Throwable t, String originalMessage, String messageID, INamedObject objectInError, long receivedTime) { if (errorMessageFormatter == null) { errorMessageFormatter = new ErrorMessageFormatter(); } // you never can trust an implementation, so try/catch! try { String formattedErrorMessage= errorMessageFormatter.format( errorMessage, t, objectInError, originalMessage, messageID, receivedTime); if (isRequestReplyLogging()) { log.info("Adapter [" + getName() + "] messageId[" + messageID + "] formatted errormessage, result [" + formattedErrorMessage + "]"); } else { if (log.isDebugEnabled()) { log.info("Adapter [" + getName() + "] messageId[" + messageID + "] formatted errormessage, result [" + formattedErrorMessage + "]"); } } return formattedErrorMessage; } catch (Exception e) { String msg = "got error while formatting errormessage, original errorMessage [" + errorMessage + "]"; msg = msg + " from [" + (objectInError == null ? "unknown-null" : objectInError.getName()) + "]"; error(false, "got error while formatting errormessage", e); return errorMessage; } } /** * retrieve the date and time of the last message. */ public String getLastMessageDate() { String result = ""; if (lastMessageDate != 0) result = DateUtils.format(new Date(lastMessageDate), DateUtils.FORMAT_FULL_GENERIC); else result = "-"; return result; } /** * the MessageKeeper is for keeping the last <code>messageKeeperSize</code> * messages available, for instance for displaying it in the webcontrol * @see nl.nn.adapterframework.util.MessageKeeper */ public synchronized MessageKeeper getMessageKeeper() { if (messageKeeper == null) messageKeeper = new MessageKeeper(messageKeeperSize < 1 ? 1 : messageKeeperSize); return messageKeeper; } public void forEachStatisticsKeeper(StatisticsKeeperIterationHandler hski, int action) { Object root=hski.start(); forEachStatisticsKeeperBody(hski,root,action); hski.end(root); } private void doForEachStatisticsKeeperBody(StatisticsKeeperIterationHandler hski, Object adapterData, int action) { hski.handleScalar(adapterData,"messagesInProcess", getNumOfMessagesInProcess()); hski.handleScalar(adapterData,"messagesProcessed", getNumOfMessagesProcessed()); hski.handleScalar(adapterData,"messagesInError", getNumOfMessagesInError()); hski.handleScalar(adapterData,"messagesProcessedThisInterval", getNumOfMessagesProcessed()-numOfMessagesProcessedMarked); hski.handleScalar(adapterData,"messagesInErrorThisInterval", getNumOfMessagesInError()-numOfMessagesInErrorMarked); hski.handleStatisticsKeeper(adapterData, statsMessageProcessingDuration); statsMessageProcessingDuration.performAction(action); if (action==HasStatistics.STATISTICS_ACTION_RESET) { numOfMessagesProcessed=0; numOfMessagesInError=0; numOfMessagesProcessedMarked=0; numOfMessagesInErrorMarked=0; } else { if (action==HasStatistics.STATISTICS_ACTION_MARK) { numOfMessagesProcessedMarked=numOfMessagesProcessed; numOfMessagesInErrorMarked=numOfMessagesInError; } } Object recsData=hski.openGroup(adapterData,getName(),"receivers"); Iterator recIt=getReceiverIterator(); if (recIt.hasNext()) { while (recIt.hasNext()) { IReceiver receiver=(IReceiver) recIt.next(); receiver.iterateOverStatistics(hski,recsData,action); } } hski.closeGroup(recsData); Object pipelineData=hski.openGroup(adapterData,getName(),"pipeline"); Hashtable pipelineStatistics = getPipeLineStatistics(); // sort the Hashtable SortedSet sortedKeys = new TreeSet(pipelineStatistics.keySet()); Iterator pipelineStatisticsIter = sortedKeys.iterator(); Object pipestatData=hski.openGroup(pipelineData,getName(),"pipeStats"); while (pipelineStatisticsIter.hasNext()) { String pipeName = (String) pipelineStatisticsIter.next(); StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName); hski.handleStatisticsKeeper(pipestatData,pstat); pstat.performAction(action); IPipe pipe = pipeline.getPipe(pipeName); if (pipe instanceof HasStatistics) { ((HasStatistics) pipe).iterateOverStatistics(hski, pipestatData,action); } } hski.closeGroup(pipestatData); pipestatData=hski.openGroup(pipelineData,getName(),"idleStats"); pipelineStatistics = getWaitingStatistics(); if (pipelineStatistics.size()>0) { // sort the Hashtable sortedKeys = new TreeSet(pipelineStatistics.keySet()); pipelineStatisticsIter = sortedKeys.iterator(); while (pipelineStatisticsIter.hasNext()) { String pipeName = (String) pipelineStatisticsIter.next(); StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName); hski.handleStatisticsKeeper(pipestatData,pstat); pstat.performAction(action); } } hski.closeGroup(pipestatData); hski.closeGroup(pipelineData); } public void forEachStatisticsKeeperBody(StatisticsKeeperIterationHandler hski, Object data, int action) { Object adapterData=hski.openGroup(data,getName(),"adapter"); hski.handleScalar(adapterData,"name", getName()); hski.handleScalar(adapterData,"upSince", getStatsUpSince()); hski.handleScalar(adapterData,"lastMessageDate", getLastMessageDate()); if (action!=HasStatistics.STATISTICS_ACTION_NONE) { synchronized (statsMessageProcessingDuration) { doForEachStatisticsKeeperBody(hski,adapterData,action); } } else { doForEachStatisticsKeeperBody(hski,adapterData,action); } hski.closeGroup(adapterData); } /** * the functional name of this adapter * @return the name of the adapter */ public String getName() { return name; } /** * The number of messages for which processing ended unsuccessfully. */ public long getNumOfMessagesInError() { synchronized (statsMessageProcessingDuration) { return numOfMessagesInError; } } public int getNumOfMessagesInProcess() { synchronized (statsMessageProcessingDuration) { return numOfMessagesInProcess; } } /** * Total of messages processed * @return long total messages processed */ public long getNumOfMessagesProcessed() { synchronized (statsMessageProcessingDuration) { return numOfMessagesProcessed; } } public Hashtable getPipeLineStatistics() { return pipeline.getPipeStatistics(); } public IReceiver getReceiverByName(String receiverName) { Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); if (receiver.getName().equalsIgnoreCase(receiverName)) { return receiver; } } return null; } public Iterator getReceiverIterator() { return receivers.iterator(); } public PipeLine getPipeLine() { return pipeline; } public RunStateEnum getRunState() { return runState.getRunState(); } public String getRunStateAsString() { return runState.getRunState().toString(); } /** * Return the total processing duration as a StatisticsKeeper * @see nl.nn.adapterframework.util.StatisticsKeeper * @return nl.nn.adapterframework.util.StatisticsKeeper */ public StatisticsKeeper getStatsMessageProcessingDuration() { return statsMessageProcessingDuration; } /** * return the date and time since active * Creation date: (19-02-2003 12:16:53) * @return String Date */ public String getStatsUpSince() { return DateUtils.format(new Date(statsUpSince), DateUtils.FORMAT_FULL_GENERIC); } /** * Retrieve the waiting statistics as a <code>Hashtable</code> */ public Hashtable getWaitingStatistics() { return pipeline.getPipeWaitingStatistics(); } /** * * Process the receiving of a message * After all Pipes have been run in the PipeLineProcessor, the Object.toString() function * is called. The result is returned to the Receiver. * */ public PipeLineResult processMessage(String messageId, String message) { PipeLineSession pls=new PipeLineSession(); Date now=new Date(); PipeLineSession.setListenerParameters(pls,messageId,null,now,now); return processMessage(messageId, message, pls); } public PipeLineResult processMessage(String messageId, String message, PipeLineSession pipeLineSession) { long startTime = System.currentTimeMillis(); try { return processMessageWithExceptions(messageId, message, pipeLineSession); } catch (Throwable t) { PipeLineResult result = new PipeLineResult(); result.setState(getErrorState()); String msg = "Illegal exception ["+t.getClass().getName()+"]"; INamedObject objectInError = null; if (t instanceof ListenerException) { Throwable cause = ((ListenerException) t).getCause(); if (cause instanceof PipeRunException) { PipeRunException pre = (PipeRunException) cause; msg = "error during pipeline processing"; objectInError = pre.getPipeInError(); } else if (cause instanceof ManagedStateException) { msg = "illegal state"; objectInError = this; } } result.setResult(formatErrorMessage(msg, t, message, messageId, objectInError, startTime)); if (isRequestReplyLogging()) { log.info("Adapter [" + getName() + "] messageId [" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } else { if (log.isDebugEnabled()) { log.debug("Adapter [" + getName() + "] messageId [" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } } return result; } } public PipeLineResult processMessageWithExceptions(String messageId, String message, PipeLineSession pipeLineSession) throws ListenerException { PipeLineResult result = new PipeLineResult(); long startTime = System.currentTimeMillis(); // prevent executing a stopped adapter // the receivers should implement this, but you never now.... RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STARTED) && !currentRunState.equals(RunStateEnum.STOPPING)) { String msgAdapterNotOpen = "Adapter [" + getName() + "] in state [" + currentRunState + "], cannot process message"; throw new ListenerException(new ManagedStateException(msgAdapterNotOpen)); } incNumOfMessagesInProcess(startTime); String lastNDC=NDC.peek(); String newNDC="cid [" + messageId + "]"; boolean ndcChanged=!newNDC.equals(lastNDC); if (ndcChanged) { NDC.push(newNDC); } if (isRequestReplyLogging()) { if (log.isInfoEnabled()) log.info("Adapter [" + name + "] received message [" + message + "] with messageId [" + messageId + "]"); } else { if (log.isDebugEnabled()) { log.debug("Adapter [" + name + "] received message [" + message + "] with messageId [" + messageId + "]"); } else { log.info("Adapter [" + name + "] received message with messageId [" + messageId + "]"); } } try { result = pipeline.process(messageId, message,pipeLineSession); if (isRequestReplyLogging()) { log.info("Adapter [" + getName() + "] messageId[" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } else { if (log.isDebugEnabled()) { log.debug("Adapter [" + getName() + "] messageId[" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } } return result; } catch (Throwable t) { ListenerException e; if (t instanceof ListenerException) { e = (ListenerException) t; } else { e = new ListenerException(t); } incNumOfMessagesInError(); error(false, "error processing message with messageId [" + messageId+"]: ",e); throw e; } finally { long endTime = System.currentTimeMillis(); long duration = endTime - startTime; //reset the InProcess fields, and increase processedMessagesCount decNumOfMessagesInProcess(duration); if (log.isDebugEnabled()) { // for performance reasons log.debug("Adapter: [" + getName() + "] STAT: Finished processing message with messageId [" + messageId + "] exit-state [" + result.getState() + "] started " + DateUtils.format(new Date(startTime), DateUtils.FORMAT_FULL_GENERIC) + " finished " + DateUtils.format(new Date(endTime), DateUtils.FORMAT_FULL_GENERIC) + " total duration: " + duration + " msecs"); } else { log.info("Adapter [" + getName() + "] completed message with messageId [" + messageId + "] with exit-state [" + result.getState() + "]"); } if (ndcChanged) { NDC.pop(); } } } /** * Register a PipeLine at this adapter. On registering, the adapter performs * a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes. * @param pipeline * @throws ConfigurationException * @see PipeLine */ public void registerPipeLine(PipeLine pipeline) throws ConfigurationException { this.pipeline = pipeline; pipeline.setAdapter(this); log.debug("Adapter [" + name + "] registered pipeline [" + pipeline.toString() + "]"); } /** * Register a receiver for this Adapter * @param receiver * @see IReceiver */ public void registerReceiver(IReceiver receiver) { boolean receiverActive=true; if (receiver instanceof ReceiverBase) { receiverActive=((ReceiverBase)receiver).isActive(); } if (receiverActive) { receivers.add(receiver); log.debug("Adapter [" + name + "] registered receiver [" + receiver.getName() + "] with properties [" + receiver.toString() + "]"); } else { log.debug("Adapter [" + name + "] did not register inactive receiver [" + receiver.getName() + "] with properties [" + receiver.toString() + "]"); } } /** * some functional description of the <code>Adapter</code>/ */ public void setDescription(String description) { this.description = description; } public String getDescription() { return this.description; } /** * Register a <code>ErrorMessageFormatter</code> as the formatter * for this <code>adapter</code> * @param errorMessageFormatter * @see IErrorMessageFormatter */ public void setErrorMessageFormatter(IErrorMessageFormatter errorMessageFormatter) { this.errorMessageFormatter = errorMessageFormatter; } /** * state to put in PipeLineResult when a PipeRunException occurs * @param newErrorState java.lang.String * @see PipeLineResult */ public void setErrorState(java.lang.String newErrorState) { errorState = newErrorState; } /** * state to put in PipeLineResult when a PipeRunException occurs. */ public String getErrorState() { return errorState; } /** * Set the number of messages that are kept on the screen. * @param size * @see nl.nn.adapterframework.util.MessageKeeper */ public void setMessageKeeperSize(int size) { this.messageKeeperSize = size; } /** * the functional name of this adapter */ public void setName(String name) { this.name = name; } /** * Start the adapter. The thread-name will be set tot the adapter's name. * The run method, called by t.start(), will call the startRunning method * of the IReceiver. The Adapter will be a new thread, as this interface * extends the <code>Runnable</code> interface. The actual starting is done * in the <code>run</code> method. * @see IReceiver#startRunning() * @see Adapter#run */ public void startRunning() { taskExecutor.execute(new Runnable() { public void run() { Thread.currentThread().setName("starting Adapter "+getName()); try { if (!configurationSucceeded) { log.error( "configuration of adapter [" + getName() + "] did not succeed, therefore starting the adapter is not possible"); warn("configuration did not succeed. Starting the adapter is not possible"); runState.setRunState(RunStateEnum.ERROR); return; } synchronized (runState) { RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STOPPED)) { String msg = "currently in state [" + currentRunState + "], ignoring start() command"; warn(msg); return; } // start the pipeline runState.setRunState(RunStateEnum.STARTING); } try { log.debug("Adapter [" + getName() + "] is starting pipeline"); pipeline.start(); } catch (PipeStartException pre) { error(true, "got error starting PipeLine", pre); runState.setRunState(RunStateEnum.ERROR); return; } // as from version 3.0 the adapter is started, // regardless of receivers are correctly started. runState.setRunState(RunStateEnum.STARTED); getMessageKeeper().add("Adapter up and running"); log.info("Adapter [" + getName() + "] up and running"); // starting receivers Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); if (receiver.getRunState() != RunStateEnum.ERROR) { log.info("Adapter [" + getName() + "] is starting receiver [" + receiver.getName() + "]"); receiver.startRunning(); } else log.warn("Adapter [" + getName() + "] will NOT start receiver [" + receiver.getName() + "] as it is in state ERROR"); } //while // // wait until the stopRunning is called // waitForRunState(RunStateEnum.STOPPING); } catch (Throwable t) { error(true, "got error starting Adapter", t); log.error("error running adapter [" + getName() + "]", t); runState.setRunState(RunStateEnum.ERROR); } } // End Runnable.run() }); // End Runnable } // End startRunning() /** * Stop the <code>Adapter</code> and close all elements like receivers, * Pipeline, pipes etc. * The adapter * will call the <code>IReceiver</code> to <code>stopListening</code> * <p>Also the <code>PipeLine.close()</code> method will be called, * closing alle registered pipes. </p> * @see IReceiver#stopRunning * @see PipeLine#stop */ public void stopRunning() { synchronized (runState) { RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STARTED) && (!currentRunState.equals(RunStateEnum.ERROR))) { warn("in state [" + currentRunState + "] while stopAdapter() command is issued, ignoring command"); return; } if (currentRunState.equals(RunStateEnum.ERROR)) { runState.setRunState(RunStateEnum.STOPPED); return; } runState.setRunState(RunStateEnum.STOPPING); } taskExecutor.execute(new Runnable() { public void run() { Thread.currentThread().setName("stopping Adapter " +getName()); try { log.debug("Adapter [" + name + "] is stopping receivers"); Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); try { receiver.stopRunning(); log.info("Adapter [" + name + "] successfully stopped receiver [" + receiver.getName() + "]"); } catch (Exception e) { error(false, "received error while stopping receiver [" + receiver.getName() + "], ignoring this, so watch out.", e); } } // stop the adapter log.debug("***stopping adapter"); it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); receiver.waitForRunState(RunStateEnum.STOPPED); log.info("Adapter [" + getName() + "] stopped [" + receiver.getName() + "]"); } int currentNumOfMessagesInProcess = getNumOfMessagesInProcess(); if (currentNumOfMessagesInProcess > 0) { String msg = "Adapter [" + name + "] is being stopped while still processing " + currentNumOfMessagesInProcess + " messages, waiting for them to finish"; warn(msg); } waitForNoMessagesInProcess(); log.debug("Adapter [" + name + "] is stopping pipeline"); pipeline.stop(); runState.setRunState(RunStateEnum.STOPPED); getMessageKeeper().add("Adapter stopped"); } catch (Throwable e) { log.error("error running adapter [" + getName() + "] [" + ToStringBuilder.reflectionToString(e) + "]", e); runState.setRunState(RunStateEnum.ERROR); } } // End of run() }); // End of Runnable } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[name=" + name + "]"); sb.append("[version=" + version + "]"); sb.append("[targetDesignDocument=" + targetDesignDocument + "]"); Iterator it = receivers.iterator(); sb.append("[receivers="); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); sb.append(" " + receiver.getName()); } sb.append("]"); sb.append( "[pipeLine=" + ((pipeline != null) ? pipeline.toString() : "none registered") + "]" + "[started=" + getRunState() + "]"); return sb.toString(); } public void waitForNoMessagesInProcess() throws InterruptedException { synchronized (statsMessageProcessingDuration) { while (getNumOfMessagesInProcess() > 0) { wait(); } } } public void waitForRunState(RunStateEnum requestedRunState) throws InterruptedException { runState.waitForRunState(requestedRunState); } public boolean waitForRunState(RunStateEnum requestedRunState, long maxWait) throws InterruptedException { return runState.waitForRunState(requestedRunState, maxWait); } /** * AutoStart indicates that the adapter should be started when the configuration * is started. AutoStart defaults to <code>true</code> * @since 4.1.1 */ public void setAutoStart(boolean autoStart) { this.autoStart = autoStart; } public boolean isAutoStart() { return autoStart; } public void setRequestReplyLogging(boolean requestReplyLogging) { this.requestReplyLogging = requestReplyLogging; } public boolean isRequestReplyLogging() { return requestReplyLogging; } public void setActive(boolean b) { active = b; } public boolean isActive() { return active; } public void setTargetDesignDocument(String string) { targetDesignDocument = string; } public String getTargetDesignDocument() { return targetDesignDocument; } public void setTaskExecutor(TaskExecutor executor) { taskExecutor = executor; } public TaskExecutor getTaskExecutor() { return taskExecutor; } /* (non-Javadoc) * @see org.springframework.beans.factory.NamedBean#getBeanName() */ public String getBeanName() { return name; } }
use CounterStatistics for counters changed references to Hashtable to Map output statistics in order of Pipes
JavaSource/nl/nn/adapterframework/core/Adapter.java
use CounterStatistics for counters changed references to Hashtable to Map output statistics in order of Pipes
<ide><path>avaSource/nl/nn/adapterframework/core/Adapter.java <ide> /* <ide> * $Log: Adapter.java,v $ <del> * Revision 1.48 2008-09-04 12:02:27 europe\L190409 <add> * Revision 1.49 2008-09-22 13:28:45 europe\L190409 <add> * use CounterStatistics for counters <add> * changed references to Hashtable to Map <add> * output statistics in order of Pipes <add> * <add> * Revision 1.48 2008/09/04 12:02:27 Gerrit van Brakel <[email protected]> <ide> * collect interval statistics <ide> * <ide> * Revision 1.47 2008/08/27 15:54:07 Gerrit van Brakel <[email protected]> <ide> import java.util.Date; <ide> import java.util.Hashtable; <ide> import java.util.Iterator; <add>import java.util.Map; <add>import java.util.Set; <ide> import java.util.SortedSet; <ide> import java.util.TreeSet; <ide> import java.util.Vector; <ide> import nl.nn.adapterframework.util.MessageKeeper; <ide> import nl.nn.adapterframework.util.RunStateEnum; <ide> import nl.nn.adapterframework.util.RunStateManager; <add>import nl.nn.adapterframework.util.CounterStatistic; <ide> import nl.nn.adapterframework.util.StatisticsKeeper; <ide> import nl.nn.adapterframework.util.StatisticsKeeperIterationHandler; <ide> <ide> */ <ide> <ide> public class Adapter implements IAdapter, NamedBean { <del> public static final String version = "$RCSfile: Adapter.java,v $ $Revision: 1.48 $ $Date: 2008-09-04 12:02:27 $"; <add> public static final String version = "$RCSfile: Adapter.java,v $ $Revision: 1.49 $ $Date: 2008-09-22 13:28:45 $"; <ide> private Logger log = LogUtil.getLogger(this); <ide> <ide> private String name; <ide> <ide> private int numOfMessagesInProcess = 0; <ide> <del> private long numOfMessagesProcessed = 0; <del> private long numOfMessagesProcessedMarked = 0; <del> <del> private long numOfMessagesInError = 0; <del> private long numOfMessagesInErrorMarked = 0; <add> private CounterStatistic numOfMessagesProcessed = new CounterStatistic(0); <add> private CounterStatistic numOfMessagesInError = new CounterStatistic(0); <ide> <ide> private StatisticsKeeper statsMessageProcessingDuration = null; <ide> <ide> private synchronized void decNumOfMessagesInProcess(long duration) { <ide> synchronized (statsMessageProcessingDuration) { <ide> numOfMessagesInProcess--; <del> numOfMessagesProcessed++; <add> numOfMessagesProcessed.increase(); <ide> statsMessageProcessingDuration.addValue(duration); <ide> notifyAll(); <ide> } <ide> */ <ide> private void incNumOfMessagesInError() { <ide> synchronized (statsMessageProcessingDuration) { <del> numOfMessagesInError++; <add> numOfMessagesInError.increase(); <ide> } <ide> } <ide> <ide> hski.handleScalar(adapterData,"messagesInProcess", getNumOfMessagesInProcess()); <ide> hski.handleScalar(adapterData,"messagesProcessed", getNumOfMessagesProcessed()); <ide> hski.handleScalar(adapterData,"messagesInError", getNumOfMessagesInError()); <del> hski.handleScalar(adapterData,"messagesProcessedThisInterval", getNumOfMessagesProcessed()-numOfMessagesProcessedMarked); <del> hski.handleScalar(adapterData,"messagesInErrorThisInterval", getNumOfMessagesInError()-numOfMessagesInErrorMarked); <add> hski.handleScalar(adapterData,"messagesProcessedThisInterval", numOfMessagesProcessed.getIntervalValue()); <add> hski.handleScalar(adapterData,"messagesInErrorThisInterval", numOfMessagesInError.getIntervalValue()); <ide> hski.handleStatisticsKeeper(adapterData, statsMessageProcessingDuration); <ide> statsMessageProcessingDuration.performAction(action); <del> <del> if (action==HasStatistics.STATISTICS_ACTION_RESET) { <del> numOfMessagesProcessed=0; <del> numOfMessagesInError=0; <del> numOfMessagesProcessedMarked=0; <del> numOfMessagesInErrorMarked=0; <del> } else { <del> if (action==HasStatistics.STATISTICS_ACTION_MARK) { <del> numOfMessagesProcessedMarked=numOfMessagesProcessed; <del> numOfMessagesInErrorMarked=numOfMessagesInError; <del> } <del> } <add> numOfMessagesProcessed.performAction(action); <add> numOfMessagesInError.performAction(action); <ide> Object recsData=hski.openGroup(adapterData,getName(),"receivers"); <ide> Iterator recIt=getReceiverIterator(); <ide> if (recIt.hasNext()) { <ide> <ide> Object pipelineData=hski.openGroup(adapterData,getName(),"pipeline"); <ide> <del> Hashtable pipelineStatistics = getPipeLineStatistics(); <del> // sort the Hashtable <del> SortedSet sortedKeys = new TreeSet(pipelineStatistics.keySet()); <del> Iterator pipelineStatisticsIter = sortedKeys.iterator(); <add> Map pipelineStatistics = getPipeLineStatistics(); <ide> Object pipestatData=hski.openGroup(pipelineData,getName(),"pipeStats"); <ide> <del> while (pipelineStatisticsIter.hasNext()) { <del> String pipeName = (String) pipelineStatisticsIter.next(); <add> for(Iterator it=getPipeLine().getPipes().iterator();it.hasNext();) { <add> IPipe pipe = (IPipe)it.next(); <add> String pipeName = pipe.getName(); <add> <ide> StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName); <ide> hski.handleStatisticsKeeper(pipestatData,pstat); <ide> pstat.performAction(action); <del> IPipe pipe = pipeline.getPipe(pipeName); <ide> if (pipe instanceof HasStatistics) { <ide> ((HasStatistics) pipe).iterateOverStatistics(hski, pipestatData,action); <ide> } <ide> } <ide> hski.closeGroup(pipestatData); <ide> <del> <del> pipestatData=hski.openGroup(pipelineData,getName(),"idleStats"); <ide> pipelineStatistics = getWaitingStatistics(); <ide> if (pipelineStatistics.size()>0) { <del> // sort the Hashtable <del> sortedKeys = new TreeSet(pipelineStatistics.keySet()); <del> pipelineStatisticsIter = sortedKeys.iterator(); <del> <del> while (pipelineStatisticsIter.hasNext()) { <del> String pipeName = (String) pipelineStatisticsIter.next(); <add> pipestatData=hski.openGroup(pipelineData,getName(),"idleStats"); <add> <add> for(Iterator it=getPipeLine().getPipes().iterator();it.hasNext();) { <add> IPipe pipe = (IPipe)it.next(); <add> String pipeName = pipe.getName(); <ide> StatisticsKeeper pstat = (StatisticsKeeper) pipelineStatistics.get(pipeName); <ide> hski.handleStatisticsKeeper(pipestatData,pstat); <ide> pstat.performAction(action); <ide> } <del> } <del> hski.closeGroup(pipestatData); <add> hski.closeGroup(pipestatData); <add> } <ide> hski.closeGroup(pipelineData); <ide> } <ide> <ide> */ <ide> public long getNumOfMessagesInError() { <ide> synchronized (statsMessageProcessingDuration) { <del> return numOfMessagesInError; <add> return numOfMessagesInError.getValue(); <ide> } <ide> } <ide> public int getNumOfMessagesInProcess() { <ide> */ <ide> public long getNumOfMessagesProcessed() { <ide> synchronized (statsMessageProcessingDuration) { <del> return numOfMessagesProcessed; <del> } <del> } <del> public Hashtable getPipeLineStatistics() { <add> return numOfMessagesProcessed.getValue(); <add> } <add> } <add> public Map getPipeLineStatistics() { <ide> return pipeline.getPipeStatistics(); <ide> } <ide> public IReceiver getReceiverByName(String receiverName) { <ide> /** <ide> * Retrieve the waiting statistics as a <code>Hashtable</code> <ide> */ <del> public Hashtable getWaitingStatistics() { <add> public Map getWaitingStatistics() { <ide> return pipeline.getPipeWaitingStatistics(); <ide> } <ide> /**
Java
mit
df8b402de23dd3c08e111585c194440d8e386643
0
buzztaiki/jenova
/* * Copyright (C) 2012 Taiki Sugawara * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.buzztaiki.jenova; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.model.JavacElements; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import java.util.Map; public class LambdaTransformer { private final Map<String, InterfaceMethod> ifMethods; private final TreeMaker maker; private final TreeInfo info; private final JavacElements elems; public LambdaTransformer(Context context, Map<String, InterfaceMethod> ifMethods) { this.ifMethods = ifMethods; this.maker = TreeMaker.instance(context); this.info = TreeInfo.instance(context); this.elems = JavacElements.instance(context); } public JCTree.JCNewClass transform(JCTree.JCNewClass fn) { InterfaceMethod ifMethod = ifMethods.get(info.name(fn.getIdentifier()).toString()); if (ifMethod != null) return transform(fn, ifMethod); return fn; } private JCTree.JCNewClass transform(JCTree.JCNewClass fn, InterfaceMethod ifMethod) { JCTree.JCClassDecl body = fn.getClassBody(); JCTree.JCBlock initBlock = initBlock(body); List<JCTree.JCExpression> typeArgs = appliedTypes(fn.getIdentifier()); JCTree.JCMethodDecl method = maker.MethodDef( maker.Modifiers(Flags.PUBLIC), ifMethod.getMethod().flatName(), ifMethod.getReturnType(typeArgs), List.<JCTree.JCTypeParameter>nil(), args(ifMethod.getParamTypes(typeArgs)), List.<JCTree.JCExpression>nil(), initBlock, null); return newClass( fn, ifMethod.getClazz(), classBody(body, method)); } private JCTree.JCExpression ident(JCTree.JCExpression orig, Symbol nameSymbol) { JCTree.JCExpression ident = maker.Ident(nameSymbol); List<JCTree.JCExpression> typeArgs = appliedTypes(orig); if (!typeArgs.isEmpty()) return maker.TypeApply(ident, typeArgs); return ident; } private List<JCTree.JCExpression> appliedTypes(JCTree.JCExpression ident) { if (ident instanceof JCTree.JCTypeApply) { JCTree.JCTypeApply ta = (JCTree.JCTypeApply)ident; return ta.getTypeArguments(); } return List.nil(); } private JCTree.JCBlock initBlock(JCTree.JCClassDecl body) { for (JCTree member : body.getMembers()) { if (member instanceof JCTree.JCBlock) return (JCTree.JCBlock)member; } throw new IllegalArgumentException("Init block not found."); } private JCTree.JCVariableDecl arg(String name, JCTree.JCExpression vartype) { return maker.VarDef(maker.Modifiers(0), elems.getName(name), vartype, null); } private List<JCTree.JCVariableDecl> args(List<JCTree.JCExpression> paramTypes) { ListBuffer<JCTree.JCVariableDecl> args = new ListBuffer<JCTree.JCVariableDecl>(); int i = 1; for (JCTree.JCExpression paramType : paramTypes) { args.append(arg("_" + i++, paramType)); } return args.toList(); } private JCTree.JCClassDecl classBody(JCTree.JCClassDecl orig, JCTree.JCMethodDecl method) { return maker.AnonymousClassDef( orig.getModifiers(), List.<JCTree>of(method)); } private JCTree.JCNewClass newClass(JCTree.JCNewClass orig, Symbol nameSymbol, JCTree.JCClassDecl classBody) { return maker.NewClass( orig.getEnclosingExpression(), orig.getTypeArguments(), ident(orig.getIdentifier(), nameSymbol), orig.getArguments(), classBody); } }
src/main/java/com/github/buzztaiki/jenova/LambdaTransformer.java
/* * Copyright (C) 2012 Taiki Sugawara * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.buzztaiki.jenova; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.model.JavacElements; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.TreeInfo; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; import java.util.Map; public class LambdaTransformer { private final Map<String, InterfaceMethod> ifMethods; private final TreeMaker maker; private final TreeInfo info; private final JavacElements elems; public LambdaTransformer(Context context, Map<String, InterfaceMethod> ifMethods) { this.ifMethods = ifMethods; this.maker = TreeMaker.instance(context); this.info = TreeInfo.instance(context); this.elems = JavacElements.instance(context); } public JCTree.JCNewClass transform(JCTree.JCNewClass fn) { InterfaceMethod ifMethod = ifMethods.get(info.name(fn.getIdentifier()).toString()); if (ifMethod != null) return transform(fn, ifMethod); return fn; } private JCTree.JCNewClass transform(JCTree.JCNewClass fn, InterfaceMethod ifMethod) { JCTree.JCClassDecl body = fn.getClassBody(); JCTree.JCBlock initBlock = initBlock(body); List<JCTree.JCExpression> typeArgs = appliedTypes(fn.getIdentifier()); JCTree.JCMethodDecl method = maker.MethodDef( maker.Modifiers(Flags.PUBLIC), ifMethod.getMethod().flatName(), ifMethod.getReturnType(typeArgs), List.<JCTree.JCTypeParameter>nil(), args(ifMethod.getParamTypes(typeArgs)), List.<JCTree.JCExpression>nil(), initBlock, null); return newClass( fn, ifMethod.getClazz(), classBody(body, method)); } private JCTree.JCExpression ident(JCTree.JCExpression orig, Symbol nameSymbol) { JCTree.JCExpression ident = maker.Ident(nameSymbol); List<JCTree.JCExpression> typeArgs = appliedTypes(orig); if (!typeArgs.isEmpty()) return maker.TypeApply(ident, typeArgs); return ident; } private List<JCTree.JCExpression> appliedTypes(JCTree.JCExpression ident) { if (ident instanceof JCTree.JCTypeApply) { JCTree.JCTypeApply ta = (JCTree.JCTypeApply)ident; return ta.getTypeArguments(); } return List.nil(); } private JCTree.JCBlock initBlock(JCTree.JCClassDecl body) { for (JCTree member : body.getMembers()) { if (member instanceof JCTree.JCBlock) return (JCTree.JCBlock)member; } throw new IllegalArgumentException("Init block not found."); } private JCTree.JCVariableDecl arg(String name, JCTree.JCExpression vartype) { return maker.VarDef(maker.Modifiers(0), elems.getName(name), vartype, null); } private List<JCTree.JCVariableDecl> args(List<JCTree.JCExpression> paramTypes) { ListBuffer<JCTree.JCVariableDecl> args = new ListBuffer<JCTree.JCVariableDecl>(); int i = 1; for (JCTree.JCExpression paramType : paramTypes) { args.append(arg("_" + i++, paramType)); } return args.toList(); } private JCTree.JCClassDecl classBody(JCTree.JCClassDecl orig, JCTree.JCMethodDecl method) { return maker.ClassDef( orig.getModifiers(), orig.getSimpleName(), orig.getTypeParameters(), orig.getExtendsClause(), // TODO: compile failed when java7 orig.getImplementsClause(), List.<JCTree>of(method)); } private JCTree.JCNewClass newClass(JCTree.JCNewClass orig, Symbol nameSymbol, JCTree.JCClassDecl classBody) { return maker.NewClass( orig.getEnclosingExpression(), orig.getTypeArguments(), ident(orig.getIdentifier(), nameSymbol), orig.getArguments(), classBody); } }
Support java7 at runtime.
src/main/java/com/github/buzztaiki/jenova/LambdaTransformer.java
Support java7 at runtime.
<ide><path>rc/main/java/com/github/buzztaiki/jenova/LambdaTransformer.java <ide> } <ide> <ide> private JCTree.JCClassDecl classBody(JCTree.JCClassDecl orig, JCTree.JCMethodDecl method) { <del> return maker.ClassDef( <add> return maker.AnonymousClassDef( <ide> orig.getModifiers(), <del> orig.getSimpleName(), <del> orig.getTypeParameters(), <del> orig.getExtendsClause(), // TODO: compile failed when java7 <del> orig.getImplementsClause(), <ide> List.<JCTree>of(method)); <ide> } <ide>
JavaScript
apache-2.0
9006a6fc06c76849dbd9b6b96913ec5a911bd7b0
0
shopgate/theme-gmd
import { connect } from 'react-redux'; import { historyPush } from '@shopgate/pwa-common/actions/router'; /** * Connects the dispatch function to a callable function in the props. * @param {Function} dispatch The redux dispatch function. * @return {Object} The extended component props. */ const mapDispatchToProps = dispatch => ({ navigate: (pathname, target) => dispatch(historyPush({ pathname, ...target && { state: { target } }, })), }); export default connect(null, mapDispatchToProps, null, { pure: () => true });
widgets/Html/connector.js
import { connect } from 'react-redux'; import { historyPush } from '@shopgate/pwa-common/actions/router'; /** * Connects the dispatch function to a callable function in the props. * @param {Function} dispatch The redux dispatch function. * @return {Object} The extended component props. */ const mapDispatchToProps = dispatch => ({ navigate: params => dispatch(historyPush(params)), }); export default connect(null, mapDispatchToProps, null, { pure: () => true });
PWA-1774 Added an additional test for the MediaProvider base class
widgets/Html/connector.js
PWA-1774 Added an additional test for the MediaProvider base class
<ide><path>idgets/Html/connector.js <ide> * @return {Object} The extended component props. <ide> */ <ide> const mapDispatchToProps = dispatch => ({ <del> navigate: params => dispatch(historyPush(params)), <add> navigate: (pathname, target) => dispatch(historyPush({ <add> pathname, <add> ...target && { state: { target } }, <add> })), <ide> }); <ide> <ide> export default connect(null, mapDispatchToProps, null, { pure: () => true });
Java
apache-2.0
error: pathspec 'tracing/src/test/java/com/palantir/remoting3/tracing/CloseableTracerTest.java' did not match any file(s) known to git
8db29cbd4e5152955fa688bd65b7f333fc289348
1
palantir/http-remoting,palantir/http-remoting
/* * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.remoting3.tracing; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public final class CloseableTracerTest { @Test public void startsAndClosesSpan() { try (CloseableTracer tracer = CloseableTracer.startSpan("foo")) { assertThat(Tracer.copyTrace().isEmpty()).isFalse(); } assertThat(Tracer.copyTrace().isEmpty()).isTrue(); } }
tracing/src/test/java/com/palantir/remoting3/tracing/CloseableTracerTest.java
Add CloseableTracerTest (#718)
tracing/src/test/java/com/palantir/remoting3/tracing/CloseableTracerTest.java
Add CloseableTracerTest (#718)
<ide><path>racing/src/test/java/com/palantir/remoting3/tracing/CloseableTracerTest.java <add>/* <add> * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package com.palantir.remoting3.tracing; <add> <add>import static org.assertj.core.api.Assertions.assertThat; <add> <add>import org.junit.Test; <add>import org.junit.runner.RunWith; <add>import org.mockito.runners.MockitoJUnitRunner; <add> <add>@RunWith(MockitoJUnitRunner.class) <add>public final class CloseableTracerTest { <add> <add> @Test <add> public void startsAndClosesSpan() { <add> try (CloseableTracer tracer = CloseableTracer.startSpan("foo")) { <add> assertThat(Tracer.copyTrace().isEmpty()).isFalse(); <add> } <add> assertThat(Tracer.copyTrace().isEmpty()).isTrue(); <add> } <add>}
JavaScript
mit
d201f6ea1e21de577122baeed5b506217e4d8029
0
mainelander/three.js,Kasual666/WebGl,MasterJames/three.js,fomenyesu/three.js,Cakin-Kwong/three.js,brason/three.js,fraguada/three.js,jeromeetienne/three.js,Pro/three.js,kkjeer/three.js,gsssrao/three.js,Kasual666/WebGl,quinonez/three.js,sweetmandm/three.js,coffeine-009/three.js,leeric92/three.js,Jerdak/three.js,fta2012/three.js,ThiagoGarciaAlves/three.js,ma-tech/three.js,HongJunLi/three.js,Ludobaka/three.js,freekh/three.js,agnivade/three.js,shanmugamss/three.js-modified,lovewitty/three.js,ZhenxingWu/three.js,zodsoft/three.js,RemusMar/three.js,r8o8s1e0/three.js,ducminhn/three.js,mrdoob/three.js,rfm1201/rfm.three.js,yuhualingfeng/three.js,ZhenxingWu/three.js,dubejf/three.js,mrkev/three.js,SatoshiKawabata/three.js,nadirhamid/three.js,lag945/three.js,gwindes/three.js,dglogik/three.js,0merta/three.js,hacksalot/three.js,programulya/three.js,yuhualingfeng/three.js,Meshu/three.js,davidvmckay/three.js,stanford-gfx/three.js,YajunQiu/three.js,MetaStackers/three.js,quinonez/three.js,zhangwenyan/three.js,surround-io/three.js,archilogic-com/three.js,srifqi/three.js,Zerschmetterling91/three.js,nhalloran/three.js,stevenliujw/three.js,zeropaper/three.js,RemusMar/three.js,ThiagoGarciaAlves/three.js,fyoudine/three.js,mrdoob/three.js,NicolasRannou/three.js,LeoEatle/three.js,jango2015/three.js,AntTech/three.js,Mugen87/three.js,gveltri/three.js,bhouston/three.js,kkjeer/three.js,JingYongWang/three.js,3DGEOM/three.js,Jerdak/three.js,Astrak/three.js,111t8e/three.js,amakaroff82/three.js,pailhead/three.js,enche/three.js,erich666/three.js,sebasbaumh/three.js,g-rocket/three.js,Astrak/three.js,jbaicoianu/three.js,mataron/three.js,googlecreativelab/three.js,fluxio/three.js,Aldrien-/three.js,prabhu-k/three.js,ndebeiss/three.js,RAtechntukan/three.js,matthiascy/three.js,aleen42/three.js,HongJunLi/three.js,acrsteiner/three.js,Meshu/three.js,UnboundVR/three.js,Amritesh/three.js,wanby/three.js,mabo77/three.js,ma-tech/three.js,agnivade/three.js,rougier/three.js,shinate/three.js,AntTech/three.js,thomasxu1991/three.js,ngokevin/three.js,prabhu-k/three.js,sufeiou/three.js,chaoallsome/three.js,mese79/three.js,liammagee/three.js,brason/three.js,liusashmily/three.js,richtr/three.js,pletzer/three.js,blokhin/three.js,tdmsinc/three.js,applexiaohao/three.js,ikerr/three.js,godlzr/Three.js,gpranay4/three.js,Samsung-Blue/three.js,technohippy/three.js,liammagee/three.js,looeee/three.js,threejsworker/three.js,elisee/three.js,godlzr/Three.js,Kasual666/WebGl,mudithkr/three.js,edge/three.js,Nitrillo/three.js,jango2015/three.js,ondys/three.js,g-rocket/three.js,colombod/three.js,leeric92/three.js,06wj/three.js,Peekmo/three.js,3DGEOM/three.js,byhj/three.js,alexconlin/three.js,Cakin-Kwong/three.js,nraynaud/three.js,mainelander/three.js,mrkev/three.js,Aldrien-/three.js,luxigo/three.js,jllodra/three.js,spite/three.js,dayo7116/three.js,yxxme/three.js,Gheehnest/three.js,rayantony/three.js,Joeldk/three.js,brianchirls/three.js,snipermiller/three.js,robsix/3ditor,jeffgoku/three.js,Jonham/three.js,matgr1/three.js,Stinkdigital/three.js,missingdays/three.js-amd,mabo77/three.js,liammagee/three.js,SpinVR/three.js,fraguada/three.js,byhj/three.js,Joeldk/three.js,carlosanunes/three.js,surround-io/three.js,rlugojr/three.js,Peekmo/three.js,jayhetee/three.js,edivancamargo/three.js,gpranay4/three.js,ducminhn/three.js,sreith1/three.js,Delejnr/three.js,lollerbus/three.js,jbaicoianu/three.js,haozi23333/three.js,thomasxu1991/three.js,lchl7890987/WebGL,pharos3d/three.js,redheli/three.js,ZhenxingWu/three.js,humbletim/three.js,TristanVALCKE/three.js,hedgerh/three.js,Jozain/three.js,imshibaji/three.js,robmyers/three.js,swieder227/three.js,byhj/three.js,blokhin/three.js,Peekmo/three.js,prabhu-k/three.js,Jericho25/three.js,jayschwa/three.js,aleen42/three.js,ducminhn/three.js,dhritzkiv/three.js,threejsworker/three.js,sitexa/three.js,redheli/three.js,yifanhunyc/three.js,donmccurdy/three.js,hedgerh/three.js,chaoallsome/three.js,liusashmily/three.js,rougier/three.js,ngokevin/three-dev,Mugen87/three.js,godlzr/Three.js,Stinkdigital/three.js,plepers/three.js,q437634645/three.js,WestLangley/three.js,Delejnr/three.js,holmberd/three.js,erich666/three.js,bdysvik/three.js,Benjamin-Dobell/three.js,dubejf/three.js,Ludobaka/three.js,MasterJames/three.js,eq0rip/three.js,kkjeer/three.js,mrkev/three.js,JamesHagerman/three.js,r8o8s1e0/three.js,fraguada/three.js,JamesHagerman/three.js,snovak/three.js,gwindes/three.js,sole/three.js,mhoangvslev/data-visualizer,nraynaud/three.js,fanzhanggoogle/three.js,yuhualingfeng/three.js,AlexanderMazaletskiy/three.js,huobaowangxi/three.js,HongJunLi/three.js,JeckoHeroOrg/three.js,julapy/three.js,Stinkdigital/three.js,unconed/three.js,spite/three.js,supergometan/three.js,ThiagoGarciaAlves/three.js,p5150j/three.js,supergometan/three.js,jpweeks/three.js,godlzr/Three.js,AdactiveSAS/three.js,brianchirls/three.js,WoodMath/three.js,yifanhunyc/three.js,archilogic-ch/three.js,jayschwa/three.js,AdactiveSAS/three.js,zhangwenyan/three.js,pailhead/three.js,matthiascy/three.js,richtr/three.js,HongJunLi/three.js,BenediktS/three.js,HongJunLi/three.js,ValtoLibraries/ThreeJS,ZAAK-ZURICHBERLIN/ZAAK.IO-Editor,sreith1/three.js,Ludobaka/three.js,dyx/three.js,fluxio/three.js,jostschmithals/three.js,framelab/three.js,archilogic-ch/three.js,lag945/three.js,Jericho25/three.js,Mohammed-Ashour/three.js,borismus/three.js,cc272309126/three.js,kangax/three.js,dubejf/three.js,dayo7116/three.js,archcomet/three.js,toguri/three.js,tamarintech/three.js,RemusMar/three.js,arose/three.js,Ymaril/three.js,TristanVALCKE/three.js,prabhu-k/three.js,AlexanderMazaletskiy/three.js,tschw/three.js,coffeine-009/three.js,brickify/three.js,IceCreamYou/three.js,fanzhanggoogle/three.js,bhouston/three.js,Jerdak/three.js,Joeldk/three.js,Black-Alpha/three.js,jayschwa/three.js,lag945/three.js,nadirhamid/three.js,sreith1/three.js,yuhualingfeng/three.js,0merta/three.js,flimshaw/three.js,ValtoLibraries/ThreeJS,zodsoft/three.js,Kakakakakku/three.js,alexconlin/three.js,yxxme/three.js,dforrer/three.js,Dewb/three.js,technohippy/three.js,archcomet/three.js,Jericho25/three.js,SpinVR/three.js,sitexa/three.js,aleen42/three.js,sreith1/three.js,shinate/three.js,dimensia/three.js,mhoangvslev/data-visualizer,nraynaud/three.js,sheafferusa/three.js,Hectate/three.js,VimVincent/three.js,amakaroff82/three.js,wavesoft/three.js,jee7/three.js,q437634645/three.js,vizorvr/three.js,sitexa/three.js,simonThiele/three.js,Kasual666/WebGl,holmberd/three.js,Joeldk/three.js,zeropaper/three.js,sebasbaumh/three.js,gigakiller/three.js,alexconlin/three.js,xundaokeji/three.js,VimVincent/three.js,SpookW/three.js,controlzee/three.js,lchl7890987/WebGL,simonThiele/three.js,yifanhunyc/three.js,tdmsinc/three.js,fomenyesu/three.js,liammagee/three.js,carlosanunes/three.js,Astrak/three.js,stopyransky/three.js,elisee/three.js,bdysvik/three.js,DeanLym/three.js,camellhf/three.js,GammaGammaRay/three.js,kangax/three.js,missingdays/three.js-amd,Delejnr/three.js,ZAAK-ZURICHBERLIN/ZAAK.IO-Editor,coloringchaos/three.js,snovak/three.js,sitexa/three.js,shanmugamss/three.js-modified,Black-Alpha/three.js,easz/three.js,coderrick/three.js,chuckfairy/three.js,ngokevin/three.js,mudithkr/three.js,mattholl/three.js,BenediktS/three.js,programulya/three.js,elephantatwork/ZAAK.IO-EditorInternal,StefanHuzz/three.js,gveltri/three.js,Coburn37/three.js,Ymaril/three.js,BrianSipple/three.js,sole/three.js,g-rocket/three.js,AntTech/three.js,snipermiller/three.js,ikerr/three.js,dhritzkiv/three.js,masterex1000/three.js,ngokevin/three-dev,stopyransky/three.js,sasha240100/three.js,mkkellogg/three.js,edge/three.js,Jericho25/three.js,datalink747/three.js,mindofmatthew/three.js,GGAlanSmithee/three.js,wanby/three.js,JuudeDemos/three.js,mataron/three.js,zeropaper/three.js,Samsy/three.js,njam/three.js,acrsteiner/three.js,luxigo/three.js,applexiaohao/three.js,q437634645/three.js,dyx/three.js,yrns/three.js,richtr/three.js,BenediktS/three.js,3DGEOM/three.js,sweetmandm/three.js,chuckfairy/three.js,mainelander/three.js,SpookW/three.js,missingdays/three.js-amd,yifanhunyc/three.js,benaadams/three.js,Wilt/three.js,3DGEOM/three.js,ondys/three.js,aleen42/three.js,kangax/three.js,TristanVALCKE/three.js,fkammer/three.js,jzitelli/three.js,mhoangvslev/data-visualizer,stevenliujw/three.js,MetaStackers/three.js,JingYongWang/three.js,gdebojyoti/three.js,Gheehnest/three.js,easz/three.js,leeric92/three.js,gigakiller/three.js,AVGP/three.js,Aldrien-/three.js,Jerdak/three.js,sole/three.js,pletzer/three.js,StefanHuzz/three.js,dyx/three.js,arose/three.js,cc272309126/three.js,anvaka/three.js,borismus/three.js,Pro/three.js,squarefeet/three.js,huobaowangxi/three.js,mainelander/three.js,jeromeetienne/three.js,opensim-org/three.js,stopyransky/three.js,unconed/three.js,ondys/three.js,dforrer/three.js,JamesHagerman/three.js,Joeldk/three.js,cadenasgmbh/three.js,billfeller/three.js,dimensia/three.js,Coburn37/three.js,Seagat2011/three.js,meizhoubao/three.js,holmberd/three.js,njam/three.js,rgaino/three.js,Itee/three.js,coloringchaos/three.js,Astrak/three.js,digital360/three.js,leitzler/three.js,alexbelyeu/three.js,mese79/three.js,colombod/three.js,tschw/three.js,jostschmithals/three.js,robmyers/three.js,crazyyaoyao/yaoyao,freekh/three.js,mattdesl/three.js,rgaino/three.js,0merta/three.js,archilogic-com/three.js,daoshengmu/three.js,snipermiller/three.js,WoodMath/three.js,snovak/three.js,satori99/three.js,ngokevin/three.js,arose/three.js,amakaroff82/three.js,haozi23333/three.js,lollerbus/three.js,BenediktS/three.js,Gheehnest/three.js,elephantatwork/three.js,gwindes/three.js,mindofmatthew/three.js,rgaino/three.js,alexbelyeu/three.js,rayantony/three.js,hsimpson/three.js,gdebojyoti/three.js,daoshengmu/three.js,gigakiller/three.js,quinonez/three.js,coderrick/three.js,dushmis/three.js,rfm1201/rfm.three.js,fkammer/three.js,Aldrien-/three.js,edge/three.js,LaughingSun/three.js,borismus/three.js,srifqi/three.js,luxigo/three.js,Seagat2011/three.js,mainelander/three.js,podgorskiy/three.js,zatchgordon/webGL,freekh/three.js,Ludobaka/three.js,fluxio/three.js,beni55/three.js,GastonBeaucage/three.js,nopjia/three.js,elephantatwork/three.js,satori99/three.js,imshibaji/three.js,mese79/three.js,AdactiveSAS/three.js,vizorvr/three.js,dforrer/three.js,swieder227/three.js,flimshaw/three.js,unphased/three.js,zodsoft/three.js,makc/three.js.fork,simonThiele/three.js,cadenasgmbh/three.js,Jozain/three.js,111t8e/three.js,imshibaji/three.js,colombod/three.js,brason/three.js,GastonBeaucage/three.js,brason/three.js,cc272309126/three.js,Jozain/three.js,masterex1000/three.js,matgr1/three.js,gdebojyoti/three.js,wizztjh/three.js,fomenyesu/three.js,QingchaoHu/three.js,yxxme/three.js,Black-Alpha/three.js,p5150j/three.js,fluxio/three.js,enche/three.js,framelab/three.js,matgr1/three.js,SET001/three.js,datalink747/three.js,brason/three.js,amakaroff82/three.js,easz/three.js,Dewb/three.js,mkkellogg/three.js,MetaStackers/three.js,rgaino/three.js,benjaminer82/threejs,AntTech/three.js,redheli/three.js,crazyyaoyao/yaoyao,edge/three.js,IceCreamYou/three.js,mese79/three.js,leitzler/three.js,TristanVALCKE/three.js,podgorskiy/three.js,ndebeiss/three.js,chuckfairy/three.js,xundaokeji/three.js,Pro/three.js,googlecreativelab/three.js,jayschwa/three.js,technohippy/three.js,eq0rip/three.js,rougier/three.js,Fox32/three.js,toguri/three.js,0merta/three.js,xundaokeji/three.js,alienity/three.js,AlexanderMazaletskiy/three.js,vizorvr/three.js,unphased/three.js,arodic/three.js,shanmugamss/three.js-modified,carlosanunes/three.js,googlecreativelab/three.js,arodic/three.js,toxicFork/three.js,freekh/three.js,carlosanunes/three.js,snipermiller/three.js,YajunQiu/three.js,bdysvik/three.js,lovewitty/three.js,aleen42/three.js,Amritesh/three.js,lovewitty/three.js,mudithkr/three.js,ValtoLibraries/ThreeJS,RAtechntukan/three.js,rlugojr/three.js,GastonBeaucage/three.js,Mohammed-Ashour/three.js,DelvarWorld/three.js,mese79/three.js,ikerr/three.js,gpranay4/three.js,erich666/three.js,masterex1000/three.js,111t8e/three.js,ducminhn/three.js,matthartman/oculus-matt,agnivade/three.js,mataron/three.js,benjaminer82/threejs,Aldrien-/three.js,zhanglingkang/three.js,LeoEatle/three.js,snipermiller/three.js,fanzhanggoogle/three.js,rougier/three.js,wuxinwei240/three.js,g-rocket/three.js,liusashmily/three.js,sweetmandm/three.js,billfeller/three.js,LaughingSun/three.js,mudithkr/three.js,shinate/three.js,JeckoHeroOrg/three.js,ThiagoGarciaAlves/three.js,mattholl/three.js,tamarintech/three.js,toxicFork/three.js,shinate/three.js,jango2015/three.js,elisee/three.js,rougier/three.js,GastonBeaucage/three.js,rbarraud/three.js,toguri/three.js,srifqi/three.js,fkammer/three.js,archilogic-com/three.js,jpweeks/three.js,LaughingSun/three.js,StefanHuzz/three.js,leeric92/three.js,bdysvik/three.js,ThiagoGarciaAlves/three.js,Hectate/three.js,stevenliujw/three.js,ZAAK-ZURICHBERLIN/ZAAK.IO-Editor,SET001/three.js,enche/three.js,fluxio/three.js,sherousee/three.js,toguri/three.js,ilovezy/three.js,freekh/three.js,JingYongWang/three.js,acrsteiner/three.js,IceCreamYou/three.js,podgorskiy/three.js,Aldrien-/three.js,DelvarWorld/three.js,wuxinwei240/three.js,tamarintech/three.js,jeffgoku/three.js,YajunQiu/three.js,timcastelijn/three.js,mindofmatthew/three.js,fta2012/three.js,0merta/three.js,SpookW/three.js,robmyers/three.js,imshibaji/three.js,plepers/three.js,dubejf/three.js,ngokevin/three.js,ilovezy/three.js,wuxinwei240/three.js,threejsworker/three.js,JamesHagerman/three.js,dforrer/three.js,datalink747/three.js,Peekmo/three.js,Wilt/three.js,SatoshiKawabata/three.js,pharos3d/three.js,dushmis/three.js,BrianSipple/three.js,chuckfairy/three.js,Gheehnest/three.js,Samsung-Blue/three.js,SatoshiKawabata/three.js,Benjamin-Dobell/three.js,0merta/three.js,aardgoose/three.js,jzitelli/three.js,Kakakakakku/three.js,SatoshiKawabata/three.js,swieder227/three.js,byhj/three.js,xundaokeji/three.js,mhoangvslev/data-visualizer,sufeiou/three.js,zodsoft/three.js,111t8e/three.js,StefanHuzz/three.js,snovak/three.js,srifqi/three.js,liusashmily/three.js,UnboundVR/three.js,mataron/three.js,richtr/three.js,DeanLym/three.js,gdebojyoti/three.js,dushmis/three.js,billfeller/three.js,NicolasRannou/three.js,WoodMath/three.js,arodic/three.js,luxigo/three.js,YajunQiu/three.js,UnboundVR/three.js,squarefeet/three.js,godlzr/Three.js,missingdays/three.js-amd,Samsy/three.js,Pro/three.js,redheli/three.js,MasterJames/three.js,BrianSipple/three.js,Black-Alpha/three.js,tdmsinc/three.js,MasterJames/three.js,Zerschmetterling91/three.js,alexbelyeu/three.js,Cakin-Kwong/three.js,mabo77/three.js,JuudeDemos/three.js,AscensionFoundation/three.js,daoshengmu/three.js,looeee/three.js,googlecreativelab/three.js,dushmis/three.js,dhritzkiv/three.js,supergometan/three.js,thomasxu1991/three.js,lovewitty/three.js,fta2012/three.js,godlzr/Three.js,yrns/three.js,lovewitty/three.js,dhritzkiv/three.js,mkkellogg/three.js,Samsy/three.js,lag945/three.js,lchl7890987/WebGL,Jozain/three.js,Fox32/three.js,SatoshiKawabata/three.js,sufeiou/three.js,dforrer/three.js,gwindes/three.js,masterex1000/three.js,mkkellogg/three.js,billfeller/three.js,freekh/three.js,thomasxu1991/three.js,squarefeet/three.js,wanby/three.js,gigakiller/three.js,lollerbus/three.js,Mohammed-Ashour/three.js,stevenliujw/three.js,stopyransky/three.js,rlugojr/three.js,ma-tech/three.js,JuudeDemos/three.js,sufeiou/three.js,lchl7890987/WebGL,stopyransky/three.js,Zerschmetterling91/three.js,gsssrao/three.js,blokhin/three.js,sheafferusa/three.js,unphased/three.js,dyx/three.js,technohippy/three.js,programulya/three.js,mese79/three.js,UnboundVR/three.js,gveltri/three.js,gsssrao/three.js,Hectate/three.js,Nitrillo/three.js,elephantatwork/ZAAK.IO-EditorInternal,LaughingSun/three.js,zeropaper/three.js,Itee/three.js,squarefeet/three.js,BrianSipple/three.js,benjaminer82/threejs,sufeiou/three.js,sebasbaumh/three.js,LeoEatle/three.js,JuudeDemos/three.js,mataron/three.js,wavesoft/three.js,billfeller/three.js,JuudeDemos/three.js,swieder227/three.js,digital360/three.js,Samsung-Blue/three.js,snovak/three.js,VimVincent/three.js,GGAlanSmithee/three.js,archcomet/three.js,crazyyaoyao/yaoyao,Liuer/three.js,brickify/three.js,vizorvr/three.js,archilogic-ch/three.js,Kasual666/WebGl,mudithkr/three.js,amazg/three.js,prika/three.js,Meshu/three.js,Leeft/three.js,zhanglingkang/three.js,AVGP/three.js,mattdesl/three.js,Jonham/three.js,SpookW/three.js,dayo7116/three.js,elephantatwork/three.js,bhouston/three.js,Stinkdigital/three.js,jzitelli/three.js,jeffgoku/three.js,Fox32/three.js,r8o8s1e0/three.js,controlzee/three.js,humbletim/three.js,gpranay4/three.js,sole/three.js,WoodMath/three.js,yrns/three.js,sherousee/three.js,ma-tech/three.js,g-rocket/three.js,g-rocket/three.js,pailhead/three.js,lag945/three.js,elephantatwork/ZAAK.IO-EditorInternal,Samsung-Blue/three.js,HongJunLi/three.js,sherousee/three.js,AdactiveSAS/three.js,arodic/three.js,controlzee/three.js,matthiascy/three.js,mhoangvslev/data-visualizer,zz85/three.js,ilovezy/three.js,GGAlanSmithee/three.js,leeric92/three.js,amakaroff82/three.js,beni55/three.js,leeric92/three.js,robmyers/three.js,beni55/three.js,Seagat2011/three.js,surround-io/three.js,sasha240100/three.js,tschw/three.js,wizztjh/three.js,eq0rip/three.js,edivancamargo/three.js,googlecreativelab/three.js,MarcusLongmuir/three.js,GastonBeaucage/three.js,jeffgoku/three.js,elisee/three.js,ducminhn/three.js,Wilt/three.js,fomenyesu/three.js,prabhu-k/three.js,tamarintech/three.js,robmyers/three.js,humbletim/three.js,ngokevin/three-dev,meizhoubao/three.js,Black-Alpha/three.js,Wilt/three.js,p5150j/three.js,ZAAK-ZURICHBERLIN/ZAAK.IO-Editor,WoodMath/three.js,gpranay4/three.js,donmccurdy/three.js,controlzee/three.js,satori99/three.js,ondys/three.js,tdmsinc/three.js,Mohammed-Ashour/three.js,lollerbus/three.js,agnivade/three.js,DeanLym/three.js,jllodra/three.js,jayhetee/three.js,prika/three.js,ZAAK-ZURICHBERLIN/ZAAK.IO-Editor,Jericho25/three.js,yxxme/three.js,jzitelli/three.js,zhanglingkang/three.js,gveltri/three.js,ngokevin/three.js,humbletim/three.js,jbaicoianu/three.js,bdysvik/three.js,agnivade/three.js,prika/three.js,mess110/three.js,BenediktS/three.js,erich666/three.js,supergometan/three.js,GammaGammaRay/three.js,VimVincent/three.js,zodsoft/three.js,Leeft/three.js,nraynaud/three.js,missingdays/three.js-amd,mainelander/three.js,Fox32/three.js,Nitrillo/three.js,matthiascy/three.js,gero3/three.js,makc/three.js.fork,edge/three.js,eq0rip/three.js,SET001/three.js,spite/three.js,takahirox/three.js,yifanhunyc/three.js,ngokevin/three.js,coloringchaos/three.js,BrianSipple/three.js,fanzhanggoogle/three.js,lollerbus/three.js,fluxio/three.js,mattdesl/three.js,yrns/three.js,zhanglingkang/three.js,pharos3d/three.js,zatchgordon/webGL,sebasbaumh/three.js,sunbc0120/three.js,alienity/three.js,Ymaril/three.js,ondys/three.js,edivancamargo/three.js,dubejf/three.js,sweetmandm/three.js,cc272309126/three.js,MarcusLongmuir/three.js,alexbelyeu/three.js,vizorvr/three.js,Benjamin-Dobell/three.js,r8o8s1e0/three.js,AscensionFoundation/three.js,eq0rip/three.js,agnivade/three.js,benaadams/three.js,mattdesl/three.js,ZhenxingWu/three.js,ondys/three.js,swieder227/three.js,quinonez/three.js,dayo7116/three.js,mattholl/three.js,MetaStackers/three.js,fkammer/three.js,YajunQiu/three.js,dhritzkiv/three.js,111t8e/three.js,MarcusLongmuir/three.js,fta2012/three.js,anvaka/three.js,zatchgordon/webGL,ndebeiss/three.js,Leeft/three.js,3DGEOM/three.js,threejsworker/three.js,plepers/three.js,alexconlin/three.js,matgr1/three.js,ThiagoGarciaAlves/three.js,SpookW/three.js,elephantatwork/ZAAK.IO-EditorInternal,ndebeiss/three.js,gveltri/three.js,haozi23333/three.js,coffeine-009/three.js,luxigo/three.js,hedgerh/three.js,dimensia/three.js,anvaka/three.js,plepers/three.js,takahirox/three.js,jeffgoku/three.js,mess110/three.js,ilovezy/three.js,imshibaji/three.js,GammaGammaRay/three.js,hsimpson/three.js,nhalloran/three.js,zhangwenyan/three.js,LeoEatle/three.js,redheli/three.js,toguri/three.js,erich666/three.js,hsimpson/three.js,Wilt/three.js,meizhoubao/three.js,njam/three.js,WestLangley/three.js,AntTech/three.js,tdmsinc/three.js,DeanLym/three.js,bhouston/three.js,elephantatwork/ZAAK.IO-EditorInternal,wuxinwei240/three.js,technohippy/three.js,fernandojsg/three.js,toxicFork/three.js,unconed/three.js,rbarraud/three.js,meizhoubao/three.js,elephantatwork/three.js,fraguada/three.js,haozi23333/three.js,acrsteiner/three.js,rlugojr/three.js,sole/three.js,surround-io/three.js,yifanhunyc/three.js,snipermiller/three.js,pletzer/three.js,RAtechntukan/three.js,daoshengmu/three.js,coderrick/three.js,RAtechntukan/three.js,Jericho25/three.js,kaisalmen/three.js,AltspaceVR/three.js,jbaicoianu/three.js,ilovezy/three.js,RemusMar/three.js,ma-tech/three.js,WoodMath/three.js,gdebojyoti/three.js,zbm2001/three.js,NicolasRannou/three.js,alexconlin/three.js,shanmugamss/three.js-modified,davidvmckay/three.js,julapy/three.js,tschw/three.js,prika/three.js,flimshaw/three.js,acrsteiner/three.js,nadirhamid/three.js,Jozain/three.js,tamarintech/three.js,flimshaw/three.js,pletzer/three.js,NicolasRannou/three.js,quinonez/three.js,Stinkdigital/three.js,JingYongWang/three.js,amazg/three.js,Nitrillo/three.js,sreith1/three.js,SatoshiKawabata/three.js,dimensia/three.js,JingYongWang/three.js,ValtoLibraries/ThreeJS,toxicFork/three.js,jbaicoianu/three.js,jango2015/three.js,stevenliujw/three.js,richtr/three.js,BlackTowerEntertainment/three.js,ngokevin/three-dev,wanby/three.js,Dewb/three.js,p5150j/three.js,masterex1000/three.js,takahirox/three.js,timcastelijn/three.js,technohippy/three.js,byhj/three.js,spite/three.js,meizhoubao/three.js,zeropaper/three.js,shinate/three.js,Zerschmetterling91/three.js,Cakin-Kwong/three.js,nhalloran/three.js,NicolasRannou/three.js,jostschmithals/three.js,MarcusLongmuir/three.js,Ymaril/three.js,pharos3d/three.js,mindofmatthew/three.js,zhangwenyan/three.js,matthartman/oculus-matt,holmberd/three.js,coderrick/three.js,AVGP/three.js,zeropaper/three.js,q437634645/three.js,sheafferusa/three.js,Meshu/three.js,prika/three.js,gdebojyoti/three.js,Leeft/three.js,BlackTowerEntertainment/three.js,r8o8s1e0/three.js,tamarintech/three.js,gveltri/three.js,colombod/three.js,jllodra/three.js,UnboundVR/three.js,zbm2001/three.js,cc272309126/three.js,MasterJames/three.js,jayhetee/three.js,anvaka/three.js,rbarraud/three.js,MetaStackers/three.js,chaoallsome/three.js,sweetmandm/three.js,dyx/three.js,gwindes/three.js,shinate/three.js,Fox32/three.js,Hectate/three.js,edge/three.js,sole/three.js,MarcusLongmuir/three.js,wanby/three.js,wuxinwei240/three.js,programulya/three.js,Dewb/three.js,06wj/three.js,anvaka/three.js,zhoushijie163/three.js,jostschmithals/three.js,wavesoft/three.js,gigakiller/three.js,MasterJames/three.js,alienity/three.js,fanzhanggoogle/three.js,yuhualingfeng/three.js,jeromeetienne/three.js,easz/three.js,archcomet/three.js,toxicFork/three.js,matthiascy/three.js,hacksalot/three.js,Samsung-Blue/three.js,Mohammed-Ashour/three.js,controlzee/three.js,jeromeetienne/three.js,vizorvr/three.js,opensim-org/three.js,JamesHagerman/three.js,carlosanunes/three.js,digital360/three.js,sunbc0120/three.js,mataron/three.js,mess110/three.js,nopjia/three.js,unconed/three.js,elephantatwork/three.js,zhangwenyan/three.js,chuckfairy/three.js,coloringchaos/three.js,hacksalot/three.js,DelvarWorld/three.js,applexiaohao/three.js,arose/three.js,Samsy/three.js,wizztjh/three.js,rbarraud/three.js,rfm1201/rfm.three.js,mattholl/three.js,mess110/three.js,ngokevin/three-dev,brickify/three.js,jllodra/three.js,kkjeer/three.js,applexiaohao/three.js,Benjamin-Dobell/three.js,amazg/three.js,wavesoft/three.js,arodic/three.js,framelab/three.js,BlackTowerEntertainment/three.js,pletzer/three.js,hacksalot/three.js,matthartman/oculus-matt,Ludobaka/three.js,brickify/three.js,rayantony/three.js,BlackTowerEntertainment/three.js,leitzler/three.js,Zerschmetterling91/three.js,mabo77/three.js,sasha240100/three.js,kaisalmen/three.js,easz/three.js,enche/three.js,quinonez/three.js,q437634645/three.js,googlecreativelab/three.js,xundaokeji/three.js,sasha240100/three.js,Benjamin-Dobell/three.js,digital360/three.js,colombod/three.js,jeromeetienne/three.js,Kasual666/WebGl,masterex1000/three.js,hacksalot/three.js,Kakakakakku/three.js,dforrer/three.js,simonThiele/three.js,sebasbaumh/three.js,sasha240100/three.js,missingdays/three.js-amd,archilogic-ch/three.js,RAtechntukan/three.js,benaadams/three.js,hedgerh/three.js,fernandojsg/three.js,SET001/three.js,lag945/three.js,amakaroff82/three.js,unconed/three.js,prabhu-k/three.js,AntTech/three.js,shanmugamss/three.js-modified,stanford-gfx/three.js,lchl7890987/WebGL,dushmis/three.js,zatchgordon/webGL,jllodra/three.js,zbm2001/three.js,zbm2001/three.js,sheafferusa/three.js,r8o8s1e0/three.js,NicolasRannou/three.js,q437634645/three.js,camellhf/three.js,camellhf/three.js,luxigo/three.js,stevenliujw/three.js,camellhf/three.js,archcomet/three.js,blokhin/three.js,archilogic-com/three.js,YajunQiu/three.js,TristanVALCKE/three.js,amazg/three.js,sheafferusa/three.js,Astrak/three.js,huobaowangxi/three.js,daoshengmu/three.js,aardgoose/three.js,archilogic-ch/three.js,bdysvik/three.js,leitzler/three.js,mess110/three.js,IceCreamYou/three.js,sttz/three.js,Gheehnest/three.js,IceCreamYou/three.js,Liuer/three.js,jeromeetienne/three.js,jayhetee/three.js,unphased/three.js,Ymaril/three.js,MarcusLongmuir/three.js,mrkev/three.js,bhouston/three.js,nopjia/three.js,mattholl/three.js,sitexa/three.js,controlzee/three.js,takahirox/three.js,xundaokeji/three.js,mabo77/three.js,humbletim/three.js,Wilt/three.js,jee7/three.js,VimVincent/three.js,MetaStackers/three.js,liammagee/three.js,jango2015/three.js,sunbc0120/three.js,jango2015/three.js,Coburn37/three.js,rgaino/three.js,shanmugamss/three.js-modified,elephantatwork/three.js,Cakin-Kwong/three.js,fraguada/three.js,easz/three.js,LaughingSun/three.js,julapy/three.js,kangax/three.js,Seagat2011/three.js,BenediktS/three.js,spite/three.js,Nitrillo/three.js,jostschmithals/three.js,coderrick/three.js,huobaowangxi/three.js,brason/three.js,eq0rip/three.js,zodsoft/three.js,nhalloran/three.js,Leeft/three.js,jeffgoku/three.js,Kakakakakku/three.js,holmberd/three.js,podgorskiy/three.js,rgaino/three.js,enche/three.js,crazyyaoyao/yaoyao,amazg/three.js,beni55/three.js,mkkellogg/three.js,StefanHuzz/three.js,stopyransky/three.js,matthartman/oculus-matt,timcastelijn/three.js,surround-io/three.js,edivancamargo/three.js,benjaminer82/threejs,fta2012/three.js,ndebeiss/three.js,mrkev/three.js,Peekmo/three.js,unphased/three.js,JeckoHeroOrg/three.js,GGAlanSmithee/three.js,byhj/three.js,Mohammed-Ashour/three.js,LeoEatle/three.js,jzitelli/three.js,Meshu/three.js,aleen42/three.js,archilogic-com/three.js,njam/three.js,dyx/three.js,AlexanderMazaletskiy/three.js,coderrick/three.js,coffeine-009/three.js,jayschwa/three.js,Stinkdigital/three.js,snovak/three.js,arodic/three.js,unphased/three.js,Ymaril/three.js,dayo7116/three.js,simonThiele/three.js,redheli/three.js,archilogic-com/three.js,VimVincent/three.js,huobaowangxi/three.js,gsssrao/three.js,ikerr/three.js,RemusMar/three.js,Delejnr/three.js,brianchirls/three.js,fomenyesu/three.js,nopjia/three.js,enche/three.js,Jonham/three.js,benaadams/three.js,StefanHuzz/three.js,coloringchaos/three.js,Jonham/three.js,QingchaoHu/three.js,Delejnr/three.js,benjaminer82/threejs,daoshengmu/three.js,unconed/three.js,GammaGammaRay/three.js,borismus/three.js,wizztjh/three.js,BlackTowerEntertainment/three.js,fernandojsg/three.js,acrsteiner/three.js,Delejnr/three.js,erich666/three.js,datalink747/three.js,Kakakakakku/three.js,supergometan/three.js,RemusMar/three.js,elisee/three.js,matgr1/three.js,ikerr/three.js,rbarraud/three.js,lovewitty/three.js,archcomet/three.js,SET001/three.js,brianchirls/three.js,imshibaji/three.js,GGAlanSmithee/three.js,gero3/three.js,mindofmatthew/three.js,Jerdak/three.js,JeckoHeroOrg/three.js,gpranay4/three.js,satori99/three.js,borismus/three.js,applexiaohao/three.js,jbaicoianu/three.js,amazg/three.js,sunbc0120/three.js,wavesoft/three.js,AltspaceVR/three.js,squarefeet/three.js,ma-tech/three.js,AVGP/three.js,sunbc0120/three.js,jzitelli/three.js,robsix/3ditor,podgorskiy/three.js,chuckfairy/three.js,brianchirls/three.js,zhoushijie163/three.js,prika/three.js,yrns/three.js,DeanLym/three.js,ngokevin/three-dev,fkammer/three.js,davidvmckay/three.js,benaadams/three.js,Samsung-Blue/three.js,GastonBeaucage/three.js,satori99/three.js,timcastelijn/three.js,colombod/three.js,hedgerh/three.js,mess110/three.js,takahirox/three.js,elisee/three.js,Zerschmetterling91/three.js,gwindes/three.js,davidvmckay/three.js,alexbelyeu/three.js,Jozain/three.js,chaoallsome/three.js,Nitrillo/three.js,alienity/three.js,Pro/three.js,mattdesl/three.js,blokhin/three.js,plepers/three.js,ZhenxingWu/three.js,programulya/three.js,zhanglingkang/three.js,njam/three.js,nraynaud/three.js,Joeldk/three.js,sitexa/three.js,AltspaceVR/three.js,Cakin-Kwong/three.js,mattholl/three.js,rayantony/three.js,brickify/three.js,leitzler/three.js,mattdesl/three.js,JeckoHeroOrg/three.js,ducminhn/three.js,JamesHagerman/three.js,zatchgordon/webGL,dglogik/three.js,beni55/three.js,DeanLym/three.js,mhoangvslev/data-visualizer,yxxme/three.js,Hectate/three.js,jayhetee/three.js,holmberd/three.js,Jonham/three.js,BrianSipple/three.js,nadirhamid/three.js,AlexanderMazaletskiy/three.js,robmyers/three.js,AscensionFoundation/three.js,lollerbus/three.js,fyoudine/three.js,nhalloran/three.js,brickify/three.js,zz85/three.js,matthiascy/three.js,Meshu/three.js,thomasxu1991/three.js,jayschwa/three.js,threejsworker/three.js,leitzler/three.js,sreith1/three.js,srifqi/three.js,Ludobaka/three.js,wizztjh/three.js,rayantony/three.js,camellhf/three.js,gigakiller/three.js,kkjeer/three.js,nopjia/three.js,nadirhamid/three.js,nhalloran/three.js,SpookW/three.js,timcastelijn/three.js,datalink747/three.js,dayo7116/three.js,mabo77/three.js,JuudeDemos/three.js,davidvmckay/three.js,thomasxu1991/three.js,squarefeet/three.js,DelvarWorld/three.js,Jonham/three.js,alexbelyeu/three.js,JingYongWang/three.js,coloringchaos/three.js,coffeine-009/three.js,jayhetee/three.js,zhangwenyan/three.js,Seagat2011/three.js,p5150j/three.js,AdactiveSAS/three.js,AlexanderMazaletskiy/three.js,swieder227/three.js,simonThiele/three.js,Mugen87/three.js,mindofmatthew/three.js,meizhoubao/three.js,3DGEOM/three.js,liammagee/three.js,sttz/three.js,flimshaw/three.js,GammaGammaRay/three.js,wanby/three.js,bhouston/three.js,Coburn37/three.js,davidvmckay/three.js,haozi23333/three.js,Kakakakakku/three.js,Astrak/three.js,beni55/three.js,AscensionFoundation/three.js,jostschmithals/three.js,lchl7890987/WebGL,tdmsinc/three.js,sasha240100/three.js,wizztjh/three.js,zbm2001/three.js,sheafferusa/three.js,richtr/three.js,sufeiou/three.js,fomenyesu/three.js,Peekmo/three.js,hedgerh/three.js,satori99/three.js,alienity/three.js,jllodra/three.js,chaoallsome/three.js,carlosanunes/three.js,zatchgordon/webGL,mrkev/three.js,AVGP/three.js,AscensionFoundation/three.js,liusashmily/three.js,fraguada/three.js,Samsy/three.js,zz85/three.js,AltspaceVR/three.js,Dewb/three.js,tschw/three.js,robsix/3ditor,crazyyaoyao/yaoyao,Benjamin-Dobell/three.js,njam/three.js,brianchirls/three.js,yrns/three.js,spite/three.js,zhanglingkang/three.js,dimensia/three.js,ValtoLibraries/ThreeJS,dushmis/three.js,Black-Alpha/three.js,blokhin/three.js,zz85/three.js,jee7/three.js,anvaka/three.js,DelvarWorld/three.js,greggman/three.js,liusashmily/three.js,programulya/three.js,takahirox/three.js,kangax/three.js,dubejf/three.js,ValtoLibraries/ThreeJS,AscensionFoundation/three.js,benaadams/three.js,AltspaceVR/three.js,zz85/three.js,Fox32/three.js,Hectate/three.js,timcastelijn/three.js,Pro/three.js,SET001/three.js,IceCreamYou/three.js,GammaGammaRay/three.js,nraynaud/three.js,ZhenxingWu/three.js,rayantony/three.js,sunbc0120/three.js,nadirhamid/three.js,wuxinwei240/three.js,JeckoHeroOrg/three.js,sweetmandm/three.js,rlugojr/three.js,GGAlanSmithee/three.js,greggman/three.js,pharos3d/three.js,chaoallsome/three.js,wavesoft/three.js,archilogic-ch/three.js,p5150j/three.js,camellhf/three.js,edivancamargo/three.js,Leeft/three.js,supergometan/three.js,Gheehnest/three.js,pletzer/three.js,rougier/three.js,UnboundVR/three.js,elephantatwork/ZAAK.IO-EditorInternal,arose/three.js,surround-io/three.js,rlugojr/three.js,sebasbaumh/three.js,edivancamargo/three.js,hacksalot/three.js,humbletim/three.js,yuhualingfeng/three.js,applexiaohao/three.js,dhritzkiv/three.js,toguri/three.js,cc272309126/three.js,mkkellogg/three.js,toxicFork/three.js,flimshaw/three.js,111t8e/three.js,borismus/three.js,Jerdak/three.js,srifqi/three.js,matthartman/oculus-matt,Coburn37/three.js,Seagat2011/three.js,kkjeer/three.js,fanzhanggoogle/three.js,billfeller/three.js,coffeine-009/three.js,alexconlin/three.js,matgr1/three.js,LaughingSun/three.js,alienity/three.js,tschw/three.js,yxxme/three.js,fkammer/three.js,RAtechntukan/three.js,threejsworker/three.js,pharos3d/three.js,gsssrao/three.js,ZAAK-ZURICHBERLIN/ZAAK.IO-Editor,zbm2001/three.js,ndebeiss/three.js,Coburn37/three.js,mudithkr/three.js,podgorskiy/three.js,Amritesh/three.js,AdactiveSAS/three.js,nopjia/three.js,TristanVALCKE/three.js,dimensia/three.js,rbarraud/three.js,huobaowangxi/three.js,digital360/three.js,datalink747/three.js,ilovezy/three.js,LeoEatle/three.js,gsssrao/three.js,AltspaceVR/three.js,haozi23333/three.js,Samsy/three.js
/** * @author supereggbert / http://www.paulbrunt.co.uk/ * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author szimek / https://github.com/szimek/ */ THREE.WebGLRenderer = function ( parameters ) { console.log( 'THREE.WebGLRenderer', THREE.REVISION ); parameters = parameters || {}; var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ), _context = parameters.context !== undefined ? parameters.context : null, _precision = parameters.precision !== undefined ? parameters.precision : 'highp', _buffers = {}, _alpha = parameters.alpha !== undefined ? parameters.alpha : false, _depth = parameters.depth !== undefined ? parameters.depth : true, _stencil = parameters.stencil !== undefined ? parameters.stencil : true, _antialias = parameters.antialias !== undefined ? parameters.antialias : false, _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, _clearColor = new THREE.Color( 0x000000 ), _clearAlpha = 0; // public properties this.domElement = _canvas; this.context = null; this.devicePixelRatio = parameters.devicePixelRatio !== undefined ? parameters.devicePixelRatio : self.devicePixelRatio !== undefined ? self.devicePixelRatio : 1; // clearing this.autoClear = true; this.autoClearColor = true; this.autoClearDepth = true; this.autoClearStencil = true; // scene graph this.sortObjects = true; this.autoUpdateObjects = true; // physically based shading this.gammaInput = false; this.gammaOutput = false; // shadow map this.shadowMapEnabled = false; this.shadowMapAutoUpdate = true; this.shadowMapType = THREE.PCFShadowMap; this.shadowMapCullFace = THREE.CullFaceFront; this.shadowMapDebug = false; this.shadowMapCascade = false; // morphs this.maxMorphTargets = 8; this.maxMorphNormals = 4; // flags this.autoScaleCubemaps = true; // custom render plugins this.renderPluginsPre = []; this.renderPluginsPost = []; // info this.info = { memory: { programs: 0, geometries: 0, textures: 0 }, render: { calls: 0, vertices: 0, faces: 0, points: 0 } }; // internal properties var _this = this, _programs = [], _programs_counter = 0, // internal state cache _currentProgram = null, _currentFramebuffer = null, _currentMaterialId = -1, _currentGeometryGroupHash = null, _currentCamera = null, _usedTextureUnits = 0, // GL state cache _oldDoubleSided = -1, _oldFlipSided = -1, _oldBlending = -1, _oldBlendEquation = -1, _oldBlendSrc = -1, _oldBlendDst = -1, _oldDepthTest = -1, _oldDepthWrite = -1, _oldPolygonOffset = null, _oldPolygonOffsetFactor = null, _oldPolygonOffsetUnits = null, _oldLineWidth = null, _viewportX = 0, _viewportY = 0, _viewportWidth = _canvas.width, _viewportHeight = _canvas.height, _currentWidth = 0, _currentHeight = 0, _enabledAttributes = new Uint8Array( 16 ), // frustum _frustum = new THREE.Frustum(), // camera matrices cache _projScreenMatrix = new THREE.Matrix4(), _projScreenMatrixPS = new THREE.Matrix4(), _vector3 = new THREE.Vector3(), // light arrays cache _direction = new THREE.Vector3(), _lightsNeedUpdate = true, _lights = { ambient: [ 0, 0, 0 ], directional: { length: 0, colors: new Array(), positions: new Array() }, point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() }, spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() }, hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() } }; // initialize var _gl; var _glExtensionTextureFloat; var _glExtensionTextureFloatLinear; var _glExtensionStandardDerivatives; var _glExtensionTextureFilterAnisotropic; var _glExtensionCompressedTextureS3TC; var _glExtensionElementIndexUint; initGL(); setDefaultGLState(); this.context = _gl; // GPU capabilities var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ); var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ); var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE ); var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0; var _supportsVertexTextures = ( _maxVertexTextures > 0 ); var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat; var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : []; // var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT ); var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT ); var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT ); var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT ); var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT ); var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT ); var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT ); var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT ); var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT ); var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT ); var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT ); var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT ); // clamp precision to maximum available var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0; var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0; if ( _precision === "highp" && ! highpAvailable ) { if ( mediumpAvailable ) { _precision = "mediump"; console.warn( "WebGLRenderer: highp not supported, using mediump" ); } else { _precision = "lowp"; console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" ); } } if ( _precision === "mediump" && ! mediumpAvailable ) { _precision = "lowp"; console.warn( "WebGLRenderer: mediump not supported, using lowp" ); } // API this.getContext = function () { return _gl; }; this.supportsVertexTextures = function () { return _supportsVertexTextures; }; this.supportsFloatTextures = function () { return _glExtensionTextureFloat; }; this.supportsStandardDerivatives = function () { return _glExtensionStandardDerivatives; }; this.supportsCompressedTextureS3TC = function () { return _glExtensionCompressedTextureS3TC; }; this.getMaxAnisotropy = function () { return _maxAnisotropy; }; this.getPrecision = function () { return _precision; }; this.setSize = function ( width, height, updateStyle ) { _canvas.width = width * this.devicePixelRatio; _canvas.height = height * this.devicePixelRatio; if ( this.devicePixelRatio !== 1 && updateStyle !== false ) { _canvas.style.width = width + 'px'; _canvas.style.height = height + 'px'; } this.setViewport( 0, 0, width, height ); }; this.setViewport = function ( x, y, width, height ) { _viewportX = x * this.devicePixelRatio; _viewportY = y * this.devicePixelRatio; _viewportWidth = width * this.devicePixelRatio; _viewportHeight = height * this.devicePixelRatio; _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); }; this.setScissor = function ( x, y, width, height ) { _gl.scissor( x * this.devicePixelRatio, y * this.devicePixelRatio, width * this.devicePixelRatio, height * this.devicePixelRatio ); }; this.enableScissorTest = function ( enable ) { enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST ); }; // Clearing this.setClearColor = function ( color, alpha ) { _clearColor.set( color ); _clearAlpha = alpha !== undefined ? alpha : 1; _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); }; this.setClearColorHex = function ( hex, alpha ) { console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' ); this.setClearColor( hex, alpha ); }; this.getClearColor = function () { return _clearColor; }; this.getClearAlpha = function () { return _clearAlpha; }; this.clear = function ( color, depth, stencil ) { var bits = 0; if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; _gl.clear( bits ); }; this.clearColor = function () { _gl.clear( _gl.COLOR_BUFFER_BIT ); }; this.clearDepth = function () { _gl.clear( _gl.DEPTH_BUFFER_BIT ); }; this.clearStencil = function () { _gl.clear( _gl.STENCIL_BUFFER_BIT ); }; this.clearTarget = function ( renderTarget, color, depth, stencil ) { this.setRenderTarget( renderTarget ); this.clear( color, depth, stencil ); }; // Plugins this.addPostPlugin = function ( plugin ) { plugin.init( this ); this.renderPluginsPost.push( plugin ); }; this.addPrePlugin = function ( plugin ) { plugin.init( this ); this.renderPluginsPre.push( plugin ); }; // Rendering this.updateShadowMap = function ( scene, camera ) { _currentProgram = null; _oldBlending = -1; _oldDepthTest = -1; _oldDepthWrite = -1; _currentGeometryGroupHash = -1; _currentMaterialId = -1; _lightsNeedUpdate = true; _oldDoubleSided = -1; _oldFlipSided = -1; this.shadowMapPlugin.update( scene, camera ); }; // Internal functions // Buffer allocation function createParticleBuffers ( geometry ) { geometry.__webglVertexBuffer = _gl.createBuffer(); geometry.__webglColorBuffer = _gl.createBuffer(); _this.info.memory.geometries ++; }; function createLineBuffers ( geometry ) { geometry.__webglVertexBuffer = _gl.createBuffer(); geometry.__webglColorBuffer = _gl.createBuffer(); geometry.__webglLineDistanceBuffer = _gl.createBuffer(); _this.info.memory.geometries ++; }; function createMeshBuffers ( geometryGroup ) { geometryGroup.__webglVertexBuffer = _gl.createBuffer(); geometryGroup.__webglNormalBuffer = _gl.createBuffer(); geometryGroup.__webglTangentBuffer = _gl.createBuffer(); geometryGroup.__webglColorBuffer = _gl.createBuffer(); geometryGroup.__webglUVBuffer = _gl.createBuffer(); geometryGroup.__webglUV2Buffer = _gl.createBuffer(); geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer(); geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer(); geometryGroup.__webglFaceBuffer = _gl.createBuffer(); geometryGroup.__webglLineBuffer = _gl.createBuffer(); var m, ml; if ( geometryGroup.numMorphTargets ) { geometryGroup.__webglMorphTargetsBuffers = []; for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() ); } } if ( geometryGroup.numMorphNormals ) { geometryGroup.__webglMorphNormalsBuffers = []; for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() ); } } _this.info.memory.geometries ++; }; // Events var onGeometryDispose = function ( event ) { var geometry = event.target; geometry.removeEventListener( 'dispose', onGeometryDispose ); deallocateGeometry( geometry ); }; var onTextureDispose = function ( event ) { var texture = event.target; texture.removeEventListener( 'dispose', onTextureDispose ); deallocateTexture( texture ); _this.info.memory.textures --; }; var onRenderTargetDispose = function ( event ) { var renderTarget = event.target; renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); deallocateRenderTarget( renderTarget ); _this.info.memory.textures --; }; var onMaterialDispose = function ( event ) { var material = event.target; material.removeEventListener( 'dispose', onMaterialDispose ); deallocateMaterial( material ); }; // Buffer deallocation var deleteBuffers = function ( geometry ) { if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer ); if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer ); if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer ); if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer ); if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer ); if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer ); if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer ); if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer ); if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer ); if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer ); if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer ); // custom attributes if ( geometry.__webglCustomAttributesList !== undefined ) { for ( var id in geometry.__webglCustomAttributesList ) { _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer ); } } _this.info.memory.geometries --; }; var deallocateGeometry = function ( geometry ) { geometry.__webglInit = undefined; if ( geometry instanceof THREE.BufferGeometry ) { var attributes = geometry.attributes; for ( var key in attributes ) { if ( attributes[ key ].buffer !== undefined ) { _gl.deleteBuffer( attributes[ key ].buffer ); } } _this.info.memory.geometries --; } else { if ( geometry.geometryGroups !== undefined ) { for ( var g in geometry.geometryGroups ) { var geometryGroup = geometry.geometryGroups[ g ]; if ( geometryGroup.numMorphTargets !== undefined ) { for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] ); } } if ( geometryGroup.numMorphNormals !== undefined ) { for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] ); } } deleteBuffers( geometryGroup ); } } else { deleteBuffers( geometry ); } } }; var deallocateTexture = function ( texture ) { if ( texture.image && texture.image.__webglTextureCube ) { // cube texture _gl.deleteTexture( texture.image.__webglTextureCube ); } else { // 2D texture if ( ! texture.__webglInit ) return; texture.__webglInit = false; _gl.deleteTexture( texture.__webglTexture ); } }; var deallocateRenderTarget = function ( renderTarget ) { if ( !renderTarget || ! renderTarget.__webglTexture ) return; _gl.deleteTexture( renderTarget.__webglTexture ); if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { for ( var i = 0; i < 6; i ++ ) { _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] ); _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] ); } } else { _gl.deleteFramebuffer( renderTarget.__webglFramebuffer ); _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer ); } }; var deallocateMaterial = function ( material ) { var program = material.program; if ( program === undefined ) return; material.program = undefined; // only deallocate GL program if this was the last use of shared program // assumed there is only single copy of any program in the _programs list // (that's how it's constructed) var i, il, programInfo; var deleteProgram = false; for ( i = 0, il = _programs.length; i < il; i ++ ) { programInfo = _programs[ i ]; if ( programInfo.program === program ) { programInfo.usedTimes --; if ( programInfo.usedTimes === 0 ) { deleteProgram = true; } break; } } if ( deleteProgram === true ) { // avoid using array.splice, this is costlier than creating new array from scratch var newPrograms = []; for ( i = 0, il = _programs.length; i < il; i ++ ) { programInfo = _programs[ i ]; if ( programInfo.program !== program ) { newPrograms.push( programInfo ); } } _programs = newPrograms; _gl.deleteProgram( program ); _this.info.memory.programs --; } }; // Buffer initialization function initCustomAttributes ( geometry, object ) { var nvertices = geometry.vertices.length; var material = object.material; if ( material.attributes ) { if ( geometry.__webglCustomAttributesList === undefined ) { geometry.__webglCustomAttributesList = []; } for ( var a in material.attributes ) { var attribute = material.attributes[ a ]; if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { attribute.__webglInitialized = true; var size = 1; // "f" and "i" if ( attribute.type === "v2" ) size = 2; else if ( attribute.type === "v3" ) size = 3; else if ( attribute.type === "v4" ) size = 4; else if ( attribute.type === "c" ) size = 3; attribute.size = size; attribute.array = new Float32Array( nvertices * size ); attribute.buffer = _gl.createBuffer(); attribute.buffer.belongsToAttribute = a; attribute.needsUpdate = true; } geometry.__webglCustomAttributesList.push( attribute ); } } }; function initParticleBuffers ( geometry, object ) { var nvertices = geometry.vertices.length; geometry.__vertexArray = new Float32Array( nvertices * 3 ); geometry.__colorArray = new Float32Array( nvertices * 3 ); geometry.__sortArray = []; geometry.__webglParticleCount = nvertices; initCustomAttributes ( geometry, object ); }; function initLineBuffers ( geometry, object ) { var nvertices = geometry.vertices.length; geometry.__vertexArray = new Float32Array( nvertices * 3 ); geometry.__colorArray = new Float32Array( nvertices * 3 ); geometry.__lineDistanceArray = new Float32Array( nvertices * 1 ); geometry.__webglLineCount = nvertices; initCustomAttributes ( geometry, object ); }; function initMeshBuffers ( geometryGroup, object ) { var geometry = object.geometry, faces3 = geometryGroup.faces3, nvertices = faces3.length * 3, ntris = faces3.length * 1, nlines = faces3.length * 3, material = getBufferMaterial( object, geometryGroup ), uvType = bufferGuessUVType( material ), normalType = bufferGuessNormalType( material ), vertexColorType = bufferGuessVertexColorType( material ); // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material ); geometryGroup.__vertexArray = new Float32Array( nvertices * 3 ); if ( normalType ) { geometryGroup.__normalArray = new Float32Array( nvertices * 3 ); } if ( geometry.hasTangents ) { geometryGroup.__tangentArray = new Float32Array( nvertices * 4 ); } if ( vertexColorType ) { geometryGroup.__colorArray = new Float32Array( nvertices * 3 ); } if ( uvType ) { if ( geometry.faceVertexUvs.length > 0 ) { geometryGroup.__uvArray = new Float32Array( nvertices * 2 ); } if ( geometry.faceVertexUvs.length > 1 ) { geometryGroup.__uv2Array = new Float32Array( nvertices * 2 ); } } if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) { geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 ); geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 ); } var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3 geometryGroup.__typeArray = UintArray; geometryGroup.__faceArray = new UintArray( ntris * 3 ); geometryGroup.__lineArray = new UintArray( nlines * 2 ); var m, ml; if ( geometryGroup.numMorphTargets ) { geometryGroup.__morphTargetsArrays = []; for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) ); } } if ( geometryGroup.numMorphNormals ) { geometryGroup.__morphNormalsArrays = []; for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) ); } } geometryGroup.__webglFaceCount = ntris * 3; geometryGroup.__webglLineCount = nlines * 2; // custom attributes if ( material.attributes ) { if ( geometryGroup.__webglCustomAttributesList === undefined ) { geometryGroup.__webglCustomAttributesList = []; } for ( var a in material.attributes ) { // Do a shallow copy of the attribute object so different geometryGroup chunks use different // attribute buffers which are correctly indexed in the setMeshBuffers function var originalAttribute = material.attributes[ a ]; var attribute = {}; for ( var property in originalAttribute ) { attribute[ property ] = originalAttribute[ property ]; } if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { attribute.__webglInitialized = true; var size = 1; // "f" and "i" if( attribute.type === "v2" ) size = 2; else if( attribute.type === "v3" ) size = 3; else if( attribute.type === "v4" ) size = 4; else if( attribute.type === "c" ) size = 3; attribute.size = size; attribute.array = new Float32Array( nvertices * size ); attribute.buffer = _gl.createBuffer(); attribute.buffer.belongsToAttribute = a; originalAttribute.needsUpdate = true; attribute.__original = originalAttribute; } geometryGroup.__webglCustomAttributesList.push( attribute ); } } geometryGroup.__inittedArrays = true; }; function getBufferMaterial( object, geometryGroup ) { return object.material instanceof THREE.MeshFaceMaterial ? object.material.materials[ geometryGroup.materialIndex ] : object.material; }; function materialNeedsSmoothNormals ( material ) { return material && material.shading !== undefined && material.shading === THREE.SmoothShading; }; function bufferGuessNormalType ( material ) { // only MeshBasicMaterial and MeshDepthMaterial don't need normals if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) { return false; } if ( materialNeedsSmoothNormals( material ) ) { return THREE.SmoothShading; } else { return THREE.FlatShading; } }; function bufferGuessVertexColorType( material ) { if ( material.vertexColors ) { return material.vertexColors; } return false; }; function bufferGuessUVType( material ) { // material must use some texture to require uvs if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) { return true; } return false; }; // function initDirectBuffers( geometry ) { for ( var name in geometry.attributes ) { var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER; var attribute = geometry.attributes[ name ]; attribute.buffer = _gl.createBuffer(); _gl.bindBuffer( bufferType, attribute.buffer ); _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW ); } } // Buffer setting function setParticleBuffers ( geometry, hint, object ) { var v, c, vertex, offset, index, color, vertices = geometry.vertices, vl = vertices.length, colors = geometry.colors, cl = colors.length, vertexArray = geometry.__vertexArray, colorArray = geometry.__colorArray, sortArray = geometry.__sortArray, dirtyVertices = geometry.verticesNeedUpdate, dirtyElements = geometry.elementsNeedUpdate, dirtyColors = geometry.colorsNeedUpdate, customAttributes = geometry.__webglCustomAttributesList, i, il, a, ca, cal, value, customAttribute; if ( object.sortParticles ) { _projScreenMatrixPS.copy( _projScreenMatrix ); _projScreenMatrixPS.multiply( object.matrixWorld ); for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; _vector3.copy( vertex ); _vector3.applyProjection( _projScreenMatrixPS ); sortArray[ v ] = [ _vector3.z, v ]; } sortArray.sort( numericalSort ); for ( v = 0; v < vl; v ++ ) { vertex = vertices[ sortArray[v][1] ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } for ( c = 0; c < cl; c ++ ) { offset = c * 3; color = colors[ sortArray[c][1] ]; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue; offset = 0; cal = customAttribute.value.length; if ( customAttribute.size === 1 ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; customAttribute.array[ ca ] = customAttribute.value[ index ]; } } else if ( customAttribute.size === 2 ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; offset += 2; } } else if ( customAttribute.size === 3 ) { if ( customAttribute.type === "c" ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.r; customAttribute.array[ offset + 1 ] = value.g; customAttribute.array[ offset + 2 ] = value.b; offset += 3; } } else { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; offset += 3; } } } else if ( customAttribute.size === 4 ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; customAttribute.array[ offset + 3 ] = value.w; offset += 4; } } } } } else { if ( dirtyVertices ) { for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } } if ( dirtyColors ) { for ( c = 0; c < cl; c ++ ) { color = colors[ c ]; offset = c * 3; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices") ) { cal = customAttribute.value.length; offset = 0; if ( customAttribute.size === 1 ) { for ( ca = 0; ca < cal; ca ++ ) { customAttribute.array[ ca ] = customAttribute.value[ ca ]; } } else if ( customAttribute.size === 2 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; offset += 2; } } else if ( customAttribute.size === 3 ) { if ( customAttribute.type === "c" ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.r; customAttribute.array[ offset + 1 ] = value.g; customAttribute.array[ offset + 2 ] = value.b; offset += 3; } } else { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; offset += 3; } } } else if ( customAttribute.size === 4 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; customAttribute.array[ offset + 3 ] = value.w; offset += 4; } } } } } } if ( dirtyVertices || object.sortParticles ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyColors || object.sortParticles ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( customAttribute.needsUpdate || object.sortParticles ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); } } } } function setLineBuffers ( geometry, hint ) { var v, c, d, vertex, offset, color, vertices = geometry.vertices, colors = geometry.colors, lineDistances = geometry.lineDistances, vl = vertices.length, cl = colors.length, dl = lineDistances.length, vertexArray = geometry.__vertexArray, colorArray = geometry.__colorArray, lineDistanceArray = geometry.__lineDistanceArray, dirtyVertices = geometry.verticesNeedUpdate, dirtyColors = geometry.colorsNeedUpdate, dirtyLineDistances = geometry.lineDistancesNeedUpdate, customAttributes = geometry.__webglCustomAttributesList, i, il, a, ca, cal, value, customAttribute; if ( dirtyVertices ) { for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyColors ) { for ( c = 0; c < cl; c ++ ) { color = colors[ c ]; offset = c * 3; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } if ( dirtyLineDistances ) { for ( d = 0; d < dl; d ++ ) { lineDistanceArray[ d ] = lineDistances[ d ]; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint ); } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) { offset = 0; cal = customAttribute.value.length; if ( customAttribute.size === 1 ) { for ( ca = 0; ca < cal; ca ++ ) { customAttribute.array[ ca ] = customAttribute.value[ ca ]; } } else if ( customAttribute.size === 2 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; offset += 2; } } else if ( customAttribute.size === 3 ) { if ( customAttribute.type === "c" ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.r; customAttribute.array[ offset + 1 ] = value.g; customAttribute.array[ offset + 2 ] = value.b; offset += 3; } } else { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; offset += 3; } } } else if ( customAttribute.size === 4 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; customAttribute.array[ offset + 3 ] = value.w; offset += 4; } } _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); } } } } function setMeshBuffers( geometryGroup, object, hint, dispose, material ) { if ( ! geometryGroup.__inittedArrays ) { return; } var normalType = bufferGuessNormalType( material ), vertexColorType = bufferGuessVertexColorType( material ), uvType = bufferGuessUVType( material ), needsSmoothNormals = ( normalType === THREE.SmoothShading ); var f, fl, fi, face, vertexNormals, faceNormal, normal, vertexColors, faceColor, vertexTangents, uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4, c1, c2, c3, c4, sw1, sw2, sw3, sw4, si1, si2, si3, si4, sa1, sa2, sa3, sa4, sb1, sb2, sb3, sb4, m, ml, i, il, vn, uvi, uv2i, vk, vkl, vka, nka, chf, faceVertexNormals, a, vertexIndex = 0, offset = 0, offset_uv = 0, offset_uv2 = 0, offset_face = 0, offset_normal = 0, offset_tangent = 0, offset_line = 0, offset_color = 0, offset_skin = 0, offset_morphTarget = 0, offset_custom = 0, offset_customSrc = 0, value, vertexArray = geometryGroup.__vertexArray, uvArray = geometryGroup.__uvArray, uv2Array = geometryGroup.__uv2Array, normalArray = geometryGroup.__normalArray, tangentArray = geometryGroup.__tangentArray, colorArray = geometryGroup.__colorArray, skinIndexArray = geometryGroup.__skinIndexArray, skinWeightArray = geometryGroup.__skinWeightArray, morphTargetsArrays = geometryGroup.__morphTargetsArrays, morphNormalsArrays = geometryGroup.__morphNormalsArrays, customAttributes = geometryGroup.__webglCustomAttributesList, customAttribute, faceArray = geometryGroup.__faceArray, lineArray = geometryGroup.__lineArray, geometry = object.geometry, // this is shared for all chunks dirtyVertices = geometry.verticesNeedUpdate, dirtyElements = geometry.elementsNeedUpdate, dirtyUvs = geometry.uvsNeedUpdate, dirtyNormals = geometry.normalsNeedUpdate, dirtyTangents = geometry.tangentsNeedUpdate, dirtyColors = geometry.colorsNeedUpdate, dirtyMorphTargets = geometry.morphTargetsNeedUpdate, vertices = geometry.vertices, chunk_faces3 = geometryGroup.faces3, obj_faces = geometry.faces, obj_uvs = geometry.faceVertexUvs[ 0 ], obj_uvs2 = geometry.faceVertexUvs[ 1 ], obj_colors = geometry.colors, obj_skinIndices = geometry.skinIndices, obj_skinWeights = geometry.skinWeights, morphTargets = geometry.morphTargets, morphNormals = geometry.morphNormals; if ( dirtyVertices ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = vertices[ face.a ]; v2 = vertices[ face.b ]; v3 = vertices[ face.c ]; vertexArray[ offset ] = v1.x; vertexArray[ offset + 1 ] = v1.y; vertexArray[ offset + 2 ] = v1.z; vertexArray[ offset + 3 ] = v2.x; vertexArray[ offset + 4 ] = v2.y; vertexArray[ offset + 5 ] = v2.z; vertexArray[ offset + 6 ] = v3.x; vertexArray[ offset + 7 ] = v3.y; vertexArray[ offset + 8 ] = v3.z; offset += 9; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyMorphTargets ) { for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) { offset_morphTarget = 0; for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { chf = chunk_faces3[ f ]; face = obj_faces[ chf ]; // morph positions v1 = morphTargets[ vk ].vertices[ face.a ]; v2 = morphTargets[ vk ].vertices[ face.b ]; v3 = morphTargets[ vk ].vertices[ face.c ]; vka = morphTargetsArrays[ vk ]; vka[ offset_morphTarget ] = v1.x; vka[ offset_morphTarget + 1 ] = v1.y; vka[ offset_morphTarget + 2 ] = v1.z; vka[ offset_morphTarget + 3 ] = v2.x; vka[ offset_morphTarget + 4 ] = v2.y; vka[ offset_morphTarget + 5 ] = v2.z; vka[ offset_morphTarget + 6 ] = v3.x; vka[ offset_morphTarget + 7 ] = v3.y; vka[ offset_morphTarget + 8 ] = v3.z; // morph normals if ( material.morphNormals ) { if ( needsSmoothNormals ) { faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ]; n1 = faceVertexNormals.a; n2 = faceVertexNormals.b; n3 = faceVertexNormals.c; } else { n1 = morphNormals[ vk ].faceNormals[ chf ]; n2 = n1; n3 = n1; } nka = morphNormalsArrays[ vk ]; nka[ offset_morphTarget ] = n1.x; nka[ offset_morphTarget + 1 ] = n1.y; nka[ offset_morphTarget + 2 ] = n1.z; nka[ offset_morphTarget + 3 ] = n2.x; nka[ offset_morphTarget + 4 ] = n2.y; nka[ offset_morphTarget + 5 ] = n2.z; nka[ offset_morphTarget + 6 ] = n3.x; nka[ offset_morphTarget + 7 ] = n3.y; nka[ offset_morphTarget + 8 ] = n3.z; } // offset_morphTarget += 9; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] ); _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint ); if ( material.morphNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] ); _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint ); } } } if ( obj_skinWeights.length ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; // weights sw1 = obj_skinWeights[ face.a ]; sw2 = obj_skinWeights[ face.b ]; sw3 = obj_skinWeights[ face.c ]; skinWeightArray[ offset_skin ] = sw1.x; skinWeightArray[ offset_skin + 1 ] = sw1.y; skinWeightArray[ offset_skin + 2 ] = sw1.z; skinWeightArray[ offset_skin + 3 ] = sw1.w; skinWeightArray[ offset_skin + 4 ] = sw2.x; skinWeightArray[ offset_skin + 5 ] = sw2.y; skinWeightArray[ offset_skin + 6 ] = sw2.z; skinWeightArray[ offset_skin + 7 ] = sw2.w; skinWeightArray[ offset_skin + 8 ] = sw3.x; skinWeightArray[ offset_skin + 9 ] = sw3.y; skinWeightArray[ offset_skin + 10 ] = sw3.z; skinWeightArray[ offset_skin + 11 ] = sw3.w; // indices si1 = obj_skinIndices[ face.a ]; si2 = obj_skinIndices[ face.b ]; si3 = obj_skinIndices[ face.c ]; skinIndexArray[ offset_skin ] = si1.x; skinIndexArray[ offset_skin + 1 ] = si1.y; skinIndexArray[ offset_skin + 2 ] = si1.z; skinIndexArray[ offset_skin + 3 ] = si1.w; skinIndexArray[ offset_skin + 4 ] = si2.x; skinIndexArray[ offset_skin + 5 ] = si2.y; skinIndexArray[ offset_skin + 6 ] = si2.z; skinIndexArray[ offset_skin + 7 ] = si2.w; skinIndexArray[ offset_skin + 8 ] = si3.x; skinIndexArray[ offset_skin + 9 ] = si3.y; skinIndexArray[ offset_skin + 10 ] = si3.z; skinIndexArray[ offset_skin + 11 ] = si3.w; offset_skin += 12; } if ( offset_skin > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint ); } } if ( dirtyColors && vertexColorType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; vertexColors = face.vertexColors; faceColor = face.color; if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) { c1 = vertexColors[ 0 ]; c2 = vertexColors[ 1 ]; c3 = vertexColors[ 2 ]; } else { c1 = faceColor; c2 = faceColor; c3 = faceColor; } colorArray[ offset_color ] = c1.r; colorArray[ offset_color + 1 ] = c1.g; colorArray[ offset_color + 2 ] = c1.b; colorArray[ offset_color + 3 ] = c2.r; colorArray[ offset_color + 4 ] = c2.g; colorArray[ offset_color + 5 ] = c2.b; colorArray[ offset_color + 6 ] = c3.r; colorArray[ offset_color + 7 ] = c3.g; colorArray[ offset_color + 8 ] = c3.b; offset_color += 9; } if ( offset_color > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } } if ( dirtyTangents && geometry.hasTangents ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; vertexTangents = face.vertexTangents; t1 = vertexTangents[ 0 ]; t2 = vertexTangents[ 1 ]; t3 = vertexTangents[ 2 ]; tangentArray[ offset_tangent ] = t1.x; tangentArray[ offset_tangent + 1 ] = t1.y; tangentArray[ offset_tangent + 2 ] = t1.z; tangentArray[ offset_tangent + 3 ] = t1.w; tangentArray[ offset_tangent + 4 ] = t2.x; tangentArray[ offset_tangent + 5 ] = t2.y; tangentArray[ offset_tangent + 6 ] = t2.z; tangentArray[ offset_tangent + 7 ] = t2.w; tangentArray[ offset_tangent + 8 ] = t3.x; tangentArray[ offset_tangent + 9 ] = t3.y; tangentArray[ offset_tangent + 10 ] = t3.z; tangentArray[ offset_tangent + 11 ] = t3.w; offset_tangent += 12; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint ); } if ( dirtyNormals && normalType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; vertexNormals = face.vertexNormals; faceNormal = face.normal; if ( vertexNormals.length === 3 && needsSmoothNormals ) { for ( i = 0; i < 3; i ++ ) { vn = vertexNormals[ i ]; normalArray[ offset_normal ] = vn.x; normalArray[ offset_normal + 1 ] = vn.y; normalArray[ offset_normal + 2 ] = vn.z; offset_normal += 3; } } else { for ( i = 0; i < 3; i ++ ) { normalArray[ offset_normal ] = faceNormal.x; normalArray[ offset_normal + 1 ] = faceNormal.y; normalArray[ offset_normal + 2 ] = faceNormal.z; offset_normal += 3; } } } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint ); } if ( dirtyUvs && obj_uvs && uvType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { fi = chunk_faces3[ f ]; uv = obj_uvs[ fi ]; if ( uv === undefined ) continue; for ( i = 0; i < 3; i ++ ) { uvi = uv[ i ]; uvArray[ offset_uv ] = uvi.x; uvArray[ offset_uv + 1 ] = uvi.y; offset_uv += 2; } } if ( offset_uv > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint ); } } if ( dirtyUvs && obj_uvs2 && uvType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { fi = chunk_faces3[ f ]; uv2 = obj_uvs2[ fi ]; if ( uv2 === undefined ) continue; for ( i = 0; i < 3; i ++ ) { uv2i = uv2[ i ]; uv2Array[ offset_uv2 ] = uv2i.x; uv2Array[ offset_uv2 + 1 ] = uv2i.y; offset_uv2 += 2; } } if ( offset_uv2 > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint ); } } if ( dirtyElements ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { faceArray[ offset_face ] = vertexIndex; faceArray[ offset_face + 1 ] = vertexIndex + 1; faceArray[ offset_face + 2 ] = vertexIndex + 2; offset_face += 3; lineArray[ offset_line ] = vertexIndex; lineArray[ offset_line + 1 ] = vertexIndex + 1; lineArray[ offset_line + 2 ] = vertexIndex; lineArray[ offset_line + 3 ] = vertexIndex + 2; lineArray[ offset_line + 4 ] = vertexIndex + 1; lineArray[ offset_line + 5 ] = vertexIndex + 2; offset_line += 6; vertexIndex += 3; } _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint ); } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( ! customAttribute.__original.needsUpdate ) continue; offset_custom = 0; offset_customSrc = 0; if ( customAttribute.size === 1 ) { if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ]; customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ]; customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ]; offset_custom += 3; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; customAttribute.array[ offset_custom ] = value; customAttribute.array[ offset_custom + 1 ] = value; customAttribute.array[ offset_custom + 2 ] = value; offset_custom += 3; } } } else if ( customAttribute.size === 2 ) { if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v2.x; customAttribute.array[ offset_custom + 3 ] = v2.y; customAttribute.array[ offset_custom + 4 ] = v3.x; customAttribute.array[ offset_custom + 5 ] = v3.y; offset_custom += 6; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value; v2 = value; v3 = value; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v2.x; customAttribute.array[ offset_custom + 3 ] = v2.y; customAttribute.array[ offset_custom + 4 ] = v3.x; customAttribute.array[ offset_custom + 5 ] = v3.y; offset_custom += 6; } } } else if ( customAttribute.size === 3 ) { var pp; if ( customAttribute.type === "c" ) { pp = [ "r", "g", "b" ]; } else { pp = [ "x", "y", "z" ]; } if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; offset_custom += 9; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value; v2 = value; v3 = value; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; offset_custom += 9; } } else if ( customAttribute.boundTo === "faceVertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value[ 0 ]; v2 = value[ 1 ]; v3 = value[ 2 ]; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; offset_custom += 9; } } } else if ( customAttribute.size === 4 ) { if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; offset_custom += 12; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value; v2 = value; v3 = value; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; offset_custom += 12; } } else if ( customAttribute.boundTo === "faceVertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value[ 0 ]; v2 = value[ 1 ]; v3 = value[ 2 ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; offset_custom += 12; } } } _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); } } if ( dispose ) { delete geometryGroup.__inittedArrays; delete geometryGroup.__colorArray; delete geometryGroup.__normalArray; delete geometryGroup.__tangentArray; delete geometryGroup.__uvArray; delete geometryGroup.__uv2Array; delete geometryGroup.__faceArray; delete geometryGroup.__vertexArray; delete geometryGroup.__lineArray; delete geometryGroup.__skinIndexArray; delete geometryGroup.__skinWeightArray; } }; function setDirectBuffers( geometry, hint ) { var attributes = geometry.attributes; var attributeName, attributeItem; for ( attributeName in attributes ) { attributeItem = attributes[ attributeName ]; if ( attributeItem.needsUpdate ) { if ( attributeName === 'index' ) { _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer ); _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint ); } else { _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint ); } attributeItem.needsUpdate = false; } } } // Buffer rendering this.renderBufferImmediate = function ( object, program, material ) { if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer(); if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer(); if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer(); if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer(); if ( object.hasPositions ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.position ); _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.hasNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer ); if ( material.shading === THREE.FlatShading ) { var nx, ny, nz, nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz, normalArray, i, il = object.count * 3; for( i = 0; i < il; i += 9 ) { normalArray = object.normalArray; nax = normalArray[ i ]; nay = normalArray[ i + 1 ]; naz = normalArray[ i + 2 ]; nbx = normalArray[ i + 3 ]; nby = normalArray[ i + 4 ]; nbz = normalArray[ i + 5 ]; ncx = normalArray[ i + 6 ]; ncy = normalArray[ i + 7 ]; ncz = normalArray[ i + 8 ]; nx = ( nax + nbx + ncx ) / 3; ny = ( nay + nby + ncy ) / 3; nz = ( naz + nbz + ncz ) / 3; normalArray[ i ] = nx; normalArray[ i + 1 ] = ny; normalArray[ i + 2 ] = nz; normalArray[ i + 3 ] = nx; normalArray[ i + 4 ] = ny; normalArray[ i + 5 ] = nz; normalArray[ i + 6 ] = nx; normalArray[ i + 7 ] = ny; normalArray[ i + 8 ] = nz; } } _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.normal ); _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.hasUvs && material.map ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.uv ); _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); } if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.color ); _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 ); } _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); object.count = 0; }; function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) { for ( var attributeName in programAttributes ) { var attributePointer = programAttributes[ attributeName ]; var attributeItem = geometryAttributes[ attributeName ]; if ( attributePointer >= 0 ) { if ( attributeItem ) { var attributeSize = attributeItem.itemSize; _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); enableAttribute( attributePointer ); _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32 } else if ( material.defaultAttributeValues ) { if ( material.defaultAttributeValues[ attributeName ].length === 2 ) { _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) { _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); } } } } } this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) { if ( material.visible === false ) return; var linewidth, a, attribute; var attributeItem, attributeName, attributePointer, attributeSize; var program = setProgram( camera, lights, fog, material, object ); var programAttributes = program.attributes; var geometryAttributes = geometry.attributes; var updateBuffers = false, wireframeBit = material.wireframe ? 1 : 0, geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; if ( geometryHash !== _currentGeometryGroupHash ) { _currentGeometryGroupHash = geometryHash; updateBuffers = true; } if ( updateBuffers ) { disableAttributes(); } // render mesh if ( object instanceof THREE.Mesh ) { var index = geometryAttributes[ "index" ]; if ( index ) { // indexed triangles var type, size; if ( index.array instanceof Uint32Array ) { type = _gl.UNSIGNED_INT; size = 4; } else { type = _gl.UNSIGNED_SHORT; size = 2; } var offsets = geometry.offsets; if ( offsets.length === 0 ) { if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); } _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 ); _this.info.render.calls ++; _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared _this.info.render.faces += index.array.length / 3; } else { // if there is more than 1 chunk // must set attribute pointers to use new offsets for each chunk // even if geometry and materials didn't change updateBuffers = true; for ( var i = 0, il = offsets.length; i < il; i ++ ) { var startIndex = offsets[ i ].index; if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); } // render indexed triangles _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size ); _this.info.render.calls ++; _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared _this.info.render.faces += offsets[ i ].count / 3; } } } else { // non-indexed triangles if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); } var position = geometry.attributes[ "position" ]; // render non-indexed triangles _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 ); _this.info.render.calls ++; _this.info.render.vertices += position.array.length / 3; _this.info.render.faces += position.array.length / 3 / 3; } } else if ( object instanceof THREE.ParticleSystem ) { // render particles if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); } var position = geometryAttributes[ "position" ]; // render particles _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 ); _this.info.render.calls ++; _this.info.render.points += position.array.length / 3; } else if ( object instanceof THREE.Line ) { var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; setLineWidth( material.linewidth ); var index = geometryAttributes[ "index" ]; if ( index ) { // indexed lines var type, size; if ( index.array instanceof Uint32Array ){ type = _gl.UNSIGNED_INT; size = 4; } else { type = _gl.UNSIGNED_SHORT; size = 2; } var offsets = geometry.offsets; if ( offsets.length === 0 ) { if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); } _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array _this.info.render.calls ++; _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared } else { // if there is more than 1 chunk // must set attribute pointers to use new offsets for each chunk // even if geometry and materials didn't change if ( offsets.length > 1 ) updateBuffers = true; for ( var i = 0, il = offsets.length; i < il; i ++ ) { var startIndex = offsets[ i ].index; if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); } // render indexed lines _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array _this.info.render.calls ++; _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared } } } else { // non-indexed lines if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); } var position = geometryAttributes[ "position" ]; _gl.drawArrays( primitives, 0, position.array.length / 3 ); _this.info.render.calls ++; _this.info.render.points += position.array.length; } } }; this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) { if ( material.visible === false ) return; var linewidth, a, attribute, i, il; var program = setProgram( camera, lights, fog, material, object ); var attributes = program.attributes; var updateBuffers = false, wireframeBit = material.wireframe ? 1 : 0, geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; if ( geometryGroupHash !== _currentGeometryGroupHash ) { _currentGeometryGroupHash = geometryGroupHash; updateBuffers = true; } if ( updateBuffers ) { disableAttributes(); } // vertices if ( !material.morphTargets && attributes.position >= 0 ) { if ( updateBuffers ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); enableAttribute( attributes.position ); _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } } else { if ( object.morphTargetBase ) { setupMorphTargets( material, geometryGroup, object ); } } if ( updateBuffers ) { // custom attributes // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers if ( geometryGroup.__webglCustomAttributesList ) { for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) { attribute = geometryGroup.__webglCustomAttributesList[ i ]; if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer ); enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] ); _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 ); } } } // colors if ( attributes.color >= 0 ) { if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); enableAttribute( attributes.color ); _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); } else if ( material.defaultAttributeValues ) { _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color ); } } // normals if ( attributes.normal >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); enableAttribute( attributes.normal ); _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); } // tangents if ( attributes.tangent >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); enableAttribute( attributes.tangent ); _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 ); } // uvs if ( attributes.uv >= 0 ) { if ( object.geometry.faceVertexUvs[0] ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); enableAttribute( attributes.uv ); _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); } else if ( material.defaultAttributeValues ) { _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv ); } } if ( attributes.uv2 >= 0 ) { if ( object.geometry.faceVertexUvs[1] ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); enableAttribute( attributes.uv2 ); _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 ); } else if ( material.defaultAttributeValues ) { _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 ); } } if ( material.skinning && attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); enableAttribute( attributes.skinIndex ); _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); enableAttribute( attributes.skinWeight ); _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 ); } // line distances if ( attributes.lineDistance >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer ); enableAttribute( attributes.lineDistance ); _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 ); } } // render mesh if ( object instanceof THREE.Mesh ) { var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT; // wireframe if ( material.wireframe ) { setLineWidth( material.wireframeLinewidth ); if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 ); // triangles } else { if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 ); } _this.info.render.calls ++; _this.info.render.vertices += geometryGroup.__webglFaceCount; _this.info.render.faces += geometryGroup.__webglFaceCount / 3; // render lines } else if ( object instanceof THREE.Line ) { var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; setLineWidth( material.linewidth ); _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount ); _this.info.render.calls ++; // render particles } else if ( object instanceof THREE.ParticleSystem ) { _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount ); _this.info.render.calls ++; _this.info.render.points += geometryGroup.__webglParticleCount; } }; function enableAttribute( attribute ) { if ( _enabledAttributes[ attribute ] === 0 ) { _gl.enableVertexAttribArray( attribute ); _enabledAttributes[ attribute ] = 1; } }; function disableAttributes() { for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) { if ( _enabledAttributes[ i ] === 1 ) { _gl.disableVertexAttribArray( i ); _enabledAttributes[ i ] = 0; } } }; function setupMorphTargets ( material, geometryGroup, object ) { // set base var attributes = material.program.attributes; if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] ); enableAttribute( attributes.position ); _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } else if ( attributes.position >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); enableAttribute( attributes.position ); _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.morphTargetForcedOrder.length ) { // set forced order var m = 0; var order = object.morphTargetForcedOrder; var influences = object.morphTargetInfluences; while ( m < material.numSupportedMorphTargets && m < order.length ) { if ( attributes[ "morphTarget" + m ] >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] ); enableAttribute( attributes[ "morphTarget" + m ] ); _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); } if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] ); enableAttribute( attributes[ "morphNormal" + m ] ); _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); } object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ]; m ++; } } else { // find the most influencing var influence, activeInfluenceIndices = []; var influences = object.morphTargetInfluences; var i, il = influences.length; for ( i = 0; i < il; i ++ ) { influence = influences[ i ]; if ( influence > 0 ) { activeInfluenceIndices.push( [ influence, i ] ); } } if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) { activeInfluenceIndices.sort( numericalSort ); activeInfluenceIndices.length = material.numSupportedMorphTargets; } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) { activeInfluenceIndices.sort( numericalSort ); } else if ( activeInfluenceIndices.length === 0 ) { activeInfluenceIndices.push( [ 0, 0 ] ); }; var influenceIndex, m = 0; while ( m < material.numSupportedMorphTargets ) { if ( activeInfluenceIndices[ m ] ) { influenceIndex = activeInfluenceIndices[ m ][ 1 ]; if ( attributes[ "morphTarget" + m ] >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] ); enableAttribute( attributes[ "morphTarget" + m ] ); _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); } if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] ); enableAttribute( attributes[ "morphNormal" + m ] ); _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); } object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ]; } else { /* _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); if ( material.morphNormals ) { _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); } */ object.__webglMorphTargetInfluences[ m ] = 0; } m ++; } } // load updated influences uniform if ( material.program.uniforms.morphTargetInfluences !== null ) { _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences ); } }; // Sorting function painterSortStable ( a, b ) { if ( a.materialId !== b.materialId ) { return b.materialId - a.materialId; } else if ( a.z !== b.z ) { return b.z - a.z; } else { return a.id - b.id; } }; function numericalSort ( a, b ) { return b[ 0 ] - a[ 0 ]; }; // Rendering this.render = function ( scene, camera, renderTarget, forceClear ) { if ( camera instanceof THREE.Camera === false ) { console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); return; } var i, il, webglObject, object, renderList, lights = scene.__lights, fog = scene.fog; // reset caching for this frame _currentMaterialId = -1; _lightsNeedUpdate = true; // update scene graph if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); // update camera matrices and frustum if ( camera.parent === undefined ) camera.updateMatrixWorld(); camera.matrixWorldInverse.getInverse( camera.matrixWorld ); _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); _frustum.setFromMatrix( _projScreenMatrix ); // update WebGL objects if ( this.autoUpdateObjects ) this.initWebGLObjects( scene ); // custom render plugins (pre pass) renderPlugins( this.renderPluginsPre, scene, camera ); // _this.info.render.calls = 0; _this.info.render.vertices = 0; _this.info.render.faces = 0; _this.info.render.points = 0; this.setRenderTarget( renderTarget ); if ( this.autoClear || forceClear ) { this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); } // set matrices for regular objects (frustum culled) renderList = scene.__webglObjects; for ( i = 0, il = renderList.length; i < il; i ++ ) { webglObject = renderList[ i ]; object = webglObject.object; webglObject.id = i; webglObject.materialId = object.material.id; webglObject.render = false; if ( object.visible ) { if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) { setupMatrices( object, camera ); unrollBufferMaterial( webglObject ); webglObject.render = true; if ( this.sortObjects === true ) { if ( object.renderDepth !== null ) { webglObject.z = object.renderDepth; } else { _vector3.setFromMatrixPosition( object.matrixWorld ); _vector3.applyProjection( _projScreenMatrix ); webglObject.z = _vector3.z; } } } } } if ( this.sortObjects ) { renderList.sort( painterSortStable ); } // set matrices for immediate objects renderList = scene.__webglObjectsImmediate; for ( i = 0, il = renderList.length; i < il; i ++ ) { webglObject = renderList[ i ]; object = webglObject.object; if ( object.visible ) { setupMatrices( object, camera ); unrollImmediateBufferMaterial( webglObject ); } } if ( scene.overrideMaterial ) { var material = scene.overrideMaterial; this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); this.setDepthTest( material.depthTest ); this.setDepthWrite( material.depthWrite ); setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material ); renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material ); } else { var material = null; // opaque pass (front-to-back order) this.setBlending( THREE.NoBlending ); renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material ); renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material ); // transparent pass (back-to-front order) renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material ); renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material ); } // custom render plugins (post pass) renderPlugins( this.renderPluginsPost, scene, camera ); // Generate mipmap if we're using any kind of mipmap filtering if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) { updateRenderTargetMipmap( renderTarget ); } // Ensure depth buffer writing is enabled so it can be cleared on next render this.setDepthTest( true ); this.setDepthWrite( true ); // _gl.finish(); }; function renderPlugins( plugins, scene, camera ) { if ( ! plugins.length ) return; for ( var i = 0, il = plugins.length; i < il; i ++ ) { // reset state for plugin (to start from clean slate) _currentProgram = null; _currentCamera = null; _oldBlending = -1; _oldDepthTest = -1; _oldDepthWrite = -1; _oldDoubleSided = -1; _oldFlipSided = -1; _currentGeometryGroupHash = -1; _currentMaterialId = -1; _lightsNeedUpdate = true; plugins[ i ].render( scene, camera, _currentWidth, _currentHeight ); // reset state after plugin (anything could have changed) _currentProgram = null; _currentCamera = null; _oldBlending = -1; _oldDepthTest = -1; _oldDepthWrite = -1; _oldDoubleSided = -1; _oldFlipSided = -1; _currentGeometryGroupHash = -1; _currentMaterialId = -1; _lightsNeedUpdate = true; } }; function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) { var webglObject, object, buffer, material, start, end, delta; if ( reverse ) { start = renderList.length - 1; end = -1; delta = -1; } else { start = 0; end = renderList.length; delta = 1; } for ( var i = start; i !== end; i += delta ) { webglObject = renderList[ i ]; if ( webglObject.render ) { object = webglObject.object; buffer = webglObject.buffer; if ( overrideMaterial ) { material = overrideMaterial; } else { material = webglObject[ materialType ]; if ( ! material ) continue; if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); _this.setDepthTest( material.depthTest ); _this.setDepthWrite( material.depthWrite ); setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); } _this.setMaterialFaces( material ); if ( buffer instanceof THREE.BufferGeometry ) { _this.renderBufferDirect( camera, lights, fog, material, buffer, object ); } else { _this.renderBuffer( camera, lights, fog, material, buffer, object ); } } } }; function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) { var webglObject, object, material, program; for ( var i = 0, il = renderList.length; i < il; i ++ ) { webglObject = renderList[ i ]; object = webglObject.object; if ( object.visible ) { if ( overrideMaterial ) { material = overrideMaterial; } else { material = webglObject[ materialType ]; if ( ! material ) continue; if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); _this.setDepthTest( material.depthTest ); _this.setDepthWrite( material.depthWrite ); setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); } _this.renderImmediateObject( camera, lights, fog, material, object ); } } }; this.renderImmediateObject = function ( camera, lights, fog, material, object ) { var program = setProgram( camera, lights, fog, material, object ); _currentGeometryGroupHash = -1; _this.setMaterialFaces( material ); if ( object.immediateRenderCallback ) { object.immediateRenderCallback( program, _gl, _frustum ); } else { object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } ); } }; function unrollImmediateBufferMaterial ( globject ) { var object = globject.object, material = object.material; if ( material.transparent ) { globject.transparent = material; globject.opaque = null; } else { globject.opaque = material; globject.transparent = null; } }; function unrollBufferMaterial ( globject ) { var object = globject.object; var buffer = globject.buffer; var geometry = object.geometry; var material = object.material; if ( material instanceof THREE.MeshFaceMaterial ) { var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex; material = material.materials[ materialIndex ]; if ( material.transparent ) { globject.transparent = material; globject.opaque = null; } else { globject.opaque = material; globject.transparent = null; } } else { if ( material ) { if ( material.transparent ) { globject.transparent = material; globject.opaque = null; } else { globject.opaque = material; globject.transparent = null; } } } }; // Objects refresh this.initWebGLObjects = function ( scene ) { if ( !scene.__webglObjects ) { scene.__webglObjects = []; scene.__webglObjectsImmediate = []; scene.__webglSprites = []; scene.__webglFlares = []; } while ( scene.__objectsAdded.length ) { addObject( scene.__objectsAdded[ 0 ], scene ); scene.__objectsAdded.splice( 0, 1 ); } while ( scene.__objectsRemoved.length ) { removeObject( scene.__objectsRemoved[ 0 ], scene ); scene.__objectsRemoved.splice( 0, 1 ); } // update must be called after objects adding / removal for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) { var object = scene.__webglObjects[ o ].object; // TODO: Remove this hack (WebGLRenderer refactoring) if ( object.__webglInit === undefined ) { if ( object.__webglActive !== undefined ) { removeObject( object, scene ); } addObject( object, scene ); } updateObject( object ); } }; // Objects adding function addObject( object, scene ) { var g, geometry, material, geometryGroup; if ( object.__webglInit === undefined ) { object.__webglInit = true; object._modelViewMatrix = new THREE.Matrix4(); object._normalMatrix = new THREE.Matrix3(); if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) { object.geometry.__webglInit = true; object.geometry.addEventListener( 'dispose', onGeometryDispose ); } geometry = object.geometry; if ( geometry === undefined ) { // fail silently for now } else if ( geometry instanceof THREE.BufferGeometry ) { initDirectBuffers( geometry ); } else if ( object instanceof THREE.Mesh ) { material = object.material; if ( geometry.geometryGroups === undefined ) { geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 ); } // create separate VBOs per geometry chunk for ( g in geometry.geometryGroups ) { geometryGroup = geometry.geometryGroups[ g ]; // initialise VBO on the first access if ( ! geometryGroup.__webglVertexBuffer ) { createMeshBuffers( geometryGroup ); initMeshBuffers( geometryGroup, object ); geometry.verticesNeedUpdate = true; geometry.morphTargetsNeedUpdate = true; geometry.elementsNeedUpdate = true; geometry.uvsNeedUpdate = true; geometry.normalsNeedUpdate = true; geometry.tangentsNeedUpdate = true; geometry.colorsNeedUpdate = true; } } } else if ( object instanceof THREE.Line ) { if ( ! geometry.__webglVertexBuffer ) { createLineBuffers( geometry ); initLineBuffers( geometry, object ); geometry.verticesNeedUpdate = true; geometry.colorsNeedUpdate = true; geometry.lineDistancesNeedUpdate = true; } } else if ( object instanceof THREE.ParticleSystem ) { if ( ! geometry.__webglVertexBuffer ) { createParticleBuffers( geometry ); initParticleBuffers( geometry, object ); geometry.verticesNeedUpdate = true; geometry.colorsNeedUpdate = true; } } } if ( object.__webglActive === undefined ) { if ( object instanceof THREE.Mesh ) { geometry = object.geometry; if ( geometry instanceof THREE.BufferGeometry ) { addBuffer( scene.__webglObjects, geometry, object ); } else if ( geometry instanceof THREE.Geometry ) { for ( g in geometry.geometryGroups ) { geometryGroup = geometry.geometryGroups[ g ]; addBuffer( scene.__webglObjects, geometryGroup, object ); } } } else if ( object instanceof THREE.Line || object instanceof THREE.ParticleSystem ) { geometry = object.geometry; addBuffer( scene.__webglObjects, geometry, object ); } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { addBufferImmediate( scene.__webglObjectsImmediate, object ); } else if ( object instanceof THREE.Sprite ) { scene.__webglSprites.push( object ); } else if ( object instanceof THREE.LensFlare ) { scene.__webglFlares.push( object ); } object.__webglActive = true; } }; function addBuffer( objlist, buffer, object ) { objlist.push( { id: null, buffer: buffer, object: object, materialId: null, opaque: null, transparent: null, z: 0 } ); }; function addBufferImmediate( objlist, object ) { objlist.push( { id: null, object: object, opaque: null, transparent: null, z: 0 } ); }; // Objects updates function updateObject( object ) { var geometry = object.geometry, geometryGroup, customAttributesDirty, material; if ( geometry instanceof THREE.BufferGeometry ) { setDirectBuffers( geometry, _gl.DYNAMIC_DRAW ); } else if ( object instanceof THREE.Mesh ) { // check all geometry groups for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) { geometryGroup = geometry.geometryGroupsList[ i ]; material = getBufferMaterial( object, geometryGroup ); if ( geometry.buffersNeedUpdate ) { initMeshBuffers( geometryGroup, object ); } customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate || geometry.uvsNeedUpdate || geometry.normalsNeedUpdate || geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) { setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material ); } } geometry.verticesNeedUpdate = false; geometry.morphTargetsNeedUpdate = false; geometry.elementsNeedUpdate = false; geometry.uvsNeedUpdate = false; geometry.normalsNeedUpdate = false; geometry.colorsNeedUpdate = false; geometry.tangentsNeedUpdate = false; geometry.buffersNeedUpdate = false; material.attributes && clearCustomAttributes( material ); } else if ( object instanceof THREE.Line ) { material = getBufferMaterial( object, geometry ); customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) { setLineBuffers( geometry, _gl.DYNAMIC_DRAW ); } geometry.verticesNeedUpdate = false; geometry.colorsNeedUpdate = false; geometry.lineDistancesNeedUpdate = false; material.attributes && clearCustomAttributes( material ); } else if ( object instanceof THREE.ParticleSystem ) { material = getBufferMaterial( object, geometry ); customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) { setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object ); } geometry.verticesNeedUpdate = false; geometry.colorsNeedUpdate = false; material.attributes && clearCustomAttributes( material ); } }; // Objects updates - custom attributes check function areCustomAttributesDirty( material ) { for ( var a in material.attributes ) { if ( material.attributes[ a ].needsUpdate ) return true; } return false; }; function clearCustomAttributes( material ) { for ( var a in material.attributes ) { material.attributes[ a ].needsUpdate = false; } }; // Objects removal function removeObject( object, scene ) { if ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem || object instanceof THREE.Line ) { removeInstances( scene.__webglObjects, object ); } else if ( object instanceof THREE.Sprite ) { removeInstancesDirect( scene.__webglSprites, object ); } else if ( object instanceof THREE.LensFlare ) { removeInstancesDirect( scene.__webglFlares, object ); } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { removeInstances( scene.__webglObjectsImmediate, object ); } delete object.__webglActive; }; function removeInstances( objlist, object ) { for ( var o = objlist.length - 1; o >= 0; o -- ) { if ( objlist[ o ].object === object ) { objlist.splice( o, 1 ); } } }; function removeInstancesDirect( objlist, object ) { for ( var o = objlist.length - 1; o >= 0; o -- ) { if ( objlist[ o ] === object ) { objlist.splice( o, 1 ); } } }; // Materials this.initMaterial = function ( material, lights, fog, object ) { material.addEventListener( 'dispose', onMaterialDispose ); var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID; if ( material instanceof THREE.MeshDepthMaterial ) { shaderID = 'depth'; } else if ( material instanceof THREE.MeshNormalMaterial ) { shaderID = 'normal'; } else if ( material instanceof THREE.MeshBasicMaterial ) { shaderID = 'basic'; } else if ( material instanceof THREE.MeshLambertMaterial ) { shaderID = 'lambert'; } else if ( material instanceof THREE.MeshPhongMaterial ) { shaderID = 'phong'; } else if ( material instanceof THREE.LineBasicMaterial ) { shaderID = 'basic'; } else if ( material instanceof THREE.LineDashedMaterial ) { shaderID = 'dashed'; } else if ( material instanceof THREE.ParticleSystemMaterial ) { shaderID = 'particle_basic'; } if ( shaderID ) { setMaterialShaders( material, THREE.ShaderLib[ shaderID ] ); } // heuristics to create shader parameters according to lights in the scene // (not to blow over maxLights budget) maxLightCount = allocateLights( lights ); maxShadows = allocateShadows( lights ); maxBones = allocateBones( object ); parameters = { map: !!material.map, envMap: !!material.envMap, lightMap: !!material.lightMap, bumpMap: !!material.bumpMap, normalMap: !!material.normalMap, specularMap: !!material.specularMap, vertexColors: material.vertexColors, fog: fog, useFog: material.fog, fogExp: fog instanceof THREE.FogExp2, sizeAttenuation: material.sizeAttenuation, skinning: material.skinning, maxBones: maxBones, useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture, morphTargets: material.morphTargets, morphNormals: material.morphNormals, maxMorphTargets: this.maxMorphTargets, maxMorphNormals: this.maxMorphNormals, maxDirLights: maxLightCount.directional, maxPointLights: maxLightCount.point, maxSpotLights: maxLightCount.spot, maxHemiLights: maxLightCount.hemi, maxShadows: maxShadows, shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0, shadowMapType: this.shadowMapType, shadowMapDebug: this.shadowMapDebug, shadowMapCascade: this.shadowMapCascade, alphaTest: material.alphaTest, metal: material.metal, wrapAround: material.wrapAround, doubleSided: material.side === THREE.DoubleSide, flipSided: material.side === THREE.BackSide }; material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName ); var attributes = material.program.attributes; if ( material.morphTargets ) { material.numSupportedMorphTargets = 0; var id, base = "morphTarget"; for ( i = 0; i < this.maxMorphTargets; i ++ ) { id = base + i; if ( attributes[ id ] >= 0 ) { material.numSupportedMorphTargets ++; } } } if ( material.morphNormals ) { material.numSupportedMorphNormals = 0; var id, base = "morphNormal"; for ( i = 0; i < this.maxMorphNormals; i ++ ) { id = base + i; if ( attributes[ id ] >= 0 ) { material.numSupportedMorphNormals ++; } } } material.uniformsList = []; for ( u in material.uniforms ) { material.uniformsList.push( [ material.uniforms[ u ], u ] ); } }; function setMaterialShaders( material, shaders ) { material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms ); material.vertexShader = shaders.vertexShader; material.fragmentShader = shaders.fragmentShader; }; function setProgram( camera, lights, fog, material, object ) { _usedTextureUnits = 0; if ( material.needsUpdate ) { if ( material.program ) deallocateMaterial( material ); _this.initMaterial( material, lights, fog, object ); material.needsUpdate = false; } if ( material.morphTargets ) { if ( ! object.__webglMorphTargetInfluences ) { object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets ); } } var refreshMaterial = false; var program = material.program, p_uniforms = program.uniforms, m_uniforms = material.uniforms; if ( program !== _currentProgram ) { _gl.useProgram( program ); _currentProgram = program; refreshMaterial = true; } if ( material.id !== _currentMaterialId ) { _currentMaterialId = material.id; refreshMaterial = true; } if ( refreshMaterial || camera !== _currentCamera ) { _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); if ( camera !== _currentCamera ) _currentCamera = camera; } // skinning uniforms must be set even if material didn't change // auto-setting of texture unit for bone texture must go before other textures // not sure why, but otherwise weird things happen if ( material.skinning ) { if ( _supportsBoneTextures && object.useVertexTexture ) { if ( p_uniforms.boneTexture !== null ) { var textureUnit = getTextureUnit(); _gl.uniform1i( p_uniforms.boneTexture, textureUnit ); _this.setTexture( object.boneTexture, textureUnit ); } if ( p_uniforms.boneTextureWidth !== null ) { _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth ); } if ( p_uniforms.boneTextureHeight !== null ) { _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight ); } } else { if ( p_uniforms.boneGlobalMatrices !== null ) { _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices ); } } } if ( refreshMaterial ) { // refresh uniforms common to several materials if ( fog && material.fog ) { refreshUniformsFog( m_uniforms, fog ); } if ( material instanceof THREE.MeshPhongMaterial || material instanceof THREE.MeshLambertMaterial || material.lights ) { if ( _lightsNeedUpdate ) { setupLights( program, lights ); _lightsNeedUpdate = false; } refreshUniformsLights( m_uniforms, _lights ); } if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) { refreshUniformsCommon( m_uniforms, material ); } // refresh single material specific uniforms if ( material instanceof THREE.LineBasicMaterial ) { refreshUniformsLine( m_uniforms, material ); } else if ( material instanceof THREE.LineDashedMaterial ) { refreshUniformsLine( m_uniforms, material ); refreshUniformsDash( m_uniforms, material ); } else if ( material instanceof THREE.ParticleSystemMaterial ) { refreshUniformsParticle( m_uniforms, material ); } else if ( material instanceof THREE.MeshPhongMaterial ) { refreshUniformsPhong( m_uniforms, material ); } else if ( material instanceof THREE.MeshLambertMaterial ) { refreshUniformsLambert( m_uniforms, material ); } else if ( material instanceof THREE.MeshDepthMaterial ) { m_uniforms.mNear.value = camera.near; m_uniforms.mFar.value = camera.far; m_uniforms.opacity.value = material.opacity; } else if ( material instanceof THREE.MeshNormalMaterial ) { m_uniforms.opacity.value = material.opacity; } if ( object.receiveShadow && ! material._shadowPass ) { refreshUniformsShadow( m_uniforms, lights ); } // load common uniforms loadUniformsGeneric( program, material.uniformsList ); // load material specific uniforms // (shader material also gets them for the sake of genericity) if ( material instanceof THREE.ShaderMaterial || material instanceof THREE.MeshPhongMaterial || material.envMap ) { if ( p_uniforms.cameraPosition !== null ) { _vector3.setFromMatrixPosition( camera.matrixWorld ); _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z ); } } if ( material instanceof THREE.MeshPhongMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.ShaderMaterial || material.skinning ) { if ( p_uniforms.viewMatrix !== null ) { _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements ); } } } loadUniformsMatrices( p_uniforms, object ); if ( p_uniforms.modelMatrix !== null ) { _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements ); } return program; }; // Uniforms (refresh uniforms objects) function refreshUniformsCommon ( uniforms, material ) { uniforms.opacity.value = material.opacity; if ( _this.gammaInput ) { uniforms.diffuse.value.copyGammaToLinear( material.color ); } else { uniforms.diffuse.value = material.color; } uniforms.map.value = material.map; uniforms.lightMap.value = material.lightMap; uniforms.specularMap.value = material.specularMap; if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); } // uv repeat and offset setting priorities // 1. color map // 2. specular map // 3. normal map // 4. bump map var uvScaleMap; if ( material.map ) { uvScaleMap = material.map; } else if ( material.specularMap ) { uvScaleMap = material.specularMap; } else if ( material.normalMap ) { uvScaleMap = material.normalMap; } else if ( material.bumpMap ) { uvScaleMap = material.bumpMap; } if ( uvScaleMap !== undefined ) { var offset = uvScaleMap.offset; var repeat = uvScaleMap.repeat; uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); } uniforms.envMap.value = material.envMap; uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1; if ( _this.gammaInput ) { //uniforms.reflectivity.value = material.reflectivity * material.reflectivity; uniforms.reflectivity.value = material.reflectivity; } else { uniforms.reflectivity.value = material.reflectivity; } uniforms.refractionRatio.value = material.refractionRatio; uniforms.combine.value = material.combine; uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping; }; function refreshUniformsLine ( uniforms, material ) { uniforms.diffuse.value = material.color; uniforms.opacity.value = material.opacity; }; function refreshUniformsDash ( uniforms, material ) { uniforms.dashSize.value = material.dashSize; uniforms.totalSize.value = material.dashSize + material.gapSize; uniforms.scale.value = material.scale; }; function refreshUniformsParticle ( uniforms, material ) { uniforms.psColor.value = material.color; uniforms.opacity.value = material.opacity; uniforms.size.value = material.size; uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this. uniforms.map.value = material.map; }; function refreshUniformsFog ( uniforms, fog ) { uniforms.fogColor.value = fog.color; if ( fog instanceof THREE.Fog ) { uniforms.fogNear.value = fog.near; uniforms.fogFar.value = fog.far; } else if ( fog instanceof THREE.FogExp2 ) { uniforms.fogDensity.value = fog.density; } }; function refreshUniformsPhong ( uniforms, material ) { uniforms.shininess.value = material.shininess; if ( _this.gammaInput ) { uniforms.ambient.value.copyGammaToLinear( material.ambient ); uniforms.emissive.value.copyGammaToLinear( material.emissive ); uniforms.specular.value.copyGammaToLinear( material.specular ); } else { uniforms.ambient.value = material.ambient; uniforms.emissive.value = material.emissive; uniforms.specular.value = material.specular; } if ( material.wrapAround ) { uniforms.wrapRGB.value.copy( material.wrapRGB ); } }; function refreshUniformsLambert ( uniforms, material ) { if ( _this.gammaInput ) { uniforms.ambient.value.copyGammaToLinear( material.ambient ); uniforms.emissive.value.copyGammaToLinear( material.emissive ); } else { uniforms.ambient.value = material.ambient; uniforms.emissive.value = material.emissive; } if ( material.wrapAround ) { uniforms.wrapRGB.value.copy( material.wrapRGB ); } }; function refreshUniformsLights ( uniforms, lights ) { uniforms.ambientLightColor.value = lights.ambient; uniforms.directionalLightColor.value = lights.directional.colors; uniforms.directionalLightDirection.value = lights.directional.positions; uniforms.pointLightColor.value = lights.point.colors; uniforms.pointLightPosition.value = lights.point.positions; uniforms.pointLightDistance.value = lights.point.distances; uniforms.spotLightColor.value = lights.spot.colors; uniforms.spotLightPosition.value = lights.spot.positions; uniforms.spotLightDistance.value = lights.spot.distances; uniforms.spotLightDirection.value = lights.spot.directions; uniforms.spotLightAngleCos.value = lights.spot.anglesCos; uniforms.spotLightExponent.value = lights.spot.exponents; uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors; uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors; uniforms.hemisphereLightDirection.value = lights.hemi.positions; }; function refreshUniformsShadow ( uniforms, lights ) { if ( uniforms.shadowMatrix ) { var j = 0; for ( var i = 0, il = lights.length; i < il; i ++ ) { var light = lights[ i ]; if ( ! light.castShadow ) continue; if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) { uniforms.shadowMap.value[ j ] = light.shadowMap; uniforms.shadowMapSize.value[ j ] = light.shadowMapSize; uniforms.shadowMatrix.value[ j ] = light.shadowMatrix; uniforms.shadowDarkness.value[ j ] = light.shadowDarkness; uniforms.shadowBias.value[ j ] = light.shadowBias; j ++; } } } }; // Uniforms (load to GPU) function loadUniformsMatrices ( uniforms, object ) { _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements ); if ( uniforms.normalMatrix ) { _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements ); } }; function getTextureUnit() { var textureUnit = _usedTextureUnits; if ( textureUnit >= _maxTextures ) { console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures ); } _usedTextureUnits += 1; return textureUnit; }; function loadUniformsGeneric ( program, uniforms ) { var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset; for ( j = 0, jl = uniforms.length; j < jl; j ++ ) { location = program.uniforms[ uniforms[ j ][ 1 ] ]; if ( !location ) continue; uniform = uniforms[ j ][ 0 ]; type = uniform.type; value = uniform.value; if ( type === "i" ) { // single integer _gl.uniform1i( location, value ); } else if ( type === "f" ) { // single float _gl.uniform1f( location, value ); } else if ( type === "v2" ) { // single THREE.Vector2 _gl.uniform2f( location, value.x, value.y ); } else if ( type === "v3" ) { // single THREE.Vector3 _gl.uniform3f( location, value.x, value.y, value.z ); } else if ( type === "v4" ) { // single THREE.Vector4 _gl.uniform4f( location, value.x, value.y, value.z, value.w ); } else if ( type === "c" ) { // single THREE.Color _gl.uniform3f( location, value.r, value.g, value.b ); } else if ( type === "iv1" ) { // flat array of integers (JS or typed array) _gl.uniform1iv( location, value ); } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array) _gl.uniform3iv( location, value ); } else if ( type === "fv1" ) { // flat array of floats (JS or typed array) _gl.uniform1fv( location, value ); } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array) _gl.uniform3fv( location, value ); } else if ( type === "v2v" ) { // array of THREE.Vector2 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 2 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { offset = i * 2; uniform._array[ offset ] = value[ i ].x; uniform._array[ offset + 1 ] = value[ i ].y; } _gl.uniform2fv( location, uniform._array ); } else if ( type === "v3v" ) { // array of THREE.Vector3 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 3 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { offset = i * 3; uniform._array[ offset ] = value[ i ].x; uniform._array[ offset + 1 ] = value[ i ].y; uniform._array[ offset + 2 ] = value[ i ].z; } _gl.uniform3fv( location, uniform._array ); } else if ( type === "v4v" ) { // array of THREE.Vector4 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 4 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { offset = i * 4; uniform._array[ offset ] = value[ i ].x; uniform._array[ offset + 1 ] = value[ i ].y; uniform._array[ offset + 2 ] = value[ i ].z; uniform._array[ offset + 3 ] = value[ i ].w; } _gl.uniform4fv( location, uniform._array ); } else if ( type === "m4") { // single THREE.Matrix4 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 16 ); } value.flattenToArray( uniform._array ); _gl.uniformMatrix4fv( location, false, uniform._array ); } else if ( type === "m4v" ) { // array of THREE.Matrix4 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 16 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { value[ i ].flattenToArrayOffset( uniform._array, i * 16 ); } _gl.uniformMatrix4fv( location, false, uniform._array ); } else if ( type === "t" ) { // single THREE.Texture (2d or cube) texture = value; textureUnit = getTextureUnit(); _gl.uniform1i( location, textureUnit ); if ( !texture ) continue; if ( texture.image instanceof Array && texture.image.length === 6 ) { setCubeTexture( texture, textureUnit ); } else if ( texture instanceof THREE.WebGLRenderTargetCube ) { setCubeTextureDynamic( texture, textureUnit ); } else { _this.setTexture( texture, textureUnit ); } } else if ( type === "tv" ) { // array of THREE.Texture (2d) if ( uniform._array === undefined ) { uniform._array = []; } for( i = 0, il = uniform.value.length; i < il; i ++ ) { uniform._array[ i ] = getTextureUnit(); } _gl.uniform1iv( location, uniform._array ); for( i = 0, il = uniform.value.length; i < il; i ++ ) { texture = uniform.value[ i ]; textureUnit = uniform._array[ i ]; if ( !texture ) continue; _this.setTexture( texture, textureUnit ); } } else { console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type ); } } }; function setupMatrices ( object, camera ) { object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); object._normalMatrix.getNormalMatrix( object._modelViewMatrix ); }; // function setColorGamma( array, offset, color, intensitySq ) { array[ offset ] = color.r * color.r * intensitySq; array[ offset + 1 ] = color.g * color.g * intensitySq; array[ offset + 2 ] = color.b * color.b * intensitySq; }; function setColorLinear( array, offset, color, intensity ) { array[ offset ] = color.r * intensity; array[ offset + 1 ] = color.g * intensity; array[ offset + 2 ] = color.b * intensity; }; function setupLights ( program, lights ) { var l, ll, light, n, r = 0, g = 0, b = 0, color, skyColor, groundColor, intensity, intensitySq, position, distance, zlights = _lights, dirColors = zlights.directional.colors, dirPositions = zlights.directional.positions, pointColors = zlights.point.colors, pointPositions = zlights.point.positions, pointDistances = zlights.point.distances, spotColors = zlights.spot.colors, spotPositions = zlights.spot.positions, spotDistances = zlights.spot.distances, spotDirections = zlights.spot.directions, spotAnglesCos = zlights.spot.anglesCos, spotExponents = zlights.spot.exponents, hemiSkyColors = zlights.hemi.skyColors, hemiGroundColors = zlights.hemi.groundColors, hemiPositions = zlights.hemi.positions, dirLength = 0, pointLength = 0, spotLength = 0, hemiLength = 0, dirCount = 0, pointCount = 0, spotCount = 0, hemiCount = 0, dirOffset = 0, pointOffset = 0, spotOffset = 0, hemiOffset = 0; for ( l = 0, ll = lights.length; l < ll; l ++ ) { light = lights[ l ]; if ( light.onlyShadow ) continue; color = light.color; intensity = light.intensity; distance = light.distance; if ( light instanceof THREE.AmbientLight ) { if ( ! light.visible ) continue; if ( _this.gammaInput ) { r += color.r * color.r; g += color.g * color.g; b += color.b * color.b; } else { r += color.r; g += color.g; b += color.b; } } else if ( light instanceof THREE.DirectionalLight ) { dirCount += 1; if ( ! light.visible ) continue; _direction.setFromMatrixPosition( light.matrixWorld ); _vector3.setFromMatrixPosition( light.target.matrixWorld ); _direction.sub( _vector3 ); _direction.normalize(); // skip lights with undefined direction // these create troubles in OpenGL (making pixel black) if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue; dirOffset = dirLength * 3; dirPositions[ dirOffset ] = _direction.x; dirPositions[ dirOffset + 1 ] = _direction.y; dirPositions[ dirOffset + 2 ] = _direction.z; if ( _this.gammaInput ) { setColorGamma( dirColors, dirOffset, color, intensity * intensity ); } else { setColorLinear( dirColors, dirOffset, color, intensity ); } dirLength += 1; } else if ( light instanceof THREE.PointLight ) { pointCount += 1; if ( ! light.visible ) continue; pointOffset = pointLength * 3; if ( _this.gammaInput ) { setColorGamma( pointColors, pointOffset, color, intensity * intensity ); } else { setColorLinear( pointColors, pointOffset, color, intensity ); } _vector3.setFromMatrixPosition( light.matrixWorld ); pointPositions[ pointOffset ] = _vector3.x; pointPositions[ pointOffset + 1 ] = _vector3.y; pointPositions[ pointOffset + 2 ] = _vector3.z; pointDistances[ pointLength ] = distance; pointLength += 1; } else if ( light instanceof THREE.SpotLight ) { spotCount += 1; if ( ! light.visible ) continue; spotOffset = spotLength * 3; if ( _this.gammaInput ) { setColorGamma( spotColors, spotOffset, color, intensity * intensity ); } else { setColorLinear( spotColors, spotOffset, color, intensity ); } _vector3.setFromMatrixPosition( light.matrixWorld ); spotPositions[ spotOffset ] = _vector3.x; spotPositions[ spotOffset + 1 ] = _vector3.y; spotPositions[ spotOffset + 2 ] = _vector3.z; spotDistances[ spotLength ] = distance; _direction.copy( _vector3 ); _vector3.setFromMatrixPosition( light.target.matrixWorld ); _direction.sub( _vector3 ); _direction.normalize(); spotDirections[ spotOffset ] = _direction.x; spotDirections[ spotOffset + 1 ] = _direction.y; spotDirections[ spotOffset + 2 ] = _direction.z; spotAnglesCos[ spotLength ] = Math.cos( light.angle ); spotExponents[ spotLength ] = light.exponent; spotLength += 1; } else if ( light instanceof THREE.HemisphereLight ) { hemiCount += 1; if ( ! light.visible ) continue; _direction.setFromMatrixPosition( light.matrixWorld ); _direction.normalize(); // skip lights with undefined direction // these create troubles in OpenGL (making pixel black) if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue; hemiOffset = hemiLength * 3; hemiPositions[ hemiOffset ] = _direction.x; hemiPositions[ hemiOffset + 1 ] = _direction.y; hemiPositions[ hemiOffset + 2 ] = _direction.z; skyColor = light.color; groundColor = light.groundColor; if ( _this.gammaInput ) { intensitySq = intensity * intensity; setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq ); setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq ); } else { setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity ); setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity ); } hemiLength += 1; } } // null eventual remains from removed lights // (this is to avoid if in shader) for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0; for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0; for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0; for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0; for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0; zlights.directional.length = dirLength; zlights.point.length = pointLength; zlights.spot.length = spotLength; zlights.hemi.length = hemiLength; zlights.ambient[ 0 ] = r; zlights.ambient[ 1 ] = g; zlights.ambient[ 2 ] = b; }; // GL state setting this.setFaceCulling = function ( cullFace, frontFaceDirection ) { if ( cullFace === THREE.CullFaceNone ) { _gl.disable( _gl.CULL_FACE ); } else { if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) { _gl.frontFace( _gl.CW ); } else { _gl.frontFace( _gl.CCW ); } if ( cullFace === THREE.CullFaceBack ) { _gl.cullFace( _gl.BACK ); } else if ( cullFace === THREE.CullFaceFront ) { _gl.cullFace( _gl.FRONT ); } else { _gl.cullFace( _gl.FRONT_AND_BACK ); } _gl.enable( _gl.CULL_FACE ); } }; this.setMaterialFaces = function ( material ) { var doubleSided = material.side === THREE.DoubleSide; var flipSided = material.side === THREE.BackSide; if ( _oldDoubleSided !== doubleSided ) { if ( doubleSided ) { _gl.disable( _gl.CULL_FACE ); } else { _gl.enable( _gl.CULL_FACE ); } _oldDoubleSided = doubleSided; } if ( _oldFlipSided !== flipSided ) { if ( flipSided ) { _gl.frontFace( _gl.CW ); } else { _gl.frontFace( _gl.CCW ); } _oldFlipSided = flipSided; } }; this.setDepthTest = function ( depthTest ) { if ( _oldDepthTest !== depthTest ) { if ( depthTest ) { _gl.enable( _gl.DEPTH_TEST ); } else { _gl.disable( _gl.DEPTH_TEST ); } _oldDepthTest = depthTest; } }; this.setDepthWrite = function ( depthWrite ) { if ( _oldDepthWrite !== depthWrite ) { _gl.depthMask( depthWrite ); _oldDepthWrite = depthWrite; } }; function setLineWidth ( width ) { if ( width !== _oldLineWidth ) { _gl.lineWidth( width ); _oldLineWidth = width; } }; function setPolygonOffset ( polygonoffset, factor, units ) { if ( _oldPolygonOffset !== polygonoffset ) { if ( polygonoffset ) { _gl.enable( _gl.POLYGON_OFFSET_FILL ); } else { _gl.disable( _gl.POLYGON_OFFSET_FILL ); } _oldPolygonOffset = polygonoffset; } if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) { _gl.polygonOffset( factor, units ); _oldPolygonOffsetFactor = factor; _oldPolygonOffsetUnits = units; } }; this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) { if ( blending !== _oldBlending ) { if ( blending === THREE.NoBlending ) { _gl.disable( _gl.BLEND ); } else if ( blending === THREE.AdditiveBlending ) { _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); } else if ( blending === THREE.SubtractiveBlending ) { // TODO: Find blendFuncSeparate() combination _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR ); } else if ( blending === THREE.MultiplyBlending ) { // TODO: Find blendFuncSeparate() combination _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR ); } else if ( blending === THREE.CustomBlending ) { _gl.enable( _gl.BLEND ); } else { _gl.enable( _gl.BLEND ); _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD ); _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA ); } _oldBlending = blending; } if ( blending === THREE.CustomBlending ) { if ( blendEquation !== _oldBlendEquation ) { _gl.blendEquation( paramThreeToGL( blendEquation ) ); _oldBlendEquation = blendEquation; } if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) { _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) ); _oldBlendSrc = blendSrc; _oldBlendDst = blendDst; } } else { _oldBlendEquation = null; _oldBlendSrc = null; _oldBlendDst = null; } }; // Defines function generateDefines ( defines ) { var value, chunk, chunks = []; for ( var d in defines ) { value = defines[ d ]; if ( value === false ) continue; chunk = "#define " + d + " " + value; chunks.push( chunk ); } return chunks.join( "\n" ); }; // Shaders function buildProgram( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) { var p, pl, d, program, code; var chunks = []; // Generate code if ( shaderID ) { chunks.push( shaderID ); } else { chunks.push( fragmentShader ); chunks.push( vertexShader ); } for ( d in defines ) { chunks.push( d ); chunks.push( defines[ d ] ); } for ( p in parameters ) { chunks.push( p ); chunks.push( parameters[ p ] ); } code = chunks.join(); // Check if code has been already compiled for ( p = 0, pl = _programs.length; p < pl; p ++ ) { var programInfo = _programs[ p ]; if ( programInfo.code === code ) { // console.log( "Code already compiled." /*: \n\n" + code*/ ); programInfo.usedTimes ++; return programInfo.program; } } var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; if ( parameters.shadowMapType === THREE.PCFShadowMap ) { shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; } // console.log( "building new program " ); // var customDefines = generateDefines( defines ); // program = _gl.createProgram(); var prefix_vertex = [ "precision " + _precision + " float;", "precision " + _precision + " int;", customDefines, _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "", _this.gammaInput ? "#define GAMMA_INPUT" : "", _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, "#define MAX_SHADOWS " + parameters.maxShadows, "#define MAX_BONES " + parameters.maxBones, parameters.map ? "#define USE_MAP" : "", parameters.envMap ? "#define USE_ENVMAP" : "", parameters.lightMap ? "#define USE_LIGHTMAP" : "", parameters.bumpMap ? "#define USE_BUMPMAP" : "", parameters.normalMap ? "#define USE_NORMALMAP" : "", parameters.specularMap ? "#define USE_SPECULARMAP" : "", parameters.vertexColors ? "#define USE_COLOR" : "", parameters.skinning ? "#define USE_SKINNING" : "", parameters.useVertexTexture ? "#define BONE_TEXTURE" : "", parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", parameters.morphNormals ? "#define USE_MORPHNORMALS" : "", parameters.wrapAround ? "#define WRAP_AROUND" : "", parameters.doubleSided ? "#define DOUBLE_SIDED" : "", parameters.flipSided ? "#define FLIP_SIDED" : "", parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", "uniform mat4 modelMatrix;", "uniform mat4 modelViewMatrix;", "uniform mat4 projectionMatrix;", "uniform mat4 viewMatrix;", "uniform mat3 normalMatrix;", "uniform vec3 cameraPosition;", "attribute vec3 position;", "attribute vec3 normal;", "attribute vec2 uv;", "attribute vec2 uv2;", "#ifdef USE_COLOR", "attribute vec3 color;", "#endif", "#ifdef USE_MORPHTARGETS", "attribute vec3 morphTarget0;", "attribute vec3 morphTarget1;", "attribute vec3 morphTarget2;", "attribute vec3 morphTarget3;", "#ifdef USE_MORPHNORMALS", "attribute vec3 morphNormal0;", "attribute vec3 morphNormal1;", "attribute vec3 morphNormal2;", "attribute vec3 morphNormal3;", "#else", "attribute vec3 morphTarget4;", "attribute vec3 morphTarget5;", "attribute vec3 morphTarget6;", "attribute vec3 morphTarget7;", "#endif", "#endif", "#ifdef USE_SKINNING", "attribute vec4 skinIndex;", "attribute vec4 skinWeight;", "#endif", "" ].join("\n"); var prefix_fragment = [ "precision " + _precision + " float;", "precision " + _precision + " int;", ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "", customDefines, "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, "#define MAX_SHADOWS " + parameters.maxShadows, parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "", _this.gammaInput ? "#define GAMMA_INPUT" : "", _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "", ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "", parameters.map ? "#define USE_MAP" : "", parameters.envMap ? "#define USE_ENVMAP" : "", parameters.lightMap ? "#define USE_LIGHTMAP" : "", parameters.bumpMap ? "#define USE_BUMPMAP" : "", parameters.normalMap ? "#define USE_NORMALMAP" : "", parameters.specularMap ? "#define USE_SPECULARMAP" : "", parameters.vertexColors ? "#define USE_COLOR" : "", parameters.metal ? "#define METAL" : "", parameters.wrapAround ? "#define WRAP_AROUND" : "", parameters.doubleSided ? "#define DOUBLE_SIDED" : "", parameters.flipSided ? "#define FLIP_SIDED" : "", parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", "uniform mat4 viewMatrix;", "uniform vec3 cameraPosition;", "" ].join("\n"); var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader ); var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader ); _gl.attachShader( program, glVertexShader ); _gl.attachShader( program, glFragmentShader ); // Force a particular attribute to index 0. // because potentially expensive emulation is done by browser if attribute 0 is disabled. // And, color, for example is often automatically bound to index 0 so disabling it if ( index0AttributeName !== undefined ) { _gl.bindAttribLocation( program, 0, index0AttributeName ); } _gl.linkProgram( program ); if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) { console.error( 'Could not initialise shader' ); console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) ); console.error( 'gl.getError()', _gl.getError() ); } if ( _gl.getProgramInfoLog( program ) !== '' ) { console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) ); } // clean up _gl.deleteShader( glFragmentShader ); _gl.deleteShader( glVertexShader ); // console.log( prefix_fragment + fragmentShader ); // console.log( prefix_vertex + vertexShader ); program.uniforms = {}; program.attributes = {}; var identifiers, u, a, i; // cache uniform locations identifiers = [ 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition', 'morphTargetInfluences' ]; if ( parameters.useVertexTexture ) { identifiers.push( 'boneTexture' ); identifiers.push( 'boneTextureWidth' ); identifiers.push( 'boneTextureHeight' ); } else { identifiers.push( 'boneGlobalMatrices' ); } for ( u in uniforms ) { identifiers.push( u ); } cacheUniformLocations( program, identifiers ); // cache attributes locations identifiers = [ "position", "normal", "uv", "uv2", "tangent", "color", "skinIndex", "skinWeight", "lineDistance" ]; for ( i = 0; i < parameters.maxMorphTargets; i ++ ) { identifiers.push( "morphTarget" + i ); } for ( i = 0; i < parameters.maxMorphNormals; i ++ ) { identifiers.push( "morphNormal" + i ); } for ( a in attributes ) { identifiers.push( a ); } cacheAttributeLocations( program, identifiers ); program.id = _programs_counter ++; _programs.push( { program: program, code: code, usedTimes: 1 } ); _this.info.memory.programs = _programs.length; return program; }; // Shader parameters cache function cacheUniformLocations ( program, identifiers ) { var i, l, id; for( i = 0, l = identifiers.length; i < l; i ++ ) { id = identifiers[ i ]; program.uniforms[ id ] = _gl.getUniformLocation( program, id ); } }; function cacheAttributeLocations ( program, identifiers ) { var i, l, id; for( i = 0, l = identifiers.length; i < l; i ++ ) { id = identifiers[ i ]; program.attributes[ id ] = _gl.getAttribLocation( program, id ); } }; function addLineNumbers ( string ) { var chunks = string.split( "\n" ); for ( var i = 0, il = chunks.length; i < il; i ++ ) { // Chrome reports shader errors on lines // starting counting from 1 chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ]; } return chunks.join( "\n" ); }; function getShader ( type, string ) { var shader; if ( type === "fragment" ) { shader = _gl.createShader( _gl.FRAGMENT_SHADER ); } else if ( type === "vertex" ) { shader = _gl.createShader( _gl.VERTEX_SHADER ); } _gl.shaderSource( shader, string ); _gl.compileShader( shader ); if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) { console.error( _gl.getShaderInfoLog( shader ) ); console.error( addLineNumbers( string ) ); return null; } return shader; }; // Textures function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) { if ( isImagePowerOfTwo ) { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); } else { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); } if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) { if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) { _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) ); texture.__oldAnisotropy = texture.anisotropy; } } }; this.setTexture = function ( texture, slot ) { if ( texture.needsUpdate ) { if ( ! texture.__webglInit ) { texture.__webglInit = true; texture.addEventListener( 'dispose', onTextureDispose ); texture.__webglTexture = _gl.createTexture(); _this.info.memory.textures ++; } _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); var image = texture.image, isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), glFormat = paramThreeToGL( texture.format ), glType = paramThreeToGL( texture.type ); setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); var mipmap, mipmaps = texture.mipmaps; if ( texture instanceof THREE.DataTexture ) { // use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if ( mipmaps.length > 0 && isImagePowerOfTwo ) { for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } texture.generateMipmaps = false; } else { _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); } } else if ( texture instanceof THREE.CompressedTexture ) { for( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; if ( texture.format!==THREE.RGBAFormat ) { _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); } else { _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } } } else { // regular Texture (image, video, canvas) // use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if ( mipmaps.length > 0 && isImagePowerOfTwo ) { for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); } texture.generateMipmaps = false; } else { _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image ); } } if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); texture.needsUpdate = false; if ( texture.onUpdate ) texture.onUpdate(); } else { _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); } }; function clampToMaxSize ( image, maxSize ) { if ( image.width <= maxSize && image.height <= maxSize ) { return image; } // Warning: Scaling through the canvas will only work with images that use // premultiplied alpha. var maxDimension = Math.max( image.width, image.height ); var newWidth = Math.floor( image.width * maxSize / maxDimension ); var newHeight = Math.floor( image.height * maxSize / maxDimension ); var canvas = document.createElement( 'canvas' ); canvas.width = newWidth; canvas.height = newHeight; var ctx = canvas.getContext( "2d" ); ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight ); return canvas; } function setCubeTexture ( texture, slot ) { if ( texture.image.length === 6 ) { if ( texture.needsUpdate ) { if ( ! texture.image.__webglTextureCube ) { texture.addEventListener( 'dispose', onTextureDispose ); texture.image.__webglTextureCube = _gl.createTexture(); _this.info.memory.textures ++; } _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); var isCompressed = texture instanceof THREE.CompressedTexture; var cubeImage = []; for ( var i = 0; i < 6; i ++ ) { if ( _this.autoScaleCubemaps && ! isCompressed ) { cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize ); } else { cubeImage[ i ] = texture.image[ i ]; } } var image = cubeImage[ 0 ], isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), glFormat = paramThreeToGL( texture.format ), glType = paramThreeToGL( texture.type ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo ); for ( var i = 0; i < 6; i ++ ) { if( !isCompressed ) { _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); } else { var mipmap, mipmaps = cubeImage[ i ].mipmaps; for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { mipmap = mipmaps[ j ]; if ( texture.format!==THREE.RGBAFormat ) { _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); } else { _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } } } } if ( texture.generateMipmaps && isImagePowerOfTwo ) { _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); } texture.needsUpdate = false; if ( texture.onUpdate ) texture.onUpdate(); } else { _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); } } }; function setCubeTextureDynamic ( texture, slot ) { _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture ); }; // Render targets function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 ); }; function setupRenderBuffer ( renderbuffer, renderTarget ) { _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); /* For some reason this is not working. Defaulting to RGBA4. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); */ } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); } else { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); } }; this.setRenderTarget = function ( renderTarget ) { var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); if ( renderTarget && ! renderTarget.__webglFramebuffer ) { if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true; if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true; renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); renderTarget.__webglTexture = _gl.createTexture(); _this.info.memory.textures ++; // Setup texture, create render and frame buffers var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ), glFormat = paramThreeToGL( renderTarget.format ), glType = paramThreeToGL( renderTarget.type ); if ( isCube ) { renderTarget.__webglFramebuffer = []; renderTarget.__webglRenderbuffer = []; _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo ); for ( var i = 0; i < 6; i ++ ) { renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer(); renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer(); _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget ); } if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); } else { renderTarget.__webglFramebuffer = _gl.createFramebuffer(); if ( renderTarget.shareDepthFrom ) { renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer; } else { renderTarget.__webglRenderbuffer = _gl.createRenderbuffer(); } _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo ); _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D ); if ( renderTarget.shareDepthFrom ) { if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); } } else { setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget ); } if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); } // Release everything if ( isCube ) { _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); } else { _gl.bindTexture( _gl.TEXTURE_2D, null ); } _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); } var framebuffer, width, height, vx, vy; if ( renderTarget ) { if ( isCube ) { framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ]; } else { framebuffer = renderTarget.__webglFramebuffer; } width = renderTarget.width; height = renderTarget.height; vx = 0; vy = 0; } else { framebuffer = null; width = _viewportWidth; height = _viewportHeight; vx = _viewportX; vy = _viewportY; } if ( framebuffer !== _currentFramebuffer ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); _gl.viewport( vx, vy, width, height ); _currentFramebuffer = framebuffer; } _currentWidth = width; _currentHeight = height; }; function updateRenderTargetMipmap ( renderTarget ) { if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); } else { _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); _gl.generateMipmap( _gl.TEXTURE_2D ); _gl.bindTexture( _gl.TEXTURE_2D, null ); } }; // Fallback filters for non-power-of-2 textures function filterFallback ( f ) { if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { return _gl.NEAREST; } return _gl.LINEAR; }; // Map three.js constants to WebGL constants function paramThreeToGL ( p ) { if ( p === THREE.RepeatWrapping ) return _gl.REPEAT; if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; if ( p === THREE.NearestFilter ) return _gl.NEAREST; if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; if ( p === THREE.LinearFilter ) return _gl.LINEAR; if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; if ( p === THREE.ByteType ) return _gl.BYTE; if ( p === THREE.ShortType ) return _gl.SHORT; if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; if ( p === THREE.IntType ) return _gl.INT; if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; if ( p === THREE.FloatType ) return _gl.FLOAT; if ( p === THREE.AlphaFormat ) return _gl.ALPHA; if ( p === THREE.RGBFormat ) return _gl.RGB; if ( p === THREE.RGBAFormat ) return _gl.RGBA; if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; if ( p === THREE.ZeroFactor ) return _gl.ZERO; if ( p === THREE.OneFactor ) return _gl.ONE; if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; if ( _glExtensionCompressedTextureS3TC !== undefined ) { if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT; if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT; if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT; if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT; } return 0; }; // Allocations function allocateBones ( object ) { if ( _supportsBoneTextures && object && object.useVertexTexture ) { return 1024; } else { // default for when object is not specified // ( for example when prebuilding shader // to be used with multiple objects ) // // - leave some extra space for other uniforms // - limit here is ANGLE's 254 max uniform vectors // (up to 54 should be safe) var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ); var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); var maxBones = nVertexMatrices; if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { maxBones = Math.min( object.bones.length, maxBones ); if ( maxBones < object.bones.length ) { console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" ); } } return maxBones; } }; function allocateLights( lights ) { var dirLights = 0; var pointLights = 0; var spotLights = 0; var hemiLights = 0; for ( var l = 0, ll = lights.length; l < ll; l ++ ) { var light = lights[ l ]; if ( light.onlyShadow || light.visible === false ) continue; if ( light instanceof THREE.DirectionalLight ) dirLights ++; if ( light instanceof THREE.PointLight ) pointLights ++; if ( light instanceof THREE.SpotLight ) spotLights ++; if ( light instanceof THREE.HemisphereLight ) hemiLights ++; } return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights }; }; function allocateShadows( lights ) { var maxShadows = 0; for ( var l = 0, ll = lights.length; l < ll; l++ ) { var light = lights[ l ]; if ( ! light.castShadow ) continue; if ( light instanceof THREE.SpotLight ) maxShadows ++; if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++; } return maxShadows; }; // Initialization function initGL() { try { var attributes = { alpha: _alpha, depth: _depth, stencil: _stencil, antialias: _antialias, premultipliedAlpha: _premultipliedAlpha, preserveDrawingBuffer: _preserveDrawingBuffer }; _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); if ( _gl === null ) { throw 'Error creating WebGL context.'; } } catch ( error ) { console.error( error ); } _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' ); _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' ); _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' ); _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' ); if ( _glExtensionTextureFloat === null ) { console.log( 'THREE.WebGLRenderer: Float textures not supported.' ); } if ( _glExtensionStandardDerivatives === null ) { console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' ); } if ( _glExtensionTextureFilterAnisotropic === null ) { console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' ); } if ( _glExtensionCompressedTextureS3TC === null ) { console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' ); } if ( _glExtensionElementIndexUint === null ) { console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' ); } if ( _gl.getShaderPrecisionFormat === undefined ) { _gl.getShaderPrecisionFormat = function() { return { "rangeMin" : 1, "rangeMax" : 1, "precision" : 1 }; } } }; function setDefaultGLState () { _gl.clearColor( 0, 0, 0, 1 ); _gl.clearDepth( 1 ); _gl.clearStencil( 0 ); _gl.enable( _gl.DEPTH_TEST ); _gl.depthFunc( _gl.LEQUAL ); _gl.frontFace( _gl.CCW ); _gl.cullFace( _gl.BACK ); _gl.enable( _gl.CULL_FACE ); _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA ); _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); }; // default plugins (order is important) this.shadowMapPlugin = new THREE.ShadowMapPlugin(); this.addPrePlugin( this.shadowMapPlugin ); this.addPostPlugin( new THREE.SpritePlugin() ); this.addPostPlugin( new THREE.LensFlarePlugin() ); };
src/renderers/WebGLRenderer.js
/** * @author supereggbert / http://www.paulbrunt.co.uk/ * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author szimek / https://github.com/szimek/ */ THREE.WebGLRenderer = function ( parameters ) { console.log( 'THREE.WebGLRenderer', THREE.REVISION ); parameters = parameters || {}; var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ), _context = parameters.context !== undefined ? parameters.context : null, _precision = parameters.precision !== undefined ? parameters.precision : 'highp', _buffers = {}, _alpha = parameters.alpha !== undefined ? parameters.alpha : false, _depth = parameters.depth !== undefined ? parameters.depth : true, _stencil = parameters.stencil !== undefined ? parameters.stencil : true, _antialias = parameters.antialias !== undefined ? parameters.antialias : false, _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, _clearColor = new THREE.Color( 0x000000 ), _clearAlpha = 0; // public properties this.domElement = _canvas; this.context = null; this.devicePixelRatio = parameters.devicePixelRatio !== undefined ? parameters.devicePixelRatio : self.devicePixelRatio !== undefined ? self.devicePixelRatio : 1; // clearing this.autoClear = true; this.autoClearColor = true; this.autoClearDepth = true; this.autoClearStencil = true; // scene graph this.sortObjects = true; this.autoUpdateObjects = true; // physically based shading this.gammaInput = false; this.gammaOutput = false; // shadow map this.shadowMapEnabled = false; this.shadowMapAutoUpdate = true; this.shadowMapType = THREE.PCFShadowMap; this.shadowMapCullFace = THREE.CullFaceFront; this.shadowMapDebug = false; this.shadowMapCascade = false; // morphs this.maxMorphTargets = 8; this.maxMorphNormals = 4; // flags this.autoScaleCubemaps = true; // custom render plugins this.renderPluginsPre = []; this.renderPluginsPost = []; // info this.info = { memory: { programs: 0, geometries: 0, textures: 0 }, render: { calls: 0, vertices: 0, faces: 0, points: 0 } }; // internal properties var _this = this, _programs = [], _programs_counter = 0, // internal state cache _currentProgram = null, _currentFramebuffer = null, _currentMaterialId = -1, _currentGeometryGroupHash = null, _currentCamera = null, _usedTextureUnits = 0, // GL state cache _oldDoubleSided = -1, _oldFlipSided = -1, _oldBlending = -1, _oldBlendEquation = -1, _oldBlendSrc = -1, _oldBlendDst = -1, _oldDepthTest = -1, _oldDepthWrite = -1, _oldPolygonOffset = null, _oldPolygonOffsetFactor = null, _oldPolygonOffsetUnits = null, _oldLineWidth = null, _viewportX = 0, _viewportY = 0, _viewportWidth = _canvas.width, _viewportHeight = _canvas.height, _currentWidth = 0, _currentHeight = 0, _enabledAttributes = new Uint8Array( 16 ), // frustum _frustum = new THREE.Frustum(), // camera matrices cache _projScreenMatrix = new THREE.Matrix4(), _projScreenMatrixPS = new THREE.Matrix4(), _vector3 = new THREE.Vector3(), // light arrays cache _direction = new THREE.Vector3(), _lightsNeedUpdate = true, _lights = { ambient: [ 0, 0, 0 ], directional: { length: 0, colors: new Array(), positions: new Array() }, point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() }, spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() }, hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() } }; // initialize var _gl; var _glExtensionTextureFloat; var _glExtensionTextureFloatLinear; var _glExtensionStandardDerivatives; var _glExtensionTextureFilterAnisotropic; var _glExtensionCompressedTextureS3TC; var _glExtensionElementIndexUint; initGL(); setDefaultGLState(); this.context = _gl; // GPU capabilities var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ); var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ); var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ); var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE ); var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0; var _supportsVertexTextures = ( _maxVertexTextures > 0 ); var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat; var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : []; // var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT ); var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT ); var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT ); var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT ); var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT ); var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT ); var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT ); var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT ); var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT ); var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT ); var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT ); var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT ); // clamp precision to maximum available var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0; var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0; if ( _precision === "highp" && ! highpAvailable ) { if ( mediumpAvailable ) { _precision = "mediump"; console.warn( "WebGLRenderer: highp not supported, using mediump" ); } else { _precision = "lowp"; console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" ); } } if ( _precision === "mediump" && ! mediumpAvailable ) { _precision = "lowp"; console.warn( "WebGLRenderer: mediump not supported, using lowp" ); } // API this.getContext = function () { return _gl; }; this.supportsVertexTextures = function () { return _supportsVertexTextures; }; this.supportsFloatTextures = function () { return _glExtensionTextureFloat; }; this.supportsStandardDerivatives = function () { return _glExtensionStandardDerivatives; }; this.supportsCompressedTextureS3TC = function () { return _glExtensionCompressedTextureS3TC; }; this.getMaxAnisotropy = function () { return _maxAnisotropy; }; this.getPrecision = function () { return _precision; }; this.setSize = function ( width, height, updateStyle ) { _canvas.width = width * this.devicePixelRatio; _canvas.height = height * this.devicePixelRatio; if ( this.devicePixelRatio !== 1 && updateStyle !== false ) { _canvas.style.width = width + 'px'; _canvas.style.height = height + 'px'; } this.setViewport( 0, 0, width, height ); }; this.setViewport = function ( x, y, width, height ) { _viewportX = x * this.devicePixelRatio; _viewportY = y * this.devicePixelRatio; _viewportWidth = width * this.devicePixelRatio; _viewportHeight = height * this.devicePixelRatio; _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); }; this.setScissor = function ( x, y, width, height ) { _gl.scissor( x * this.devicePixelRatio, y * this.devicePixelRatio, width * this.devicePixelRatio, height * this.devicePixelRatio ); }; this.enableScissorTest = function ( enable ) { enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST ); }; // Clearing this.setClearColor = function ( color, alpha ) { _clearColor.set( color ); _clearAlpha = alpha !== undefined ? alpha : 1; _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); }; this.setClearColorHex = function ( hex, alpha ) { console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' ); this.setClearColor( hex, alpha ); }; this.getClearColor = function () { return _clearColor; }; this.getClearAlpha = function () { return _clearAlpha; }; this.clear = function ( color, depth, stencil ) { var bits = 0; if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT; if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT; if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT; _gl.clear( bits ); }; this.clearColor = function () { _gl.clear( _gl.COLOR_BUFFER_BIT ); }; this.clearDepth = function () { _gl.clear( _gl.DEPTH_BUFFER_BIT ); }; this.clearStencil = function () { _gl.clear( _gl.STENCIL_BUFFER_BIT ); }; this.clearTarget = function ( renderTarget, color, depth, stencil ) { this.setRenderTarget( renderTarget ); this.clear( color, depth, stencil ); }; // Plugins this.addPostPlugin = function ( plugin ) { plugin.init( this ); this.renderPluginsPost.push( plugin ); }; this.addPrePlugin = function ( plugin ) { plugin.init( this ); this.renderPluginsPre.push( plugin ); }; // Rendering this.updateShadowMap = function ( scene, camera ) { _currentProgram = null; _oldBlending = -1; _oldDepthTest = -1; _oldDepthWrite = -1; _currentGeometryGroupHash = -1; _currentMaterialId = -1; _lightsNeedUpdate = true; _oldDoubleSided = -1; _oldFlipSided = -1; this.shadowMapPlugin.update( scene, camera ); }; // Internal functions // Buffer allocation function createParticleBuffers ( geometry ) { geometry.__webglVertexBuffer = _gl.createBuffer(); geometry.__webglColorBuffer = _gl.createBuffer(); _this.info.memory.geometries ++; }; function createLineBuffers ( geometry ) { geometry.__webglVertexBuffer = _gl.createBuffer(); geometry.__webglColorBuffer = _gl.createBuffer(); geometry.__webglLineDistanceBuffer = _gl.createBuffer(); _this.info.memory.geometries ++; }; function createMeshBuffers ( geometryGroup ) { geometryGroup.__webglVertexBuffer = _gl.createBuffer(); geometryGroup.__webglNormalBuffer = _gl.createBuffer(); geometryGroup.__webglTangentBuffer = _gl.createBuffer(); geometryGroup.__webglColorBuffer = _gl.createBuffer(); geometryGroup.__webglUVBuffer = _gl.createBuffer(); geometryGroup.__webglUV2Buffer = _gl.createBuffer(); geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer(); geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer(); geometryGroup.__webglFaceBuffer = _gl.createBuffer(); geometryGroup.__webglLineBuffer = _gl.createBuffer(); var m, ml; if ( geometryGroup.numMorphTargets ) { geometryGroup.__webglMorphTargetsBuffers = []; for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() ); } } if ( geometryGroup.numMorphNormals ) { geometryGroup.__webglMorphNormalsBuffers = []; for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() ); } } _this.info.memory.geometries ++; }; // Events var onGeometryDispose = function ( event ) { var geometry = event.target; geometry.removeEventListener( 'dispose', onGeometryDispose ); deallocateGeometry( geometry ); }; var onTextureDispose = function ( event ) { var texture = event.target; texture.removeEventListener( 'dispose', onTextureDispose ); deallocateTexture( texture ); _this.info.memory.textures --; }; var onRenderTargetDispose = function ( event ) { var renderTarget = event.target; renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); deallocateRenderTarget( renderTarget ); _this.info.memory.textures --; }; var onMaterialDispose = function ( event ) { var material = event.target; material.removeEventListener( 'dispose', onMaterialDispose ); deallocateMaterial( material ); }; // Buffer deallocation var deleteBuffers = function ( geometry ) { if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer ); if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer ); if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer ); if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer ); if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer ); if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer ); if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer ); if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer ); if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer ); if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer ); if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer ); // custom attributes if ( geometry.__webglCustomAttributesList !== undefined ) { for ( var id in geometry.__webglCustomAttributesList ) { _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer ); } } _this.info.memory.geometries --; }; var deallocateGeometry = function ( geometry ) { geometry.__webglInit = undefined; if ( geometry instanceof THREE.BufferGeometry ) { var attributes = geometry.attributes; for ( var key in attributes ) { if ( attributes[ key ].buffer !== undefined ) { _gl.deleteBuffer( attributes[ key ].buffer ); } } _this.info.memory.geometries --; } else { if ( geometry.geometryGroups !== undefined ) { for ( var g in geometry.geometryGroups ) { var geometryGroup = geometry.geometryGroups[ g ]; if ( geometryGroup.numMorphTargets !== undefined ) { for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] ); } } if ( geometryGroup.numMorphNormals !== undefined ) { for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] ); } } deleteBuffers( geometryGroup ); } } else { deleteBuffers( geometry ); } } }; var deallocateTexture = function ( texture ) { if ( texture.image && texture.image.__webglTextureCube ) { // cube texture _gl.deleteTexture( texture.image.__webglTextureCube ); } else { // 2D texture if ( ! texture.__webglInit ) return; texture.__webglInit = false; _gl.deleteTexture( texture.__webglTexture ); } }; var deallocateRenderTarget = function ( renderTarget ) { if ( !renderTarget || ! renderTarget.__webglTexture ) return; _gl.deleteTexture( renderTarget.__webglTexture ); if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { for ( var i = 0; i < 6; i ++ ) { _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] ); _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] ); } } else { _gl.deleteFramebuffer( renderTarget.__webglFramebuffer ); _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer ); } }; var deallocateMaterial = function ( material ) { var program = material.program; if ( program === undefined ) return; material.program = undefined; // only deallocate GL program if this was the last use of shared program // assumed there is only single copy of any program in the _programs list // (that's how it's constructed) var i, il, programInfo; var deleteProgram = false; for ( i = 0, il = _programs.length; i < il; i ++ ) { programInfo = _programs[ i ]; if ( programInfo.program === program ) { programInfo.usedTimes --; if ( programInfo.usedTimes === 0 ) { deleteProgram = true; } break; } } if ( deleteProgram === true ) { // avoid using array.splice, this is costlier than creating new array from scratch var newPrograms = []; for ( i = 0, il = _programs.length; i < il; i ++ ) { programInfo = _programs[ i ]; if ( programInfo.program !== program ) { newPrograms.push( programInfo ); } } _programs = newPrograms; _gl.deleteProgram( program ); _this.info.memory.programs --; } }; // Buffer initialization function initCustomAttributes ( geometry, object ) { var nvertices = geometry.vertices.length; var material = object.material; if ( material.attributes ) { if ( geometry.__webglCustomAttributesList === undefined ) { geometry.__webglCustomAttributesList = []; } for ( var a in material.attributes ) { var attribute = material.attributes[ a ]; if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { attribute.__webglInitialized = true; var size = 1; // "f" and "i" if ( attribute.type === "v2" ) size = 2; else if ( attribute.type === "v3" ) size = 3; else if ( attribute.type === "v4" ) size = 4; else if ( attribute.type === "c" ) size = 3; attribute.size = size; attribute.array = new Float32Array( nvertices * size ); attribute.buffer = _gl.createBuffer(); attribute.buffer.belongsToAttribute = a; attribute.needsUpdate = true; } geometry.__webglCustomAttributesList.push( attribute ); } } }; function initParticleBuffers ( geometry, object ) { var nvertices = geometry.vertices.length; geometry.__vertexArray = new Float32Array( nvertices * 3 ); geometry.__colorArray = new Float32Array( nvertices * 3 ); geometry.__sortArray = []; geometry.__webglParticleCount = nvertices; initCustomAttributes ( geometry, object ); }; function initLineBuffers ( geometry, object ) { var nvertices = geometry.vertices.length; geometry.__vertexArray = new Float32Array( nvertices * 3 ); geometry.__colorArray = new Float32Array( nvertices * 3 ); geometry.__lineDistanceArray = new Float32Array( nvertices * 1 ); geometry.__webglLineCount = nvertices; initCustomAttributes ( geometry, object ); }; function initMeshBuffers ( geometryGroup, object ) { var geometry = object.geometry, faces3 = geometryGroup.faces3, nvertices = faces3.length * 3, ntris = faces3.length * 1, nlines = faces3.length * 3, material = getBufferMaterial( object, geometryGroup ), uvType = bufferGuessUVType( material ), normalType = bufferGuessNormalType( material ), vertexColorType = bufferGuessVertexColorType( material ); // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material ); geometryGroup.__vertexArray = new Float32Array( nvertices * 3 ); if ( normalType ) { geometryGroup.__normalArray = new Float32Array( nvertices * 3 ); } if ( geometry.hasTangents ) { geometryGroup.__tangentArray = new Float32Array( nvertices * 4 ); } if ( vertexColorType ) { geometryGroup.__colorArray = new Float32Array( nvertices * 3 ); } if ( uvType ) { if ( geometry.faceVertexUvs.length > 0 ) { geometryGroup.__uvArray = new Float32Array( nvertices * 2 ); } if ( geometry.faceVertexUvs.length > 1 ) { geometryGroup.__uv2Array = new Float32Array( nvertices * 2 ); } } if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) { geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 ); geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 ); } var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3 geometryGroup.__typeArray = UintArray; geometryGroup.__faceArray = new UintArray( ntris * 3 ); geometryGroup.__lineArray = new UintArray( nlines * 2 ); var m, ml; if ( geometryGroup.numMorphTargets ) { geometryGroup.__morphTargetsArrays = []; for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) { geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) ); } } if ( geometryGroup.numMorphNormals ) { geometryGroup.__morphNormalsArrays = []; for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) { geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) ); } } geometryGroup.__webglFaceCount = ntris * 3; geometryGroup.__webglLineCount = nlines * 2; // custom attributes if ( material.attributes ) { if ( geometryGroup.__webglCustomAttributesList === undefined ) { geometryGroup.__webglCustomAttributesList = []; } for ( var a in material.attributes ) { // Do a shallow copy of the attribute object so different geometryGroup chunks use different // attribute buffers which are correctly indexed in the setMeshBuffers function var originalAttribute = material.attributes[ a ]; var attribute = {}; for ( var property in originalAttribute ) { attribute[ property ] = originalAttribute[ property ]; } if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) { attribute.__webglInitialized = true; var size = 1; // "f" and "i" if( attribute.type === "v2" ) size = 2; else if( attribute.type === "v3" ) size = 3; else if( attribute.type === "v4" ) size = 4; else if( attribute.type === "c" ) size = 3; attribute.size = size; attribute.array = new Float32Array( nvertices * size ); attribute.buffer = _gl.createBuffer(); attribute.buffer.belongsToAttribute = a; originalAttribute.needsUpdate = true; attribute.__original = originalAttribute; } geometryGroup.__webglCustomAttributesList.push( attribute ); } } geometryGroup.__inittedArrays = true; }; function getBufferMaterial( object, geometryGroup ) { return object.material instanceof THREE.MeshFaceMaterial ? object.material.materials[ geometryGroup.materialIndex ] : object.material; }; function materialNeedsSmoothNormals ( material ) { return material && material.shading !== undefined && material.shading === THREE.SmoothShading; }; function bufferGuessNormalType ( material ) { // only MeshBasicMaterial and MeshDepthMaterial don't need normals if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) { return false; } if ( materialNeedsSmoothNormals( material ) ) { return THREE.SmoothShading; } else { return THREE.FlatShading; } }; function bufferGuessVertexColorType( material ) { if ( material.vertexColors ) { return material.vertexColors; } return false; }; function bufferGuessUVType( material ) { // material must use some texture to require uvs if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) { return true; } return false; }; // function initDirectBuffers( geometry ) { for ( var name in geometry.attributes ) { var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER; var attribute = geometry.attributes[ name ]; attribute.buffer = _gl.createBuffer(); _gl.bindBuffer( bufferType, attribute.buffer ); _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW ); } } // Buffer setting function setParticleBuffers ( geometry, hint, object ) { var v, c, vertex, offset, index, color, vertices = geometry.vertices, vl = vertices.length, colors = geometry.colors, cl = colors.length, vertexArray = geometry.__vertexArray, colorArray = geometry.__colorArray, sortArray = geometry.__sortArray, dirtyVertices = geometry.verticesNeedUpdate, dirtyElements = geometry.elementsNeedUpdate, dirtyColors = geometry.colorsNeedUpdate, customAttributes = geometry.__webglCustomAttributesList, i, il, a, ca, cal, value, customAttribute; if ( object.sortParticles ) { _projScreenMatrixPS.copy( _projScreenMatrix ); _projScreenMatrixPS.multiply( object.matrixWorld ); for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; _vector3.copy( vertex ); _vector3.applyProjection( _projScreenMatrixPS ); sortArray[ v ] = [ _vector3.z, v ]; } sortArray.sort( numericalSort ); for ( v = 0; v < vl; v ++ ) { vertex = vertices[ sortArray[v][1] ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } for ( c = 0; c < cl; c ++ ) { offset = c * 3; color = colors[ sortArray[c][1] ]; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue; offset = 0; cal = customAttribute.value.length; if ( customAttribute.size === 1 ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; customAttribute.array[ ca ] = customAttribute.value[ index ]; } } else if ( customAttribute.size === 2 ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; offset += 2; } } else if ( customAttribute.size === 3 ) { if ( customAttribute.type === "c" ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.r; customAttribute.array[ offset + 1 ] = value.g; customAttribute.array[ offset + 2 ] = value.b; offset += 3; } } else { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; offset += 3; } } } else if ( customAttribute.size === 4 ) { for ( ca = 0; ca < cal; ca ++ ) { index = sortArray[ ca ][ 1 ]; value = customAttribute.value[ index ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; customAttribute.array[ offset + 3 ] = value.w; offset += 4; } } } } } else { if ( dirtyVertices ) { for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } } if ( dirtyColors ) { for ( c = 0; c < cl; c ++ ) { color = colors[ c ]; offset = c * 3; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices") ) { cal = customAttribute.value.length; offset = 0; if ( customAttribute.size === 1 ) { for ( ca = 0; ca < cal; ca ++ ) { customAttribute.array[ ca ] = customAttribute.value[ ca ]; } } else if ( customAttribute.size === 2 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; offset += 2; } } else if ( customAttribute.size === 3 ) { if ( customAttribute.type === "c" ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.r; customAttribute.array[ offset + 1 ] = value.g; customAttribute.array[ offset + 2 ] = value.b; offset += 3; } } else { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; offset += 3; } } } else if ( customAttribute.size === 4 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; customAttribute.array[ offset + 3 ] = value.w; offset += 4; } } } } } } if ( dirtyVertices || object.sortParticles ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyColors || object.sortParticles ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( customAttribute.needsUpdate || object.sortParticles ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); } } } } function setLineBuffers ( geometry, hint ) { var v, c, d, vertex, offset, color, vertices = geometry.vertices, colors = geometry.colors, lineDistances = geometry.lineDistances, vl = vertices.length, cl = colors.length, dl = lineDistances.length, vertexArray = geometry.__vertexArray, colorArray = geometry.__colorArray, lineDistanceArray = geometry.__lineDistanceArray, dirtyVertices = geometry.verticesNeedUpdate, dirtyColors = geometry.colorsNeedUpdate, dirtyLineDistances = geometry.lineDistancesNeedUpdate, customAttributes = geometry.__webglCustomAttributesList, i, il, a, ca, cal, value, customAttribute; if ( dirtyVertices ) { for ( v = 0; v < vl; v ++ ) { vertex = vertices[ v ]; offset = v * 3; vertexArray[ offset ] = vertex.x; vertexArray[ offset + 1 ] = vertex.y; vertexArray[ offset + 2 ] = vertex.z; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyColors ) { for ( c = 0; c < cl; c ++ ) { color = colors[ c ]; offset = c * 3; colorArray[ offset ] = color.r; colorArray[ offset + 1 ] = color.g; colorArray[ offset + 2 ] = color.b; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } if ( dirtyLineDistances ) { for ( d = 0; d < dl; d ++ ) { lineDistanceArray[ d ] = lineDistances[ d ]; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint ); } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( customAttribute.needsUpdate && ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) { offset = 0; cal = customAttribute.value.length; if ( customAttribute.size === 1 ) { for ( ca = 0; ca < cal; ca ++ ) { customAttribute.array[ ca ] = customAttribute.value[ ca ]; } } else if ( customAttribute.size === 2 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; offset += 2; } } else if ( customAttribute.size === 3 ) { if ( customAttribute.type === "c" ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.r; customAttribute.array[ offset + 1 ] = value.g; customAttribute.array[ offset + 2 ] = value.b; offset += 3; } } else { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; offset += 3; } } } else if ( customAttribute.size === 4 ) { for ( ca = 0; ca < cal; ca ++ ) { value = customAttribute.value[ ca ]; customAttribute.array[ offset ] = value.x; customAttribute.array[ offset + 1 ] = value.y; customAttribute.array[ offset + 2 ] = value.z; customAttribute.array[ offset + 3 ] = value.w; offset += 4; } } _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); } } } } function setMeshBuffers( geometryGroup, object, hint, dispose, material ) { if ( ! geometryGroup.__inittedArrays ) { return; } var normalType = bufferGuessNormalType( material ), vertexColorType = bufferGuessVertexColorType( material ), uvType = bufferGuessUVType( material ), needsSmoothNormals = ( normalType === THREE.SmoothShading ); var f, fl, fi, face, vertexNormals, faceNormal, normal, vertexColors, faceColor, vertexTangents, uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4, c1, c2, c3, c4, sw1, sw2, sw3, sw4, si1, si2, si3, si4, sa1, sa2, sa3, sa4, sb1, sb2, sb3, sb4, m, ml, i, il, vn, uvi, uv2i, vk, vkl, vka, nka, chf, faceVertexNormals, a, vertexIndex = 0, offset = 0, offset_uv = 0, offset_uv2 = 0, offset_face = 0, offset_normal = 0, offset_tangent = 0, offset_line = 0, offset_color = 0, offset_skin = 0, offset_morphTarget = 0, offset_custom = 0, offset_customSrc = 0, value, vertexArray = geometryGroup.__vertexArray, uvArray = geometryGroup.__uvArray, uv2Array = geometryGroup.__uv2Array, normalArray = geometryGroup.__normalArray, tangentArray = geometryGroup.__tangentArray, colorArray = geometryGroup.__colorArray, skinIndexArray = geometryGroup.__skinIndexArray, skinWeightArray = geometryGroup.__skinWeightArray, morphTargetsArrays = geometryGroup.__morphTargetsArrays, morphNormalsArrays = geometryGroup.__morphNormalsArrays, customAttributes = geometryGroup.__webglCustomAttributesList, customAttribute, faceArray = geometryGroup.__faceArray, lineArray = geometryGroup.__lineArray, geometry = object.geometry, // this is shared for all chunks dirtyVertices = geometry.verticesNeedUpdate, dirtyElements = geometry.elementsNeedUpdate, dirtyUvs = geometry.uvsNeedUpdate, dirtyNormals = geometry.normalsNeedUpdate, dirtyTangents = geometry.tangentsNeedUpdate, dirtyColors = geometry.colorsNeedUpdate, dirtyMorphTargets = geometry.morphTargetsNeedUpdate, vertices = geometry.vertices, chunk_faces3 = geometryGroup.faces3, obj_faces = geometry.faces, obj_uvs = geometry.faceVertexUvs[ 0 ], obj_uvs2 = geometry.faceVertexUvs[ 1 ], obj_colors = geometry.colors, obj_skinIndices = geometry.skinIndices, obj_skinWeights = geometry.skinWeights, morphTargets = geometry.morphTargets, morphNormals = geometry.morphNormals; if ( dirtyVertices ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = vertices[ face.a ]; v2 = vertices[ face.b ]; v3 = vertices[ face.c ]; vertexArray[ offset ] = v1.x; vertexArray[ offset + 1 ] = v1.y; vertexArray[ offset + 2 ] = v1.z; vertexArray[ offset + 3 ] = v2.x; vertexArray[ offset + 4 ] = v2.y; vertexArray[ offset + 5 ] = v2.z; vertexArray[ offset + 6 ] = v3.x; vertexArray[ offset + 7 ] = v3.y; vertexArray[ offset + 8 ] = v3.z; offset += 9; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint ); } if ( dirtyMorphTargets ) { for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) { offset_morphTarget = 0; for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { chf = chunk_faces3[ f ]; face = obj_faces[ chf ]; // morph positions v1 = morphTargets[ vk ].vertices[ face.a ]; v2 = morphTargets[ vk ].vertices[ face.b ]; v3 = morphTargets[ vk ].vertices[ face.c ]; vka = morphTargetsArrays[ vk ]; vka[ offset_morphTarget ] = v1.x; vka[ offset_morphTarget + 1 ] = v1.y; vka[ offset_morphTarget + 2 ] = v1.z; vka[ offset_morphTarget + 3 ] = v2.x; vka[ offset_morphTarget + 4 ] = v2.y; vka[ offset_morphTarget + 5 ] = v2.z; vka[ offset_morphTarget + 6 ] = v3.x; vka[ offset_morphTarget + 7 ] = v3.y; vka[ offset_morphTarget + 8 ] = v3.z; // morph normals if ( material.morphNormals ) { if ( needsSmoothNormals ) { faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ]; n1 = faceVertexNormals.a; n2 = faceVertexNormals.b; n3 = faceVertexNormals.c; } else { n1 = morphNormals[ vk ].faceNormals[ chf ]; n2 = n1; n3 = n1; } nka = morphNormalsArrays[ vk ]; nka[ offset_morphTarget ] = n1.x; nka[ offset_morphTarget + 1 ] = n1.y; nka[ offset_morphTarget + 2 ] = n1.z; nka[ offset_morphTarget + 3 ] = n2.x; nka[ offset_morphTarget + 4 ] = n2.y; nka[ offset_morphTarget + 5 ] = n2.z; nka[ offset_morphTarget + 6 ] = n3.x; nka[ offset_morphTarget + 7 ] = n3.y; nka[ offset_morphTarget + 8 ] = n3.z; } // offset_morphTarget += 9; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] ); _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint ); if ( material.morphNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] ); _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint ); } } } if ( obj_skinWeights.length ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; // weights sw1 = obj_skinWeights[ face.a ]; sw2 = obj_skinWeights[ face.b ]; sw3 = obj_skinWeights[ face.c ]; skinWeightArray[ offset_skin ] = sw1.x; skinWeightArray[ offset_skin + 1 ] = sw1.y; skinWeightArray[ offset_skin + 2 ] = sw1.z; skinWeightArray[ offset_skin + 3 ] = sw1.w; skinWeightArray[ offset_skin + 4 ] = sw2.x; skinWeightArray[ offset_skin + 5 ] = sw2.y; skinWeightArray[ offset_skin + 6 ] = sw2.z; skinWeightArray[ offset_skin + 7 ] = sw2.w; skinWeightArray[ offset_skin + 8 ] = sw3.x; skinWeightArray[ offset_skin + 9 ] = sw3.y; skinWeightArray[ offset_skin + 10 ] = sw3.z; skinWeightArray[ offset_skin + 11 ] = sw3.w; // indices si1 = obj_skinIndices[ face.a ]; si2 = obj_skinIndices[ face.b ]; si3 = obj_skinIndices[ face.c ]; skinIndexArray[ offset_skin ] = si1.x; skinIndexArray[ offset_skin + 1 ] = si1.y; skinIndexArray[ offset_skin + 2 ] = si1.z; skinIndexArray[ offset_skin + 3 ] = si1.w; skinIndexArray[ offset_skin + 4 ] = si2.x; skinIndexArray[ offset_skin + 5 ] = si2.y; skinIndexArray[ offset_skin + 6 ] = si2.z; skinIndexArray[ offset_skin + 7 ] = si2.w; skinIndexArray[ offset_skin + 8 ] = si3.x; skinIndexArray[ offset_skin + 9 ] = si3.y; skinIndexArray[ offset_skin + 10 ] = si3.z; skinIndexArray[ offset_skin + 11 ] = si3.w; offset_skin += 12; } if ( offset_skin > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint ); } } if ( dirtyColors && vertexColorType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; vertexColors = face.vertexColors; faceColor = face.color; if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) { c1 = vertexColors[ 0 ]; c2 = vertexColors[ 1 ]; c3 = vertexColors[ 2 ]; } else { c1 = faceColor; c2 = faceColor; c3 = faceColor; } colorArray[ offset_color ] = c1.r; colorArray[ offset_color + 1 ] = c1.g; colorArray[ offset_color + 2 ] = c1.b; colorArray[ offset_color + 3 ] = c2.r; colorArray[ offset_color + 4 ] = c2.g; colorArray[ offset_color + 5 ] = c2.b; colorArray[ offset_color + 6 ] = c3.r; colorArray[ offset_color + 7 ] = c3.g; colorArray[ offset_color + 8 ] = c3.b; offset_color += 9; } if ( offset_color > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint ); } } if ( dirtyTangents && geometry.hasTangents ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; vertexTangents = face.vertexTangents; t1 = vertexTangents[ 0 ]; t2 = vertexTangents[ 1 ]; t3 = vertexTangents[ 2 ]; tangentArray[ offset_tangent ] = t1.x; tangentArray[ offset_tangent + 1 ] = t1.y; tangentArray[ offset_tangent + 2 ] = t1.z; tangentArray[ offset_tangent + 3 ] = t1.w; tangentArray[ offset_tangent + 4 ] = t2.x; tangentArray[ offset_tangent + 5 ] = t2.y; tangentArray[ offset_tangent + 6 ] = t2.z; tangentArray[ offset_tangent + 7 ] = t2.w; tangentArray[ offset_tangent + 8 ] = t3.x; tangentArray[ offset_tangent + 9 ] = t3.y; tangentArray[ offset_tangent + 10 ] = t3.z; tangentArray[ offset_tangent + 11 ] = t3.w; offset_tangent += 12; } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint ); } if ( dirtyNormals && normalType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; vertexNormals = face.vertexNormals; faceNormal = face.normal; if ( vertexNormals.length === 3 && needsSmoothNormals ) { for ( i = 0; i < 3; i ++ ) { vn = vertexNormals[ i ]; normalArray[ offset_normal ] = vn.x; normalArray[ offset_normal + 1 ] = vn.y; normalArray[ offset_normal + 2 ] = vn.z; offset_normal += 3; } } else { for ( i = 0; i < 3; i ++ ) { normalArray[ offset_normal ] = faceNormal.x; normalArray[ offset_normal + 1 ] = faceNormal.y; normalArray[ offset_normal + 2 ] = faceNormal.z; offset_normal += 3; } } } _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint ); } if ( dirtyUvs && obj_uvs && uvType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { fi = chunk_faces3[ f ]; uv = obj_uvs[ fi ]; if ( uv === undefined ) continue; for ( i = 0; i < 3; i ++ ) { uvi = uv[ i ]; uvArray[ offset_uv ] = uvi.x; uvArray[ offset_uv + 1 ] = uvi.y; offset_uv += 2; } } if ( offset_uv > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint ); } } if ( dirtyUvs && obj_uvs2 && uvType ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { fi = chunk_faces3[ f ]; uv2 = obj_uvs2[ fi ]; if ( uv2 === undefined ) continue; for ( i = 0; i < 3; i ++ ) { uv2i = uv2[ i ]; uv2Array[ offset_uv2 ] = uv2i.x; uv2Array[ offset_uv2 + 1 ] = uv2i.y; offset_uv2 += 2; } } if ( offset_uv2 > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint ); } } if ( dirtyElements ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { faceArray[ offset_face ] = vertexIndex; faceArray[ offset_face + 1 ] = vertexIndex + 1; faceArray[ offset_face + 2 ] = vertexIndex + 2; offset_face += 3; lineArray[ offset_line ] = vertexIndex; lineArray[ offset_line + 1 ] = vertexIndex + 1; lineArray[ offset_line + 2 ] = vertexIndex; lineArray[ offset_line + 3 ] = vertexIndex + 2; lineArray[ offset_line + 4 ] = vertexIndex + 1; lineArray[ offset_line + 5 ] = vertexIndex + 2; offset_line += 6; vertexIndex += 3; } _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint ); } if ( customAttributes ) { for ( i = 0, il = customAttributes.length; i < il; i ++ ) { customAttribute = customAttributes[ i ]; if ( ! customAttribute.__original.needsUpdate ) continue; offset_custom = 0; offset_customSrc = 0; if ( customAttribute.size === 1 ) { if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ]; customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ]; customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ]; offset_custom += 3; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; customAttribute.array[ offset_custom ] = value; customAttribute.array[ offset_custom + 1 ] = value; customAttribute.array[ offset_custom + 2 ] = value; offset_custom += 3; } } } else if ( customAttribute.size === 2 ) { if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v2.x; customAttribute.array[ offset_custom + 3 ] = v2.y; customAttribute.array[ offset_custom + 4 ] = v3.x; customAttribute.array[ offset_custom + 5 ] = v3.y; offset_custom += 6; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value; v2 = value; v3 = value; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v2.x; customAttribute.array[ offset_custom + 3 ] = v2.y; customAttribute.array[ offset_custom + 4 ] = v3.x; customAttribute.array[ offset_custom + 5 ] = v3.y; offset_custom += 6; } } } else if ( customAttribute.size === 3 ) { var pp; if ( customAttribute.type === "c" ) { pp = [ "r", "g", "b" ]; } else { pp = [ "x", "y", "z" ]; } if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; offset_custom += 9; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value; v2 = value; v3 = value; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; offset_custom += 9; } } else if ( customAttribute.boundTo === "faceVertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value[ 0 ]; v2 = value[ 1 ]; v3 = value[ 2 ]; customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ]; customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ]; customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ]; customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ]; offset_custom += 9; } } } else if ( customAttribute.size === 4 ) { if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { face = obj_faces[ chunk_faces3[ f ] ]; v1 = customAttribute.value[ face.a ]; v2 = customAttribute.value[ face.b ]; v3 = customAttribute.value[ face.c ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; offset_custom += 12; } } else if ( customAttribute.boundTo === "faces" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value; v2 = value; v3 = value; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; offset_custom += 12; } } else if ( customAttribute.boundTo === "faceVertices" ) { for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) { value = customAttribute.value[ chunk_faces3[ f ] ]; v1 = value[ 0 ]; v2 = value[ 1 ]; v3 = value[ 2 ]; customAttribute.array[ offset_custom ] = v1.x; customAttribute.array[ offset_custom + 1 ] = v1.y; customAttribute.array[ offset_custom + 2 ] = v1.z; customAttribute.array[ offset_custom + 3 ] = v1.w; customAttribute.array[ offset_custom + 4 ] = v2.x; customAttribute.array[ offset_custom + 5 ] = v2.y; customAttribute.array[ offset_custom + 6 ] = v2.z; customAttribute.array[ offset_custom + 7 ] = v2.w; customAttribute.array[ offset_custom + 8 ] = v3.x; customAttribute.array[ offset_custom + 9 ] = v3.y; customAttribute.array[ offset_custom + 10 ] = v3.z; customAttribute.array[ offset_custom + 11 ] = v3.w; offset_custom += 12; } } } _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint ); } } if ( dispose ) { delete geometryGroup.__inittedArrays; delete geometryGroup.__colorArray; delete geometryGroup.__normalArray; delete geometryGroup.__tangentArray; delete geometryGroup.__uvArray; delete geometryGroup.__uv2Array; delete geometryGroup.__faceArray; delete geometryGroup.__vertexArray; delete geometryGroup.__lineArray; delete geometryGroup.__skinIndexArray; delete geometryGroup.__skinWeightArray; } }; function setDirectBuffers( geometry, hint ) { var attributes = geometry.attributes; var attributeName, attributeItem; for ( attributeName in attributes ) { attributeItem = attributes[ attributeName ]; if ( attributeItem.needsUpdate ) { if ( attributeName === 'index' ) { _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer ); _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint ); } else { _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint ); } attributeItem.needsUpdate = false; } } } // Buffer rendering this.renderBufferImmediate = function ( object, program, material ) { if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer(); if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer(); if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer(); if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer(); if ( object.hasPositions ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.position ); _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.hasNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer ); if ( material.shading === THREE.FlatShading ) { var nx, ny, nz, nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz, normalArray, i, il = object.count * 3; for( i = 0; i < il; i += 9 ) { normalArray = object.normalArray; nax = normalArray[ i ]; nay = normalArray[ i + 1 ]; naz = normalArray[ i + 2 ]; nbx = normalArray[ i + 3 ]; nby = normalArray[ i + 4 ]; nbz = normalArray[ i + 5 ]; ncx = normalArray[ i + 6 ]; ncy = normalArray[ i + 7 ]; ncz = normalArray[ i + 8 ]; nx = ( nax + nbx + ncx ) / 3; ny = ( nay + nby + ncy ) / 3; nz = ( naz + nbz + ncz ) / 3; normalArray[ i ] = nx; normalArray[ i + 1 ] = ny; normalArray[ i + 2 ] = nz; normalArray[ i + 3 ] = nx; normalArray[ i + 4 ] = ny; normalArray[ i + 5 ] = nz; normalArray[ i + 6 ] = nx; normalArray[ i + 7 ] = ny; normalArray[ i + 8 ] = nz; } } _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.normal ); _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.hasUvs && material.map ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.uv ); _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); } if ( object.hasColors && material.vertexColors !== THREE.NoColors ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer ); _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW ); _gl.enableVertexAttribArray( program.attributes.color ); _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 ); } _gl.drawArrays( _gl.TRIANGLES, 0, object.count ); object.count = 0; }; function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) { for ( var attributeName in programAttributes ) { var attributePointer = programAttributes[ attributeName ]; var attributeItem = geometryAttributes[ attributeName ]; if ( attributePointer >= 0 ) { if ( attributeItem ) { var attributeSize = attributeItem.itemSize; _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer ); enableAttribute( attributePointer ); _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32 } else if ( material.defaultAttributeValues ) { if ( material.defaultAttributeValues[ attributeName ].length === 2 ) { _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) { _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] ); } } } } } this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) { if ( material.visible === false ) return; var linewidth, a, attribute; var attributeItem, attributeName, attributePointer, attributeSize; var program = setProgram( camera, lights, fog, material, object ); var programAttributes = program.attributes; var geometryAttributes = geometry.attributes; var updateBuffers = false, wireframeBit = material.wireframe ? 1 : 0, geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; if ( geometryHash !== _currentGeometryGroupHash ) { _currentGeometryGroupHash = geometryHash; updateBuffers = true; } if ( updateBuffers ) { disableAttributes(); } // render mesh if ( object instanceof THREE.Mesh ) { var index = geometryAttributes[ "index" ]; if ( index ) { // indexed triangles var type, size; if ( index.array instanceof Uint32Array ) { type = _gl.UNSIGNED_INT; size = 4; } else { type = _gl.UNSIGNED_SHORT; size = 2; } var offsets = geometry.offsets; if ( offsets.length === 0 ) { if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); } _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 ); _this.info.render.calls ++; _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared _this.info.render.faces += index.array.length / 3; } else { // if there is more than 1 chunk // must set attribute pointers to use new offsets for each chunk // even if geometry and materials didn't change updateBuffers = true; for ( var i = 0, il = offsets.length; i < il; i ++ ) { var startIndex = offsets[ i ].index; if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); } // render indexed triangles _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size ); _this.info.render.calls ++; _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared _this.info.render.faces += offsets[ i ].count / 3; } } } else { // non-indexed triangles if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); } var position = geometry.attributes[ "position" ]; // render non-indexed triangles _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 ); _this.info.render.calls ++; _this.info.render.vertices += position.array.length / 3; _this.info.render.faces += position.array.length / 3 / 3; } } else if ( object instanceof THREE.ParticleSystem ) { // render particles if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); } var position = geometryAttributes[ "position" ]; // render particles _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 ); _this.info.render.calls ++; _this.info.render.points += position.array.length / 3; } else if ( object instanceof THREE.Line ) { var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; setLineWidth( material.linewidth ); var index = geometryAttributes[ "index" ]; if ( index ) { // indexed lines var type, size; if ( index.array instanceof Uint32Array ){ type = _gl.UNSIGNED_INT; size = 4; } else { type = _gl.UNSIGNED_SHORT; size = 2; } var offsets = geometry.offsets; if ( offsets.length === 0 ) { if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); } _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array _this.info.render.calls ++; _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared } else { // if there is more than 1 chunk // must set attribute pointers to use new offsets for each chunk // even if geometry and materials didn't change if ( offsets.length > 1 ) updateBuffers = true; for ( var i = 0, il = offsets.length; i < il; i ++ ) { var startIndex = offsets[ i ].index; if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ); _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer ); } // render indexed lines _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array _this.info.render.calls ++; _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared } } } else { // non-indexed lines if ( updateBuffers ) { setupVertexAttributes( material, programAttributes, geometryAttributes, 0 ); } var position = geometryAttributes[ "position" ]; _gl.drawArrays( primitives, 0, position.array.length / 3 ); _this.info.render.calls ++; _this.info.render.points += position.array.length; } } }; this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) { if ( material.visible === false ) return; var linewidth, a, attribute, i, il; var program = setProgram( camera, lights, fog, material, object ); var attributes = program.attributes; var updateBuffers = false, wireframeBit = material.wireframe ? 1 : 0, geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit; if ( geometryGroupHash !== _currentGeometryGroupHash ) { _currentGeometryGroupHash = geometryGroupHash; updateBuffers = true; } if ( updateBuffers ) { disableAttributes(); } // vertices if ( !material.morphTargets && attributes.position >= 0 ) { if ( updateBuffers ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); enableAttribute( attributes.position ); _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } } else { if ( object.morphTargetBase ) { setupMorphTargets( material, geometryGroup, object ); } } if ( updateBuffers ) { // custom attributes // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers if ( geometryGroup.__webglCustomAttributesList ) { for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) { attribute = geometryGroup.__webglCustomAttributesList[ i ]; if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer ); enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] ); _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 ); } } } // colors if ( attributes.color >= 0 ) { if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer ); enableAttribute( attributes.color ); _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 ); } else if ( material.defaultAttributeValues ) { _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color ); } } // normals if ( attributes.normal >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer ); enableAttribute( attributes.normal ); _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 ); } // tangents if ( attributes.tangent >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer ); enableAttribute( attributes.tangent ); _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 ); } // uvs if ( attributes.uv >= 0 ) { if ( object.geometry.faceVertexUvs[0] ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer ); enableAttribute( attributes.uv ); _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 ); } else if ( material.defaultAttributeValues ) { _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv ); } } if ( attributes.uv2 >= 0 ) { if ( object.geometry.faceVertexUvs[1] ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer ); enableAttribute( attributes.uv2 ); _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 ); } else if ( material.defaultAttributeValues ) { _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 ); } } if ( material.skinning && attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer ); enableAttribute( attributes.skinIndex ); _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 ); _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer ); enableAttribute( attributes.skinWeight ); _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 ); } // line distances if ( attributes.lineDistance >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer ); enableAttribute( attributes.lineDistance ); _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 ); } } // render mesh if ( object instanceof THREE.Mesh ) { var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT; // wireframe if ( material.wireframe ) { setLineWidth( material.wireframeLinewidth ); if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer ); _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 ); // triangles } else { if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer ); _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 ); } _this.info.render.calls ++; _this.info.render.vertices += geometryGroup.__webglFaceCount; _this.info.render.faces += geometryGroup.__webglFaceCount / 3; // render lines } else if ( object instanceof THREE.Line ) { var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES; setLineWidth( material.linewidth ); _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount ); _this.info.render.calls ++; // render particles } else if ( object instanceof THREE.ParticleSystem ) { _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount ); _this.info.render.calls ++; _this.info.render.points += geometryGroup.__webglParticleCount; } }; function enableAttribute( attribute ) { if ( _enabledAttributes[ attribute ] === 0 ) { _gl.enableVertexAttribArray( attribute ); _enabledAttributes[ attribute ] = 1; } }; function disableAttributes() { for ( var attribute in _enabledAttributes ) { if ( _enabledAttributes[ attribute ] === 1 ) { _gl.disableVertexAttribArray( attribute ); _enabledAttributes[ attribute ] = 0; } } }; function setupMorphTargets ( material, geometryGroup, object ) { // set base var attributes = material.program.attributes; if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] ); enableAttribute( attributes.position ); _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } else if ( attributes.position >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer ); enableAttribute( attributes.position ); _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 ); } if ( object.morphTargetForcedOrder.length ) { // set forced order var m = 0; var order = object.morphTargetForcedOrder; var influences = object.morphTargetInfluences; while ( m < material.numSupportedMorphTargets && m < order.length ) { if ( attributes[ "morphTarget" + m ] >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] ); enableAttribute( attributes[ "morphTarget" + m ] ); _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); } if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] ); enableAttribute( attributes[ "morphNormal" + m ] ); _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); } object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ]; m ++; } } else { // find the most influencing var influence, activeInfluenceIndices = []; var influences = object.morphTargetInfluences; var i, il = influences.length; for ( i = 0; i < il; i ++ ) { influence = influences[ i ]; if ( influence > 0 ) { activeInfluenceIndices.push( [ influence, i ] ); } } if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) { activeInfluenceIndices.sort( numericalSort ); activeInfluenceIndices.length = material.numSupportedMorphTargets; } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) { activeInfluenceIndices.sort( numericalSort ); } else if ( activeInfluenceIndices.length === 0 ) { activeInfluenceIndices.push( [ 0, 0 ] ); }; var influenceIndex, m = 0; while ( m < material.numSupportedMorphTargets ) { if ( activeInfluenceIndices[ m ] ) { influenceIndex = activeInfluenceIndices[ m ][ 1 ]; if ( attributes[ "morphTarget" + m ] >= 0 ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] ); enableAttribute( attributes[ "morphTarget" + m ] ); _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); } if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) { _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] ); enableAttribute( attributes[ "morphNormal" + m ] ); _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); } object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ]; } else { /* _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 ); if ( material.morphNormals ) { _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 ); } */ object.__webglMorphTargetInfluences[ m ] = 0; } m ++; } } // load updated influences uniform if ( material.program.uniforms.morphTargetInfluences !== null ) { _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences ); } }; // Sorting function painterSortStable ( a, b ) { if ( a.materialId !== b.materialId ) { return b.materialId - a.materialId; } else if ( a.z !== b.z ) { return b.z - a.z; } else { return a.id - b.id; } }; function numericalSort ( a, b ) { return b[ 0 ] - a[ 0 ]; }; // Rendering this.render = function ( scene, camera, renderTarget, forceClear ) { if ( camera instanceof THREE.Camera === false ) { console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); return; } var i, il, webglObject, object, renderList, lights = scene.__lights, fog = scene.fog; // reset caching for this frame _currentMaterialId = -1; _lightsNeedUpdate = true; // update scene graph if ( scene.autoUpdate === true ) scene.updateMatrixWorld(); // update camera matrices and frustum if ( camera.parent === undefined ) camera.updateMatrixWorld(); camera.matrixWorldInverse.getInverse( camera.matrixWorld ); _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); _frustum.setFromMatrix( _projScreenMatrix ); // update WebGL objects if ( this.autoUpdateObjects ) this.initWebGLObjects( scene ); // custom render plugins (pre pass) renderPlugins( this.renderPluginsPre, scene, camera ); // _this.info.render.calls = 0; _this.info.render.vertices = 0; _this.info.render.faces = 0; _this.info.render.points = 0; this.setRenderTarget( renderTarget ); if ( this.autoClear || forceClear ) { this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil ); } // set matrices for regular objects (frustum culled) renderList = scene.__webglObjects; for ( i = 0, il = renderList.length; i < il; i ++ ) { webglObject = renderList[ i ]; object = webglObject.object; webglObject.id = i; webglObject.materialId = object.material.id; webglObject.render = false; if ( object.visible ) { if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) { setupMatrices( object, camera ); unrollBufferMaterial( webglObject ); webglObject.render = true; if ( this.sortObjects === true ) { if ( object.renderDepth !== null ) { webglObject.z = object.renderDepth; } else { _vector3.setFromMatrixPosition( object.matrixWorld ); _vector3.applyProjection( _projScreenMatrix ); webglObject.z = _vector3.z; } } } } } if ( this.sortObjects ) { renderList.sort( painterSortStable ); } // set matrices for immediate objects renderList = scene.__webglObjectsImmediate; for ( i = 0, il = renderList.length; i < il; i ++ ) { webglObject = renderList[ i ]; object = webglObject.object; if ( object.visible ) { setupMatrices( object, camera ); unrollImmediateBufferMaterial( webglObject ); } } if ( scene.overrideMaterial ) { var material = scene.overrideMaterial; this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); this.setDepthTest( material.depthTest ); this.setDepthWrite( material.depthWrite ); setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material ); renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material ); } else { var material = null; // opaque pass (front-to-back order) this.setBlending( THREE.NoBlending ); renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material ); renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material ); // transparent pass (back-to-front order) renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material ); renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material ); } // custom render plugins (post pass) renderPlugins( this.renderPluginsPost, scene, camera ); // Generate mipmap if we're using any kind of mipmap filtering if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) { updateRenderTargetMipmap( renderTarget ); } // Ensure depth buffer writing is enabled so it can be cleared on next render this.setDepthTest( true ); this.setDepthWrite( true ); // _gl.finish(); }; function renderPlugins( plugins, scene, camera ) { if ( ! plugins.length ) return; for ( var i = 0, il = plugins.length; i < il; i ++ ) { // reset state for plugin (to start from clean slate) _currentProgram = null; _currentCamera = null; _oldBlending = -1; _oldDepthTest = -1; _oldDepthWrite = -1; _oldDoubleSided = -1; _oldFlipSided = -1; _currentGeometryGroupHash = -1; _currentMaterialId = -1; _lightsNeedUpdate = true; plugins[ i ].render( scene, camera, _currentWidth, _currentHeight ); // reset state after plugin (anything could have changed) _currentProgram = null; _currentCamera = null; _oldBlending = -1; _oldDepthTest = -1; _oldDepthWrite = -1; _oldDoubleSided = -1; _oldFlipSided = -1; _currentGeometryGroupHash = -1; _currentMaterialId = -1; _lightsNeedUpdate = true; } }; function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) { var webglObject, object, buffer, material, start, end, delta; if ( reverse ) { start = renderList.length - 1; end = -1; delta = -1; } else { start = 0; end = renderList.length; delta = 1; } for ( var i = start; i !== end; i += delta ) { webglObject = renderList[ i ]; if ( webglObject.render ) { object = webglObject.object; buffer = webglObject.buffer; if ( overrideMaterial ) { material = overrideMaterial; } else { material = webglObject[ materialType ]; if ( ! material ) continue; if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); _this.setDepthTest( material.depthTest ); _this.setDepthWrite( material.depthWrite ); setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); } _this.setMaterialFaces( material ); if ( buffer instanceof THREE.BufferGeometry ) { _this.renderBufferDirect( camera, lights, fog, material, buffer, object ); } else { _this.renderBuffer( camera, lights, fog, material, buffer, object ); } } } }; function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) { var webglObject, object, material, program; for ( var i = 0, il = renderList.length; i < il; i ++ ) { webglObject = renderList[ i ]; object = webglObject.object; if ( object.visible ) { if ( overrideMaterial ) { material = overrideMaterial; } else { material = webglObject[ materialType ]; if ( ! material ) continue; if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst ); _this.setDepthTest( material.depthTest ); _this.setDepthWrite( material.depthWrite ); setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); } _this.renderImmediateObject( camera, lights, fog, material, object ); } } }; this.renderImmediateObject = function ( camera, lights, fog, material, object ) { var program = setProgram( camera, lights, fog, material, object ); _currentGeometryGroupHash = -1; _this.setMaterialFaces( material ); if ( object.immediateRenderCallback ) { object.immediateRenderCallback( program, _gl, _frustum ); } else { object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } ); } }; function unrollImmediateBufferMaterial ( globject ) { var object = globject.object, material = object.material; if ( material.transparent ) { globject.transparent = material; globject.opaque = null; } else { globject.opaque = material; globject.transparent = null; } }; function unrollBufferMaterial ( globject ) { var object = globject.object; var buffer = globject.buffer; var geometry = object.geometry; var material = object.material; if ( material instanceof THREE.MeshFaceMaterial ) { var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex; material = material.materials[ materialIndex ]; if ( material.transparent ) { globject.transparent = material; globject.opaque = null; } else { globject.opaque = material; globject.transparent = null; } } else { if ( material ) { if ( material.transparent ) { globject.transparent = material; globject.opaque = null; } else { globject.opaque = material; globject.transparent = null; } } } }; // Objects refresh this.initWebGLObjects = function ( scene ) { if ( !scene.__webglObjects ) { scene.__webglObjects = []; scene.__webglObjectsImmediate = []; scene.__webglSprites = []; scene.__webglFlares = []; } while ( scene.__objectsAdded.length ) { addObject( scene.__objectsAdded[ 0 ], scene ); scene.__objectsAdded.splice( 0, 1 ); } while ( scene.__objectsRemoved.length ) { removeObject( scene.__objectsRemoved[ 0 ], scene ); scene.__objectsRemoved.splice( 0, 1 ); } // update must be called after objects adding / removal for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) { var object = scene.__webglObjects[ o ].object; // TODO: Remove this hack (WebGLRenderer refactoring) if ( object.__webglInit === undefined ) { if ( object.__webglActive !== undefined ) { removeObject( object, scene ); } addObject( object, scene ); } updateObject( object ); } }; // Objects adding function addObject( object, scene ) { var g, geometry, material, geometryGroup; if ( object.__webglInit === undefined ) { object.__webglInit = true; object._modelViewMatrix = new THREE.Matrix4(); object._normalMatrix = new THREE.Matrix3(); if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) { object.geometry.__webglInit = true; object.geometry.addEventListener( 'dispose', onGeometryDispose ); } geometry = object.geometry; if ( geometry === undefined ) { // fail silently for now } else if ( geometry instanceof THREE.BufferGeometry ) { initDirectBuffers( geometry ); } else if ( object instanceof THREE.Mesh ) { material = object.material; if ( geometry.geometryGroups === undefined ) { geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 ); } // create separate VBOs per geometry chunk for ( g in geometry.geometryGroups ) { geometryGroup = geometry.geometryGroups[ g ]; // initialise VBO on the first access if ( ! geometryGroup.__webglVertexBuffer ) { createMeshBuffers( geometryGroup ); initMeshBuffers( geometryGroup, object ); geometry.verticesNeedUpdate = true; geometry.morphTargetsNeedUpdate = true; geometry.elementsNeedUpdate = true; geometry.uvsNeedUpdate = true; geometry.normalsNeedUpdate = true; geometry.tangentsNeedUpdate = true; geometry.colorsNeedUpdate = true; } } } else if ( object instanceof THREE.Line ) { if ( ! geometry.__webglVertexBuffer ) { createLineBuffers( geometry ); initLineBuffers( geometry, object ); geometry.verticesNeedUpdate = true; geometry.colorsNeedUpdate = true; geometry.lineDistancesNeedUpdate = true; } } else if ( object instanceof THREE.ParticleSystem ) { if ( ! geometry.__webglVertexBuffer ) { createParticleBuffers( geometry ); initParticleBuffers( geometry, object ); geometry.verticesNeedUpdate = true; geometry.colorsNeedUpdate = true; } } } if ( object.__webglActive === undefined ) { if ( object instanceof THREE.Mesh ) { geometry = object.geometry; if ( geometry instanceof THREE.BufferGeometry ) { addBuffer( scene.__webglObjects, geometry, object ); } else if ( geometry instanceof THREE.Geometry ) { for ( g in geometry.geometryGroups ) { geometryGroup = geometry.geometryGroups[ g ]; addBuffer( scene.__webglObjects, geometryGroup, object ); } } } else if ( object instanceof THREE.Line || object instanceof THREE.ParticleSystem ) { geometry = object.geometry; addBuffer( scene.__webglObjects, geometry, object ); } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { addBufferImmediate( scene.__webglObjectsImmediate, object ); } else if ( object instanceof THREE.Sprite ) { scene.__webglSprites.push( object ); } else if ( object instanceof THREE.LensFlare ) { scene.__webglFlares.push( object ); } object.__webglActive = true; } }; function addBuffer( objlist, buffer, object ) { objlist.push( { id: null, buffer: buffer, object: object, materialId: null, opaque: null, transparent: null, z: 0 } ); }; function addBufferImmediate( objlist, object ) { objlist.push( { id: null, object: object, opaque: null, transparent: null, z: 0 } ); }; // Objects updates function updateObject( object ) { var geometry = object.geometry, geometryGroup, customAttributesDirty, material; if ( geometry instanceof THREE.BufferGeometry ) { setDirectBuffers( geometry, _gl.DYNAMIC_DRAW ); } else if ( object instanceof THREE.Mesh ) { // check all geometry groups for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) { geometryGroup = geometry.geometryGroupsList[ i ]; material = getBufferMaterial( object, geometryGroup ); if ( geometry.buffersNeedUpdate ) { initMeshBuffers( geometryGroup, object ); } customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate || geometry.uvsNeedUpdate || geometry.normalsNeedUpdate || geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) { setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material ); } } geometry.verticesNeedUpdate = false; geometry.morphTargetsNeedUpdate = false; geometry.elementsNeedUpdate = false; geometry.uvsNeedUpdate = false; geometry.normalsNeedUpdate = false; geometry.colorsNeedUpdate = false; geometry.tangentsNeedUpdate = false; geometry.buffersNeedUpdate = false; material.attributes && clearCustomAttributes( material ); } else if ( object instanceof THREE.Line ) { material = getBufferMaterial( object, geometry ); customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) { setLineBuffers( geometry, _gl.DYNAMIC_DRAW ); } geometry.verticesNeedUpdate = false; geometry.colorsNeedUpdate = false; geometry.lineDistancesNeedUpdate = false; material.attributes && clearCustomAttributes( material ); } else if ( object instanceof THREE.ParticleSystem ) { material = getBufferMaterial( object, geometry ); customAttributesDirty = material.attributes && areCustomAttributesDirty( material ); if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) { setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object ); } geometry.verticesNeedUpdate = false; geometry.colorsNeedUpdate = false; material.attributes && clearCustomAttributes( material ); } }; // Objects updates - custom attributes check function areCustomAttributesDirty( material ) { for ( var a in material.attributes ) { if ( material.attributes[ a ].needsUpdate ) return true; } return false; }; function clearCustomAttributes( material ) { for ( var a in material.attributes ) { material.attributes[ a ].needsUpdate = false; } }; // Objects removal function removeObject( object, scene ) { if ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem || object instanceof THREE.Line ) { removeInstances( scene.__webglObjects, object ); } else if ( object instanceof THREE.Sprite ) { removeInstancesDirect( scene.__webglSprites, object ); } else if ( object instanceof THREE.LensFlare ) { removeInstancesDirect( scene.__webglFlares, object ); } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) { removeInstances( scene.__webglObjectsImmediate, object ); } delete object.__webglActive; }; function removeInstances( objlist, object ) { for ( var o = objlist.length - 1; o >= 0; o -- ) { if ( objlist[ o ].object === object ) { objlist.splice( o, 1 ); } } }; function removeInstancesDirect( objlist, object ) { for ( var o = objlist.length - 1; o >= 0; o -- ) { if ( objlist[ o ] === object ) { objlist.splice( o, 1 ); } } }; // Materials this.initMaterial = function ( material, lights, fog, object ) { material.addEventListener( 'dispose', onMaterialDispose ); var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID; if ( material instanceof THREE.MeshDepthMaterial ) { shaderID = 'depth'; } else if ( material instanceof THREE.MeshNormalMaterial ) { shaderID = 'normal'; } else if ( material instanceof THREE.MeshBasicMaterial ) { shaderID = 'basic'; } else if ( material instanceof THREE.MeshLambertMaterial ) { shaderID = 'lambert'; } else if ( material instanceof THREE.MeshPhongMaterial ) { shaderID = 'phong'; } else if ( material instanceof THREE.LineBasicMaterial ) { shaderID = 'basic'; } else if ( material instanceof THREE.LineDashedMaterial ) { shaderID = 'dashed'; } else if ( material instanceof THREE.ParticleSystemMaterial ) { shaderID = 'particle_basic'; } if ( shaderID ) { setMaterialShaders( material, THREE.ShaderLib[ shaderID ] ); } // heuristics to create shader parameters according to lights in the scene // (not to blow over maxLights budget) maxLightCount = allocateLights( lights ); maxShadows = allocateShadows( lights ); maxBones = allocateBones( object ); parameters = { map: !!material.map, envMap: !!material.envMap, lightMap: !!material.lightMap, bumpMap: !!material.bumpMap, normalMap: !!material.normalMap, specularMap: !!material.specularMap, vertexColors: material.vertexColors, fog: fog, useFog: material.fog, fogExp: fog instanceof THREE.FogExp2, sizeAttenuation: material.sizeAttenuation, skinning: material.skinning, maxBones: maxBones, useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture, morphTargets: material.morphTargets, morphNormals: material.morphNormals, maxMorphTargets: this.maxMorphTargets, maxMorphNormals: this.maxMorphNormals, maxDirLights: maxLightCount.directional, maxPointLights: maxLightCount.point, maxSpotLights: maxLightCount.spot, maxHemiLights: maxLightCount.hemi, maxShadows: maxShadows, shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0, shadowMapType: this.shadowMapType, shadowMapDebug: this.shadowMapDebug, shadowMapCascade: this.shadowMapCascade, alphaTest: material.alphaTest, metal: material.metal, wrapAround: material.wrapAround, doubleSided: material.side === THREE.DoubleSide, flipSided: material.side === THREE.BackSide }; material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName ); var attributes = material.program.attributes; if ( material.morphTargets ) { material.numSupportedMorphTargets = 0; var id, base = "morphTarget"; for ( i = 0; i < this.maxMorphTargets; i ++ ) { id = base + i; if ( attributes[ id ] >= 0 ) { material.numSupportedMorphTargets ++; } } } if ( material.morphNormals ) { material.numSupportedMorphNormals = 0; var id, base = "morphNormal"; for ( i = 0; i < this.maxMorphNormals; i ++ ) { id = base + i; if ( attributes[ id ] >= 0 ) { material.numSupportedMorphNormals ++; } } } material.uniformsList = []; for ( u in material.uniforms ) { material.uniformsList.push( [ material.uniforms[ u ], u ] ); } }; function setMaterialShaders( material, shaders ) { material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms ); material.vertexShader = shaders.vertexShader; material.fragmentShader = shaders.fragmentShader; }; function setProgram( camera, lights, fog, material, object ) { _usedTextureUnits = 0; if ( material.needsUpdate ) { if ( material.program ) deallocateMaterial( material ); _this.initMaterial( material, lights, fog, object ); material.needsUpdate = false; } if ( material.morphTargets ) { if ( ! object.__webglMorphTargetInfluences ) { object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets ); } } var refreshMaterial = false; var program = material.program, p_uniforms = program.uniforms, m_uniforms = material.uniforms; if ( program !== _currentProgram ) { _gl.useProgram( program ); _currentProgram = program; refreshMaterial = true; } if ( material.id !== _currentMaterialId ) { _currentMaterialId = material.id; refreshMaterial = true; } if ( refreshMaterial || camera !== _currentCamera ) { _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements ); if ( camera !== _currentCamera ) _currentCamera = camera; } // skinning uniforms must be set even if material didn't change // auto-setting of texture unit for bone texture must go before other textures // not sure why, but otherwise weird things happen if ( material.skinning ) { if ( _supportsBoneTextures && object.useVertexTexture ) { if ( p_uniforms.boneTexture !== null ) { var textureUnit = getTextureUnit(); _gl.uniform1i( p_uniforms.boneTexture, textureUnit ); _this.setTexture( object.boneTexture, textureUnit ); } if ( p_uniforms.boneTextureWidth !== null ) { _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth ); } if ( p_uniforms.boneTextureHeight !== null ) { _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight ); } } else { if ( p_uniforms.boneGlobalMatrices !== null ) { _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices ); } } } if ( refreshMaterial ) { // refresh uniforms common to several materials if ( fog && material.fog ) { refreshUniformsFog( m_uniforms, fog ); } if ( material instanceof THREE.MeshPhongMaterial || material instanceof THREE.MeshLambertMaterial || material.lights ) { if ( _lightsNeedUpdate ) { setupLights( program, lights ); _lightsNeedUpdate = false; } refreshUniformsLights( m_uniforms, _lights ); } if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) { refreshUniformsCommon( m_uniforms, material ); } // refresh single material specific uniforms if ( material instanceof THREE.LineBasicMaterial ) { refreshUniformsLine( m_uniforms, material ); } else if ( material instanceof THREE.LineDashedMaterial ) { refreshUniformsLine( m_uniforms, material ); refreshUniformsDash( m_uniforms, material ); } else if ( material instanceof THREE.ParticleSystemMaterial ) { refreshUniformsParticle( m_uniforms, material ); } else if ( material instanceof THREE.MeshPhongMaterial ) { refreshUniformsPhong( m_uniforms, material ); } else if ( material instanceof THREE.MeshLambertMaterial ) { refreshUniformsLambert( m_uniforms, material ); } else if ( material instanceof THREE.MeshDepthMaterial ) { m_uniforms.mNear.value = camera.near; m_uniforms.mFar.value = camera.far; m_uniforms.opacity.value = material.opacity; } else if ( material instanceof THREE.MeshNormalMaterial ) { m_uniforms.opacity.value = material.opacity; } if ( object.receiveShadow && ! material._shadowPass ) { refreshUniformsShadow( m_uniforms, lights ); } // load common uniforms loadUniformsGeneric( program, material.uniformsList ); // load material specific uniforms // (shader material also gets them for the sake of genericity) if ( material instanceof THREE.ShaderMaterial || material instanceof THREE.MeshPhongMaterial || material.envMap ) { if ( p_uniforms.cameraPosition !== null ) { _vector3.setFromMatrixPosition( camera.matrixWorld ); _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z ); } } if ( material instanceof THREE.MeshPhongMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.ShaderMaterial || material.skinning ) { if ( p_uniforms.viewMatrix !== null ) { _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements ); } } } loadUniformsMatrices( p_uniforms, object ); if ( p_uniforms.modelMatrix !== null ) { _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements ); } return program; }; // Uniforms (refresh uniforms objects) function refreshUniformsCommon ( uniforms, material ) { uniforms.opacity.value = material.opacity; if ( _this.gammaInput ) { uniforms.diffuse.value.copyGammaToLinear( material.color ); } else { uniforms.diffuse.value = material.color; } uniforms.map.value = material.map; uniforms.lightMap.value = material.lightMap; uniforms.specularMap.value = material.specularMap; if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); } // uv repeat and offset setting priorities // 1. color map // 2. specular map // 3. normal map // 4. bump map var uvScaleMap; if ( material.map ) { uvScaleMap = material.map; } else if ( material.specularMap ) { uvScaleMap = material.specularMap; } else if ( material.normalMap ) { uvScaleMap = material.normalMap; } else if ( material.bumpMap ) { uvScaleMap = material.bumpMap; } if ( uvScaleMap !== undefined ) { var offset = uvScaleMap.offset; var repeat = uvScaleMap.repeat; uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); } uniforms.envMap.value = material.envMap; uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1; if ( _this.gammaInput ) { //uniforms.reflectivity.value = material.reflectivity * material.reflectivity; uniforms.reflectivity.value = material.reflectivity; } else { uniforms.reflectivity.value = material.reflectivity; } uniforms.refractionRatio.value = material.refractionRatio; uniforms.combine.value = material.combine; uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping; }; function refreshUniformsLine ( uniforms, material ) { uniforms.diffuse.value = material.color; uniforms.opacity.value = material.opacity; }; function refreshUniformsDash ( uniforms, material ) { uniforms.dashSize.value = material.dashSize; uniforms.totalSize.value = material.dashSize + material.gapSize; uniforms.scale.value = material.scale; }; function refreshUniformsParticle ( uniforms, material ) { uniforms.psColor.value = material.color; uniforms.opacity.value = material.opacity; uniforms.size.value = material.size; uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this. uniforms.map.value = material.map; }; function refreshUniformsFog ( uniforms, fog ) { uniforms.fogColor.value = fog.color; if ( fog instanceof THREE.Fog ) { uniforms.fogNear.value = fog.near; uniforms.fogFar.value = fog.far; } else if ( fog instanceof THREE.FogExp2 ) { uniforms.fogDensity.value = fog.density; } }; function refreshUniformsPhong ( uniforms, material ) { uniforms.shininess.value = material.shininess; if ( _this.gammaInput ) { uniforms.ambient.value.copyGammaToLinear( material.ambient ); uniforms.emissive.value.copyGammaToLinear( material.emissive ); uniforms.specular.value.copyGammaToLinear( material.specular ); } else { uniforms.ambient.value = material.ambient; uniforms.emissive.value = material.emissive; uniforms.specular.value = material.specular; } if ( material.wrapAround ) { uniforms.wrapRGB.value.copy( material.wrapRGB ); } }; function refreshUniformsLambert ( uniforms, material ) { if ( _this.gammaInput ) { uniforms.ambient.value.copyGammaToLinear( material.ambient ); uniforms.emissive.value.copyGammaToLinear( material.emissive ); } else { uniforms.ambient.value = material.ambient; uniforms.emissive.value = material.emissive; } if ( material.wrapAround ) { uniforms.wrapRGB.value.copy( material.wrapRGB ); } }; function refreshUniformsLights ( uniforms, lights ) { uniforms.ambientLightColor.value = lights.ambient; uniforms.directionalLightColor.value = lights.directional.colors; uniforms.directionalLightDirection.value = lights.directional.positions; uniforms.pointLightColor.value = lights.point.colors; uniforms.pointLightPosition.value = lights.point.positions; uniforms.pointLightDistance.value = lights.point.distances; uniforms.spotLightColor.value = lights.spot.colors; uniforms.spotLightPosition.value = lights.spot.positions; uniforms.spotLightDistance.value = lights.spot.distances; uniforms.spotLightDirection.value = lights.spot.directions; uniforms.spotLightAngleCos.value = lights.spot.anglesCos; uniforms.spotLightExponent.value = lights.spot.exponents; uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors; uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors; uniforms.hemisphereLightDirection.value = lights.hemi.positions; }; function refreshUniformsShadow ( uniforms, lights ) { if ( uniforms.shadowMatrix ) { var j = 0; for ( var i = 0, il = lights.length; i < il; i ++ ) { var light = lights[ i ]; if ( ! light.castShadow ) continue; if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) { uniforms.shadowMap.value[ j ] = light.shadowMap; uniforms.shadowMapSize.value[ j ] = light.shadowMapSize; uniforms.shadowMatrix.value[ j ] = light.shadowMatrix; uniforms.shadowDarkness.value[ j ] = light.shadowDarkness; uniforms.shadowBias.value[ j ] = light.shadowBias; j ++; } } } }; // Uniforms (load to GPU) function loadUniformsMatrices ( uniforms, object ) { _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements ); if ( uniforms.normalMatrix ) { _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements ); } }; function getTextureUnit() { var textureUnit = _usedTextureUnits; if ( textureUnit >= _maxTextures ) { console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures ); } _usedTextureUnits += 1; return textureUnit; }; function loadUniformsGeneric ( program, uniforms ) { var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset; for ( j = 0, jl = uniforms.length; j < jl; j ++ ) { location = program.uniforms[ uniforms[ j ][ 1 ] ]; if ( !location ) continue; uniform = uniforms[ j ][ 0 ]; type = uniform.type; value = uniform.value; if ( type === "i" ) { // single integer _gl.uniform1i( location, value ); } else if ( type === "f" ) { // single float _gl.uniform1f( location, value ); } else if ( type === "v2" ) { // single THREE.Vector2 _gl.uniform2f( location, value.x, value.y ); } else if ( type === "v3" ) { // single THREE.Vector3 _gl.uniform3f( location, value.x, value.y, value.z ); } else if ( type === "v4" ) { // single THREE.Vector4 _gl.uniform4f( location, value.x, value.y, value.z, value.w ); } else if ( type === "c" ) { // single THREE.Color _gl.uniform3f( location, value.r, value.g, value.b ); } else if ( type === "iv1" ) { // flat array of integers (JS or typed array) _gl.uniform1iv( location, value ); } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array) _gl.uniform3iv( location, value ); } else if ( type === "fv1" ) { // flat array of floats (JS or typed array) _gl.uniform1fv( location, value ); } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array) _gl.uniform3fv( location, value ); } else if ( type === "v2v" ) { // array of THREE.Vector2 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 2 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { offset = i * 2; uniform._array[ offset ] = value[ i ].x; uniform._array[ offset + 1 ] = value[ i ].y; } _gl.uniform2fv( location, uniform._array ); } else if ( type === "v3v" ) { // array of THREE.Vector3 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 3 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { offset = i * 3; uniform._array[ offset ] = value[ i ].x; uniform._array[ offset + 1 ] = value[ i ].y; uniform._array[ offset + 2 ] = value[ i ].z; } _gl.uniform3fv( location, uniform._array ); } else if ( type === "v4v" ) { // array of THREE.Vector4 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 4 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { offset = i * 4; uniform._array[ offset ] = value[ i ].x; uniform._array[ offset + 1 ] = value[ i ].y; uniform._array[ offset + 2 ] = value[ i ].z; uniform._array[ offset + 3 ] = value[ i ].w; } _gl.uniform4fv( location, uniform._array ); } else if ( type === "m4") { // single THREE.Matrix4 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 16 ); } value.flattenToArray( uniform._array ); _gl.uniformMatrix4fv( location, false, uniform._array ); } else if ( type === "m4v" ) { // array of THREE.Matrix4 if ( uniform._array === undefined ) { uniform._array = new Float32Array( 16 * value.length ); } for ( i = 0, il = value.length; i < il; i ++ ) { value[ i ].flattenToArrayOffset( uniform._array, i * 16 ); } _gl.uniformMatrix4fv( location, false, uniform._array ); } else if ( type === "t" ) { // single THREE.Texture (2d or cube) texture = value; textureUnit = getTextureUnit(); _gl.uniform1i( location, textureUnit ); if ( !texture ) continue; if ( texture.image instanceof Array && texture.image.length === 6 ) { setCubeTexture( texture, textureUnit ); } else if ( texture instanceof THREE.WebGLRenderTargetCube ) { setCubeTextureDynamic( texture, textureUnit ); } else { _this.setTexture( texture, textureUnit ); } } else if ( type === "tv" ) { // array of THREE.Texture (2d) if ( uniform._array === undefined ) { uniform._array = []; } for( i = 0, il = uniform.value.length; i < il; i ++ ) { uniform._array[ i ] = getTextureUnit(); } _gl.uniform1iv( location, uniform._array ); for( i = 0, il = uniform.value.length; i < il; i ++ ) { texture = uniform.value[ i ]; textureUnit = uniform._array[ i ]; if ( !texture ) continue; _this.setTexture( texture, textureUnit ); } } else { console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type ); } } }; function setupMatrices ( object, camera ) { object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); object._normalMatrix.getNormalMatrix( object._modelViewMatrix ); }; // function setColorGamma( array, offset, color, intensitySq ) { array[ offset ] = color.r * color.r * intensitySq; array[ offset + 1 ] = color.g * color.g * intensitySq; array[ offset + 2 ] = color.b * color.b * intensitySq; }; function setColorLinear( array, offset, color, intensity ) { array[ offset ] = color.r * intensity; array[ offset + 1 ] = color.g * intensity; array[ offset + 2 ] = color.b * intensity; }; function setupLights ( program, lights ) { var l, ll, light, n, r = 0, g = 0, b = 0, color, skyColor, groundColor, intensity, intensitySq, position, distance, zlights = _lights, dirColors = zlights.directional.colors, dirPositions = zlights.directional.positions, pointColors = zlights.point.colors, pointPositions = zlights.point.positions, pointDistances = zlights.point.distances, spotColors = zlights.spot.colors, spotPositions = zlights.spot.positions, spotDistances = zlights.spot.distances, spotDirections = zlights.spot.directions, spotAnglesCos = zlights.spot.anglesCos, spotExponents = zlights.spot.exponents, hemiSkyColors = zlights.hemi.skyColors, hemiGroundColors = zlights.hemi.groundColors, hemiPositions = zlights.hemi.positions, dirLength = 0, pointLength = 0, spotLength = 0, hemiLength = 0, dirCount = 0, pointCount = 0, spotCount = 0, hemiCount = 0, dirOffset = 0, pointOffset = 0, spotOffset = 0, hemiOffset = 0; for ( l = 0, ll = lights.length; l < ll; l ++ ) { light = lights[ l ]; if ( light.onlyShadow ) continue; color = light.color; intensity = light.intensity; distance = light.distance; if ( light instanceof THREE.AmbientLight ) { if ( ! light.visible ) continue; if ( _this.gammaInput ) { r += color.r * color.r; g += color.g * color.g; b += color.b * color.b; } else { r += color.r; g += color.g; b += color.b; } } else if ( light instanceof THREE.DirectionalLight ) { dirCount += 1; if ( ! light.visible ) continue; _direction.setFromMatrixPosition( light.matrixWorld ); _vector3.setFromMatrixPosition( light.target.matrixWorld ); _direction.sub( _vector3 ); _direction.normalize(); // skip lights with undefined direction // these create troubles in OpenGL (making pixel black) if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue; dirOffset = dirLength * 3; dirPositions[ dirOffset ] = _direction.x; dirPositions[ dirOffset + 1 ] = _direction.y; dirPositions[ dirOffset + 2 ] = _direction.z; if ( _this.gammaInput ) { setColorGamma( dirColors, dirOffset, color, intensity * intensity ); } else { setColorLinear( dirColors, dirOffset, color, intensity ); } dirLength += 1; } else if ( light instanceof THREE.PointLight ) { pointCount += 1; if ( ! light.visible ) continue; pointOffset = pointLength * 3; if ( _this.gammaInput ) { setColorGamma( pointColors, pointOffset, color, intensity * intensity ); } else { setColorLinear( pointColors, pointOffset, color, intensity ); } _vector3.setFromMatrixPosition( light.matrixWorld ); pointPositions[ pointOffset ] = _vector3.x; pointPositions[ pointOffset + 1 ] = _vector3.y; pointPositions[ pointOffset + 2 ] = _vector3.z; pointDistances[ pointLength ] = distance; pointLength += 1; } else if ( light instanceof THREE.SpotLight ) { spotCount += 1; if ( ! light.visible ) continue; spotOffset = spotLength * 3; if ( _this.gammaInput ) { setColorGamma( spotColors, spotOffset, color, intensity * intensity ); } else { setColorLinear( spotColors, spotOffset, color, intensity ); } _vector3.setFromMatrixPosition( light.matrixWorld ); spotPositions[ spotOffset ] = _vector3.x; spotPositions[ spotOffset + 1 ] = _vector3.y; spotPositions[ spotOffset + 2 ] = _vector3.z; spotDistances[ spotLength ] = distance; _direction.copy( _vector3 ); _vector3.setFromMatrixPosition( light.target.matrixWorld ); _direction.sub( _vector3 ); _direction.normalize(); spotDirections[ spotOffset ] = _direction.x; spotDirections[ spotOffset + 1 ] = _direction.y; spotDirections[ spotOffset + 2 ] = _direction.z; spotAnglesCos[ spotLength ] = Math.cos( light.angle ); spotExponents[ spotLength ] = light.exponent; spotLength += 1; } else if ( light instanceof THREE.HemisphereLight ) { hemiCount += 1; if ( ! light.visible ) continue; _direction.setFromMatrixPosition( light.matrixWorld ); _direction.normalize(); // skip lights with undefined direction // these create troubles in OpenGL (making pixel black) if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue; hemiOffset = hemiLength * 3; hemiPositions[ hemiOffset ] = _direction.x; hemiPositions[ hemiOffset + 1 ] = _direction.y; hemiPositions[ hemiOffset + 2 ] = _direction.z; skyColor = light.color; groundColor = light.groundColor; if ( _this.gammaInput ) { intensitySq = intensity * intensity; setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq ); setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq ); } else { setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity ); setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity ); } hemiLength += 1; } } // null eventual remains from removed lights // (this is to avoid if in shader) for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0; for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0; for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0; for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0; for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0; zlights.directional.length = dirLength; zlights.point.length = pointLength; zlights.spot.length = spotLength; zlights.hemi.length = hemiLength; zlights.ambient[ 0 ] = r; zlights.ambient[ 1 ] = g; zlights.ambient[ 2 ] = b; }; // GL state setting this.setFaceCulling = function ( cullFace, frontFaceDirection ) { if ( cullFace === THREE.CullFaceNone ) { _gl.disable( _gl.CULL_FACE ); } else { if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) { _gl.frontFace( _gl.CW ); } else { _gl.frontFace( _gl.CCW ); } if ( cullFace === THREE.CullFaceBack ) { _gl.cullFace( _gl.BACK ); } else if ( cullFace === THREE.CullFaceFront ) { _gl.cullFace( _gl.FRONT ); } else { _gl.cullFace( _gl.FRONT_AND_BACK ); } _gl.enable( _gl.CULL_FACE ); } }; this.setMaterialFaces = function ( material ) { var doubleSided = material.side === THREE.DoubleSide; var flipSided = material.side === THREE.BackSide; if ( _oldDoubleSided !== doubleSided ) { if ( doubleSided ) { _gl.disable( _gl.CULL_FACE ); } else { _gl.enable( _gl.CULL_FACE ); } _oldDoubleSided = doubleSided; } if ( _oldFlipSided !== flipSided ) { if ( flipSided ) { _gl.frontFace( _gl.CW ); } else { _gl.frontFace( _gl.CCW ); } _oldFlipSided = flipSided; } }; this.setDepthTest = function ( depthTest ) { if ( _oldDepthTest !== depthTest ) { if ( depthTest ) { _gl.enable( _gl.DEPTH_TEST ); } else { _gl.disable( _gl.DEPTH_TEST ); } _oldDepthTest = depthTest; } }; this.setDepthWrite = function ( depthWrite ) { if ( _oldDepthWrite !== depthWrite ) { _gl.depthMask( depthWrite ); _oldDepthWrite = depthWrite; } }; function setLineWidth ( width ) { if ( width !== _oldLineWidth ) { _gl.lineWidth( width ); _oldLineWidth = width; } }; function setPolygonOffset ( polygonoffset, factor, units ) { if ( _oldPolygonOffset !== polygonoffset ) { if ( polygonoffset ) { _gl.enable( _gl.POLYGON_OFFSET_FILL ); } else { _gl.disable( _gl.POLYGON_OFFSET_FILL ); } _oldPolygonOffset = polygonoffset; } if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) { _gl.polygonOffset( factor, units ); _oldPolygonOffsetFactor = factor; _oldPolygonOffsetUnits = units; } }; this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) { if ( blending !== _oldBlending ) { if ( blending === THREE.NoBlending ) { _gl.disable( _gl.BLEND ); } else if ( blending === THREE.AdditiveBlending ) { _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); } else if ( blending === THREE.SubtractiveBlending ) { // TODO: Find blendFuncSeparate() combination _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR ); } else if ( blending === THREE.MultiplyBlending ) { // TODO: Find blendFuncSeparate() combination _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR ); } else if ( blending === THREE.CustomBlending ) { _gl.enable( _gl.BLEND ); } else { _gl.enable( _gl.BLEND ); _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD ); _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA ); } _oldBlending = blending; } if ( blending === THREE.CustomBlending ) { if ( blendEquation !== _oldBlendEquation ) { _gl.blendEquation( paramThreeToGL( blendEquation ) ); _oldBlendEquation = blendEquation; } if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) { _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) ); _oldBlendSrc = blendSrc; _oldBlendDst = blendDst; } } else { _oldBlendEquation = null; _oldBlendSrc = null; _oldBlendDst = null; } }; // Defines function generateDefines ( defines ) { var value, chunk, chunks = []; for ( var d in defines ) { value = defines[ d ]; if ( value === false ) continue; chunk = "#define " + d + " " + value; chunks.push( chunk ); } return chunks.join( "\n" ); }; // Shaders function buildProgram( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) { var p, pl, d, program, code; var chunks = []; // Generate code if ( shaderID ) { chunks.push( shaderID ); } else { chunks.push( fragmentShader ); chunks.push( vertexShader ); } for ( d in defines ) { chunks.push( d ); chunks.push( defines[ d ] ); } for ( p in parameters ) { chunks.push( p ); chunks.push( parameters[ p ] ); } code = chunks.join(); // Check if code has been already compiled for ( p = 0, pl = _programs.length; p < pl; p ++ ) { var programInfo = _programs[ p ]; if ( programInfo.code === code ) { // console.log( "Code already compiled." /*: \n\n" + code*/ ); programInfo.usedTimes ++; return programInfo.program; } } var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; if ( parameters.shadowMapType === THREE.PCFShadowMap ) { shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) { shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; } // console.log( "building new program " ); // var customDefines = generateDefines( defines ); // program = _gl.createProgram(); var prefix_vertex = [ "precision " + _precision + " float;", "precision " + _precision + " int;", customDefines, _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "", _this.gammaInput ? "#define GAMMA_INPUT" : "", _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, "#define MAX_SHADOWS " + parameters.maxShadows, "#define MAX_BONES " + parameters.maxBones, parameters.map ? "#define USE_MAP" : "", parameters.envMap ? "#define USE_ENVMAP" : "", parameters.lightMap ? "#define USE_LIGHTMAP" : "", parameters.bumpMap ? "#define USE_BUMPMAP" : "", parameters.normalMap ? "#define USE_NORMALMAP" : "", parameters.specularMap ? "#define USE_SPECULARMAP" : "", parameters.vertexColors ? "#define USE_COLOR" : "", parameters.skinning ? "#define USE_SKINNING" : "", parameters.useVertexTexture ? "#define BONE_TEXTURE" : "", parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", parameters.morphNormals ? "#define USE_MORPHNORMALS" : "", parameters.wrapAround ? "#define WRAP_AROUND" : "", parameters.doubleSided ? "#define DOUBLE_SIDED" : "", parameters.flipSided ? "#define FLIP_SIDED" : "", parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", "uniform mat4 modelMatrix;", "uniform mat4 modelViewMatrix;", "uniform mat4 projectionMatrix;", "uniform mat4 viewMatrix;", "uniform mat3 normalMatrix;", "uniform vec3 cameraPosition;", "attribute vec3 position;", "attribute vec3 normal;", "attribute vec2 uv;", "attribute vec2 uv2;", "#ifdef USE_COLOR", "attribute vec3 color;", "#endif", "#ifdef USE_MORPHTARGETS", "attribute vec3 morphTarget0;", "attribute vec3 morphTarget1;", "attribute vec3 morphTarget2;", "attribute vec3 morphTarget3;", "#ifdef USE_MORPHNORMALS", "attribute vec3 morphNormal0;", "attribute vec3 morphNormal1;", "attribute vec3 morphNormal2;", "attribute vec3 morphNormal3;", "#else", "attribute vec3 morphTarget4;", "attribute vec3 morphTarget5;", "attribute vec3 morphTarget6;", "attribute vec3 morphTarget7;", "#endif", "#endif", "#ifdef USE_SKINNING", "attribute vec4 skinIndex;", "attribute vec4 skinWeight;", "#endif", "" ].join("\n"); var prefix_fragment = [ "precision " + _precision + " float;", "precision " + _precision + " int;", ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "", customDefines, "#define MAX_DIR_LIGHTS " + parameters.maxDirLights, "#define MAX_POINT_LIGHTS " + parameters.maxPointLights, "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights, "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights, "#define MAX_SHADOWS " + parameters.maxShadows, parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "", _this.gammaInput ? "#define GAMMA_INPUT" : "", _this.gammaOutput ? "#define GAMMA_OUTPUT" : "", ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "", ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "", parameters.map ? "#define USE_MAP" : "", parameters.envMap ? "#define USE_ENVMAP" : "", parameters.lightMap ? "#define USE_LIGHTMAP" : "", parameters.bumpMap ? "#define USE_BUMPMAP" : "", parameters.normalMap ? "#define USE_NORMALMAP" : "", parameters.specularMap ? "#define USE_SPECULARMAP" : "", parameters.vertexColors ? "#define USE_COLOR" : "", parameters.metal ? "#define METAL" : "", parameters.wrapAround ? "#define WRAP_AROUND" : "", parameters.doubleSided ? "#define DOUBLE_SIDED" : "", parameters.flipSided ? "#define FLIP_SIDED" : "", parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "", parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "", "uniform mat4 viewMatrix;", "uniform vec3 cameraPosition;", "" ].join("\n"); var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader ); var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader ); _gl.attachShader( program, glVertexShader ); _gl.attachShader( program, glFragmentShader ); // Force a particular attribute to index 0. // because potentially expensive emulation is done by browser if attribute 0 is disabled. // And, color, for example is often automatically bound to index 0 so disabling it if ( index0AttributeName !== undefined ) { _gl.bindAttribLocation( program, 0, index0AttributeName ); } _gl.linkProgram( program ); if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) { console.error( 'Could not initialise shader' ); console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) ); console.error( 'gl.getError()', _gl.getError() ); } if ( _gl.getProgramInfoLog( program ) !== '' ) { console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) ); } // clean up _gl.deleteShader( glFragmentShader ); _gl.deleteShader( glVertexShader ); // console.log( prefix_fragment + fragmentShader ); // console.log( prefix_vertex + vertexShader ); program.uniforms = {}; program.attributes = {}; var identifiers, u, a, i; // cache uniform locations identifiers = [ 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition', 'morphTargetInfluences' ]; if ( parameters.useVertexTexture ) { identifiers.push( 'boneTexture' ); identifiers.push( 'boneTextureWidth' ); identifiers.push( 'boneTextureHeight' ); } else { identifiers.push( 'boneGlobalMatrices' ); } for ( u in uniforms ) { identifiers.push( u ); } cacheUniformLocations( program, identifiers ); // cache attributes locations identifiers = [ "position", "normal", "uv", "uv2", "tangent", "color", "skinIndex", "skinWeight", "lineDistance" ]; for ( i = 0; i < parameters.maxMorphTargets; i ++ ) { identifiers.push( "morphTarget" + i ); } for ( i = 0; i < parameters.maxMorphNormals; i ++ ) { identifiers.push( "morphNormal" + i ); } for ( a in attributes ) { identifiers.push( a ); } cacheAttributeLocations( program, identifiers ); program.id = _programs_counter ++; _programs.push( { program: program, code: code, usedTimes: 1 } ); _this.info.memory.programs = _programs.length; return program; }; // Shader parameters cache function cacheUniformLocations ( program, identifiers ) { var i, l, id; for( i = 0, l = identifiers.length; i < l; i ++ ) { id = identifiers[ i ]; program.uniforms[ id ] = _gl.getUniformLocation( program, id ); } }; function cacheAttributeLocations ( program, identifiers ) { var i, l, id; for( i = 0, l = identifiers.length; i < l; i ++ ) { id = identifiers[ i ]; program.attributes[ id ] = _gl.getAttribLocation( program, id ); } }; function addLineNumbers ( string ) { var chunks = string.split( "\n" ); for ( var i = 0, il = chunks.length; i < il; i ++ ) { // Chrome reports shader errors on lines // starting counting from 1 chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ]; } return chunks.join( "\n" ); }; function getShader ( type, string ) { var shader; if ( type === "fragment" ) { shader = _gl.createShader( _gl.FRAGMENT_SHADER ); } else if ( type === "vertex" ) { shader = _gl.createShader( _gl.VERTEX_SHADER ); } _gl.shaderSource( shader, string ); _gl.compileShader( shader ); if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) { console.error( _gl.getShaderInfoLog( shader ) ); console.error( addLineNumbers( string ) ); return null; } return shader; }; // Textures function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) { if ( isImagePowerOfTwo ) { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) ); } else { _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE ); _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE ); _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) ); _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) ); } if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) { if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) { _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) ); texture.__oldAnisotropy = texture.anisotropy; } } }; this.setTexture = function ( texture, slot ) { if ( texture.needsUpdate ) { if ( ! texture.__webglInit ) { texture.__webglInit = true; texture.addEventListener( 'dispose', onTextureDispose ); texture.__webglTexture = _gl.createTexture(); _this.info.memory.textures ++; } _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha ); _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment ); var image = texture.image, isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), glFormat = paramThreeToGL( texture.format ), glType = paramThreeToGL( texture.type ); setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo ); var mipmap, mipmaps = texture.mipmaps; if ( texture instanceof THREE.DataTexture ) { // use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if ( mipmaps.length > 0 && isImagePowerOfTwo ) { for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } texture.generateMipmaps = false; } else { _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data ); } } else if ( texture instanceof THREE.CompressedTexture ) { for( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; if ( texture.format!==THREE.RGBAFormat ) { _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); } else { _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } } } else { // regular Texture (image, video, canvas) // use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if ( mipmaps.length > 0 && isImagePowerOfTwo ) { for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap ); } texture.generateMipmaps = false; } else { _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image ); } } if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); texture.needsUpdate = false; if ( texture.onUpdate ) texture.onUpdate(); } else { _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture ); } }; function clampToMaxSize ( image, maxSize ) { if ( image.width <= maxSize && image.height <= maxSize ) { return image; } // Warning: Scaling through the canvas will only work with images that use // premultiplied alpha. var maxDimension = Math.max( image.width, image.height ); var newWidth = Math.floor( image.width * maxSize / maxDimension ); var newHeight = Math.floor( image.height * maxSize / maxDimension ); var canvas = document.createElement( 'canvas' ); canvas.width = newWidth; canvas.height = newHeight; var ctx = canvas.getContext( "2d" ); ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight ); return canvas; } function setCubeTexture ( texture, slot ) { if ( texture.image.length === 6 ) { if ( texture.needsUpdate ) { if ( ! texture.image.__webglTextureCube ) { texture.addEventListener( 'dispose', onTextureDispose ); texture.image.__webglTextureCube = _gl.createTexture(); _this.info.memory.textures ++; } _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY ); var isCompressed = texture instanceof THREE.CompressedTexture; var cubeImage = []; for ( var i = 0; i < 6; i ++ ) { if ( _this.autoScaleCubemaps && ! isCompressed ) { cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize ); } else { cubeImage[ i ] = texture.image[ i ]; } } var image = cubeImage[ 0 ], isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ), glFormat = paramThreeToGL( texture.format ), glType = paramThreeToGL( texture.type ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo ); for ( var i = 0; i < 6; i ++ ) { if( !isCompressed ) { _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] ); } else { var mipmap, mipmaps = cubeImage[ i ].mipmaps; for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) { mipmap = mipmaps[ j ]; if ( texture.format!==THREE.RGBAFormat ) { _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data ); } else { _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } } } } if ( texture.generateMipmaps && isImagePowerOfTwo ) { _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); } texture.needsUpdate = false; if ( texture.onUpdate ) texture.onUpdate(); } else { _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube ); } } }; function setCubeTextureDynamic ( texture, slot ) { _gl.activeTexture( _gl.TEXTURE0 + slot ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture ); }; // Render targets function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 ); }; function setupRenderBuffer ( renderbuffer, renderTarget ) { _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer ); if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); /* For some reason this is not working. Defaulting to RGBA4. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); */ } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height ); _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer ); } else { _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height ); } }; this.setRenderTarget = function ( renderTarget ) { var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube ); if ( renderTarget && ! renderTarget.__webglFramebuffer ) { if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true; if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true; renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); renderTarget.__webglTexture = _gl.createTexture(); _this.info.memory.textures ++; // Setup texture, create render and frame buffers var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ), glFormat = paramThreeToGL( renderTarget.format ), glType = paramThreeToGL( renderTarget.type ); if ( isCube ) { renderTarget.__webglFramebuffer = []; renderTarget.__webglRenderbuffer = []; _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo ); for ( var i = 0; i < 6; i ++ ) { renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer(); renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer(); _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget ); } if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); } else { renderTarget.__webglFramebuffer = _gl.createFramebuffer(); if ( renderTarget.shareDepthFrom ) { renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer; } else { renderTarget.__webglRenderbuffer = _gl.createRenderbuffer(); } _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo ); _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D ); if ( renderTarget.shareDepthFrom ) { if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer ); } } else { setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget ); } if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D ); } // Release everything if ( isCube ) { _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); } else { _gl.bindTexture( _gl.TEXTURE_2D, null ); } _gl.bindRenderbuffer( _gl.RENDERBUFFER, null ); _gl.bindFramebuffer( _gl.FRAMEBUFFER, null ); } var framebuffer, width, height, vx, vy; if ( renderTarget ) { if ( isCube ) { framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ]; } else { framebuffer = renderTarget.__webglFramebuffer; } width = renderTarget.width; height = renderTarget.height; vx = 0; vy = 0; } else { framebuffer = null; width = _viewportWidth; height = _viewportHeight; vx = _viewportX; vy = _viewportY; } if ( framebuffer !== _currentFramebuffer ) { _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer ); _gl.viewport( vx, vy, width, height ); _currentFramebuffer = framebuffer; } _currentWidth = width; _currentHeight = height; }; function updateRenderTargetMipmap ( renderTarget ) { if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) { _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture ); _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP ); _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null ); } else { _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture ); _gl.generateMipmap( _gl.TEXTURE_2D ); _gl.bindTexture( _gl.TEXTURE_2D, null ); } }; // Fallback filters for non-power-of-2 textures function filterFallback ( f ) { if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) { return _gl.NEAREST; } return _gl.LINEAR; }; // Map three.js constants to WebGL constants function paramThreeToGL ( p ) { if ( p === THREE.RepeatWrapping ) return _gl.REPEAT; if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE; if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT; if ( p === THREE.NearestFilter ) return _gl.NEAREST; if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST; if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR; if ( p === THREE.LinearFilter ) return _gl.LINEAR; if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST; if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR; if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE; if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4; if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1; if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5; if ( p === THREE.ByteType ) return _gl.BYTE; if ( p === THREE.ShortType ) return _gl.SHORT; if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT; if ( p === THREE.IntType ) return _gl.INT; if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT; if ( p === THREE.FloatType ) return _gl.FLOAT; if ( p === THREE.AlphaFormat ) return _gl.ALPHA; if ( p === THREE.RGBFormat ) return _gl.RGB; if ( p === THREE.RGBAFormat ) return _gl.RGBA; if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE; if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA; if ( p === THREE.AddEquation ) return _gl.FUNC_ADD; if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT; if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT; if ( p === THREE.ZeroFactor ) return _gl.ZERO; if ( p === THREE.OneFactor ) return _gl.ONE; if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR; if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR; if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA; if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA; if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA; if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA; if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR; if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR; if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE; if ( _glExtensionCompressedTextureS3TC !== undefined ) { if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT; if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT; if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT; if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT; } return 0; }; // Allocations function allocateBones ( object ) { if ( _supportsBoneTextures && object && object.useVertexTexture ) { return 1024; } else { // default for when object is not specified // ( for example when prebuilding shader // to be used with multiple objects ) // // - leave some extra space for other uniforms // - limit here is ANGLE's 254 max uniform vectors // (up to 54 should be safe) var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ); var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); var maxBones = nVertexMatrices; if ( object !== undefined && object instanceof THREE.SkinnedMesh ) { maxBones = Math.min( object.bones.length, maxBones ); if ( maxBones < object.bones.length ) { console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" ); } } return maxBones; } }; function allocateLights( lights ) { var dirLights = 0; var pointLights = 0; var spotLights = 0; var hemiLights = 0; for ( var l = 0, ll = lights.length; l < ll; l ++ ) { var light = lights[ l ]; if ( light.onlyShadow || light.visible === false ) continue; if ( light instanceof THREE.DirectionalLight ) dirLights ++; if ( light instanceof THREE.PointLight ) pointLights ++; if ( light instanceof THREE.SpotLight ) spotLights ++; if ( light instanceof THREE.HemisphereLight ) hemiLights ++; } return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights }; }; function allocateShadows( lights ) { var maxShadows = 0; for ( var l = 0, ll = lights.length; l < ll; l++ ) { var light = lights[ l ]; if ( ! light.castShadow ) continue; if ( light instanceof THREE.SpotLight ) maxShadows ++; if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++; } return maxShadows; }; // Initialization function initGL() { try { var attributes = { alpha: _alpha, depth: _depth, stencil: _stencil, antialias: _antialias, premultipliedAlpha: _premultipliedAlpha, preserveDrawingBuffer: _preserveDrawingBuffer }; _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes ); if ( _gl === null ) { throw 'Error creating WebGL context.'; } } catch ( error ) { console.error( error ); } _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' ); _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' ); _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' ); _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' ); if ( _glExtensionTextureFloat === null ) { console.log( 'THREE.WebGLRenderer: Float textures not supported.' ); } if ( _glExtensionStandardDerivatives === null ) { console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' ); } if ( _glExtensionTextureFilterAnisotropic === null ) { console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' ); } if ( _glExtensionCompressedTextureS3TC === null ) { console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' ); } if ( _glExtensionElementIndexUint === null ) { console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' ); } if ( _gl.getShaderPrecisionFormat === undefined ) { _gl.getShaderPrecisionFormat = function() { return { "rangeMin" : 1, "rangeMax" : 1, "precision" : 1 }; } } }; function setDefaultGLState () { _gl.clearColor( 0, 0, 0, 1 ); _gl.clearDepth( 1 ); _gl.clearStencil( 0 ); _gl.enable( _gl.DEPTH_TEST ); _gl.depthFunc( _gl.LEQUAL ); _gl.frontFace( _gl.CCW ); _gl.cullFace( _gl.BACK ); _gl.enable( _gl.CULL_FACE ); _gl.enable( _gl.BLEND ); _gl.blendEquation( _gl.FUNC_ADD ); _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA ); _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight ); _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha ); }; // default plugins (order is important) this.shadowMapPlugin = new THREE.ShadowMapPlugin(); this.addPrePlugin( this.shadowMapPlugin ); this.addPostPlugin( new THREE.SpritePlugin() ); this.addPostPlugin( new THREE.LensFlarePlugin() ); };
WebGLRenderer: Fixed disableAttributes disabling strings instead of integers.
src/renderers/WebGLRenderer.js
WebGLRenderer: Fixed disableAttributes disabling strings instead of integers.
<ide><path>rc/renderers/WebGLRenderer.js <ide> <ide> function disableAttributes() { <ide> <del> for ( var attribute in _enabledAttributes ) { <del> <del> if ( _enabledAttributes[ attribute ] === 1 ) { <del> <del> _gl.disableVertexAttribArray( attribute ); <del> _enabledAttributes[ attribute ] = 0; <add> for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) { <add> <add> if ( _enabledAttributes[ i ] === 1 ) { <add> <add> _gl.disableVertexAttribArray( i ); <add> _enabledAttributes[ i ] = 0; <ide> <ide> } <ide>
Java
apache-2.0
d18258fecf7ff48fcec540812d6dd140bd69a5b0
0
phax/ph-commons
/** * Copyright (C) 2014-2015 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.commons.xml.serialize.write; import java.nio.charset.Charset; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import javax.xml.namespace.NamespaceContext; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Nonempty; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.charset.CCharset; import com.helger.commons.charset.CharsetManager; import com.helger.commons.equals.EqualsHelper; import com.helger.commons.hashcode.HashCodeGenerator; import com.helger.commons.lang.ICloneable; import com.helger.commons.string.StringHelper; import com.helger.commons.string.ToStringGenerator; import com.helger.commons.system.ENewLineMode; import com.helger.commons.xml.EXMLVersion; import com.helger.commons.xml.namespace.MapBasedNamespaceContext; /** * Default implementation of the {@link IXMLWriterSettings} interface.<br> * Describes the export settings for the MicroWriter. Defaults to indented and * aligned XML in the UTF-8 charset. * * @author Philip Helger */ @NotThreadSafe public class XMLWriterSettings implements IXMLWriterSettings, ICloneable <XMLWriterSettings> { // Must be before the IXMLWriterSettings constants! /** The default charset is UTF-8 */ public static final String DEFAULT_XML_CHARSET = CCharset.CHARSET_UTF_8; /** The default charset is UTF-8 */ public static final Charset DEFAULT_XML_CHARSET_OBJ = CCharset.CHARSET_UTF_8_OBJ; /** By default double quotes are used to wrap attribute values */ public static final boolean DEFAULT_USE_DOUBLE_QUOTES_FOR_ATTRIBUTES = true; /** * By default a leading space is inserted before a self closed element (e.g. * <code>&lt;b /&gt;</code> in contrast to <code>&lt;b/&gt;</code>). */ public static final boolean DEFAULT_SPACE_ON_SELF_CLOSED_ELEMENT = true; /** By default indentation happens with 2 spaces */ public static final String DEFAULT_INDENTATION_STRING = " "; /** * By default namespaces are written. */ public static final boolean DEFAULT_EMIT_NAMESPACES = true; /** * By default namespace context prefixes are not put inside the root element * (for backwards compatibility) */ public static final boolean DEFAULT_PUT_NAMESPACE_CONTEXT_PREFIXES_IN_ROOT = false; /** The default settings to use */ public static final IXMLWriterSettings DEFAULT_XML_SETTINGS = new XMLWriterSettings (); private EXMLVersion m_eXMLVersion = EXMLVersion.XML_10; private EXMLSerializeVersion m_eSerializeVersion = EXMLSerializeVersion.XML_10; private EXMLSerializeXMLDeclaration m_eSerializeXMLDecl = EXMLSerializeXMLDeclaration.EMIT; private EXMLSerializeDocType m_eSerializeDocType = EXMLSerializeDocType.EMIT; private EXMLSerializeComments m_eSerializeComments = EXMLSerializeComments.EMIT; private EXMLSerializeIndent m_eIndent = EXMLSerializeIndent.INDENT_AND_ALIGN; private IXMLIndentDeterminator m_aIndentDeterminator = new XMLIndentDeterminatorXML (); private EXMLIncorrectCharacterHandling m_eIncorrectCharacterHandling = EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING; private Charset m_aCharset = DEFAULT_XML_CHARSET_OBJ; private NamespaceContext m_aNamespaceContext = new MapBasedNamespaceContext (); private boolean m_bUseDoubleQuotesForAttributes = DEFAULT_USE_DOUBLE_QUOTES_FOR_ATTRIBUTES; private IXMLBracketModeDeterminator m_aBracketModeDeterminator = new XMLBracketModeDeterminatorXML (); private boolean m_bSpaceOnSelfClosedElement = DEFAULT_SPACE_ON_SELF_CLOSED_ELEMENT; private ENewLineMode m_eNewLineMode = ENewLineMode.DEFAULT; private String m_sIndentationString = DEFAULT_INDENTATION_STRING; private boolean m_bEmitNamespaces = DEFAULT_EMIT_NAMESPACES; private boolean m_bPutNamespaceContextPrefixesInRoot = DEFAULT_PUT_NAMESPACE_CONTEXT_PREFIXES_IN_ROOT; // Status vars private String m_sIndentationStringToString; /** * Creates a default settings object with the following settings: * <ul> * <li>XML version 1.0</li> * <li>with XML declaration</li> * <li>with document type</li> * <li>with comments</li> * <li>Indented and aligned</li> * <li>Writing invalid characters to the file as is - may result in invalid * XML files</li> * <li>Default character set UTF-8</li> * <li>No namespace context</li> * </ul> */ public XMLWriterSettings () {} /** * Copy constructor. * * @param aOther * The object to copy the settings from. May not be <code>null</code>. */ public XMLWriterSettings (@Nonnull final IXMLWriterSettings aOther) { ValueEnforcer.notNull (aOther, "Other"); setSerializeVersion (aOther.getSerializeVersion ()); setSerializeXMLDeclaration (aOther.getSerializeXMLDeclaration ()); setSerializeDocType (aOther.getSerializeDocType ()); setSerializeComments (aOther.getSerializeComments ()); setIndent (aOther.getIndent ()); setIndentDeterminator (aOther.getIndentDeterminator ()); setIncorrectCharacterHandling (aOther.getIncorrectCharacterHandling ()); setCharset (aOther.getCharsetObj ()); setNamespaceContext (aOther.getNamespaceContext ()); setBracketModeDeterminator (aOther.getBracketModeDeterminator ()); setUseDoubleQuotesForAttributes (aOther.isUseDoubleQuotesForAttributes ()); setSpaceOnSelfClosedElement (aOther.isSpaceOnSelfClosedElement ()); setNewLineMode (aOther.getNewLineMode ()); setIndentationString (aOther.getIndentationString ()); setEmitNamespaces (aOther.isEmitNamespaces ()); setPutNamespaceContextPrefixesInRoot (aOther.isPutNamespaceContextPrefixesInRoot ()); } @Nonnull public EXMLVersion getXMLVersion () { return m_eXMLVersion; } /** * Set the preferred XML version to use. * * @param eSerializeVersion * The XML serialize version. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setSerializeVersion (@Nonnull final EXMLSerializeVersion eSerializeVersion) { m_eSerializeVersion = ValueEnforcer.notNull (eSerializeVersion, "Version"); m_eXMLVersion = eSerializeVersion.getXMLVersionOrDefault (EXMLVersion.XML_10); return this; } @Nonnull public EXMLSerializeVersion getSerializeVersion () { return m_eSerializeVersion; } /** * Set the way how to handle the XML declaration. * * @param eSerializeXMLDecl * XML declaration handling. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setSerializeXMLDeclaration (@Nonnull final EXMLSerializeXMLDeclaration eSerializeXMLDecl) { m_eSerializeXMLDecl = ValueEnforcer.notNull (eSerializeXMLDecl, "SerializeXMLDecl"); return this; } @Nonnull public EXMLSerializeXMLDeclaration getSerializeXMLDeclaration () { return m_eSerializeXMLDecl; } /** * Set the way how to handle the doc type. * * @param eSerializeDocType * Doc type handling. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setSerializeDocType (@Nonnull final EXMLSerializeDocType eSerializeDocType) { m_eSerializeDocType = ValueEnforcer.notNull (eSerializeDocType, "SerializeDocType"); return this; } @Nonnull public EXMLSerializeDocType getSerializeDocType () { return m_eSerializeDocType; } /** * Set the way how comments should be handled. * * @param eSerializeComments * The comment handling. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setSerializeComments (@Nonnull final EXMLSerializeComments eSerializeComments) { m_eSerializeComments = ValueEnforcer.notNull (eSerializeComments, "SerializeComments"); return this; } @Nonnull public EXMLSerializeComments getSerializeComments () { return m_eSerializeComments; } /** * Set the way how to indent/align * * @param eIndent * Indent and align definition. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setIndent (@Nonnull final EXMLSerializeIndent eIndent) { m_eIndent = ValueEnforcer.notNull (eIndent, "Indent"); return this; } @Nonnull public EXMLSerializeIndent getIndent () { return m_eIndent; } /** * Set the dynamic (per-element) indent determinator to be used. * * @param aIndentDeterminator * The object to use. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setIndentDeterminator (@Nonnull final IXMLIndentDeterminator aIndentDeterminator) { m_aIndentDeterminator = ValueEnforcer.notNull (aIndentDeterminator, "IndentDeterminator"); return this; } @Nonnull public IXMLIndentDeterminator getIndentDeterminator () { return m_aIndentDeterminator; } /** * Set the way how to handle invalid characters. * * @param eIncorrectCharacterHandling * The invalid character handling. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setIncorrectCharacterHandling (@Nonnull final EXMLIncorrectCharacterHandling eIncorrectCharacterHandling) { m_eIncorrectCharacterHandling = ValueEnforcer.notNull (eIncorrectCharacterHandling, "IncorrectCharacterHandling"); return this; } @Nonnull public EXMLIncorrectCharacterHandling getIncorrectCharacterHandling () { return m_eIncorrectCharacterHandling; } /** * Set the serialization charset. * * @param aCharset * The charset to be used. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setCharset (@Nonnull final Charset aCharset) { m_aCharset = ValueEnforcer.notNull (aCharset, "Charset"); return this; } @Nonnull public String getCharset () { return m_aCharset.name (); } @Nonnull public Charset getCharsetObj () { return m_aCharset; } /** * Set the namespace context to be used. * * @param aNamespaceContext * The namespace context to be used. May be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setNamespaceContext (@Nullable final NamespaceContext aNamespaceContext) { // A namespace context must always be present, to resolve default namespaces m_aNamespaceContext = aNamespaceContext != null ? aNamespaceContext : new MapBasedNamespaceContext (); return this; } @Nonnull public NamespaceContext getNamespaceContext () { return m_aNamespaceContext; } @Nonnull public final XMLWriterSettings setUseDoubleQuotesForAttributes (final boolean bUseDoubleQuotesForAttributes) { m_bUseDoubleQuotesForAttributes = bUseDoubleQuotesForAttributes; return this; } public boolean isUseDoubleQuotesForAttributes () { return m_bUseDoubleQuotesForAttributes; } @Nonnull public final XMLWriterSettings setBracketModeDeterminator (@Nonnull final IXMLBracketModeDeterminator aBracketModeDeterminator) { ValueEnforcer.notNull (aBracketModeDeterminator, "BracketModeDeterminator"); m_aBracketModeDeterminator = aBracketModeDeterminator; return this; } @Nonnull public IXMLBracketModeDeterminator getBracketModeDeterminator () { return m_aBracketModeDeterminator; } @Nonnull public final XMLWriterSettings setSpaceOnSelfClosedElement (final boolean bSpaceOnSelfClosedElement) { m_bSpaceOnSelfClosedElement = bSpaceOnSelfClosedElement; return this; } public boolean isSpaceOnSelfClosedElement () { return m_bSpaceOnSelfClosedElement; } @Nonnull public final XMLWriterSettings setNewLineMode (@Nonnull final ENewLineMode eNewLineMode) { m_eNewLineMode = ValueEnforcer.notNull (eNewLineMode, "NewLineMode"); return this; } @Nonnull public ENewLineMode getNewLineMode () { return m_eNewLineMode; } @Nonnull @Nonempty public String getNewLineString () { return m_eNewLineMode.getText (); } @Nonnull public final XMLWriterSettings setIndentationString (@Nonnull @Nonempty final String sIndentationString) { m_sIndentationString = ValueEnforcer.notEmpty (sIndentationString, "IndentationString"); m_sIndentationStringToString = null; return this; } @Nonnull @Nonempty public String getIndentationString () { return m_sIndentationString; } @Nonnull public final XMLWriterSettings setEmitNamespaces (final boolean bEmitNamespaces) { m_bEmitNamespaces = bEmitNamespaces; return this; } public boolean isEmitNamespaces () { return m_bEmitNamespaces; } @Nonnull public final XMLWriterSettings setPutNamespaceContextPrefixesInRoot (final boolean bPutNamespaceContextPrefixesInRoot) { m_bPutNamespaceContextPrefixesInRoot = bPutNamespaceContextPrefixesInRoot; return this; } public boolean isPutNamespaceContextPrefixesInRoot () { return m_bPutNamespaceContextPrefixesInRoot; } @Nonnull public XMLWriterSettings getClone () { return new XMLWriterSettings (this); } @Override public boolean equals (final Object o) { if (o == this) return true; if (o == null || !getClass ().equals (o.getClass ())) return false; final XMLWriterSettings rhs = (XMLWriterSettings) o; // namespace context does not necessarily implement equals/hashCode return m_eXMLVersion.equals (rhs.m_eXMLVersion) && m_eSerializeXMLDecl.equals (rhs.m_eSerializeXMLDecl) && m_eSerializeDocType.equals (rhs.m_eSerializeDocType) && m_eSerializeComments.equals (rhs.m_eSerializeComments) && m_eIndent.equals (rhs.m_eIndent) && m_aIndentDeterminator.equals (rhs.m_aIndentDeterminator) && m_eIncorrectCharacterHandling.equals (rhs.m_eIncorrectCharacterHandling) && m_aCharset.equals (rhs.m_aCharset) && EqualsHelper.equals (m_aNamespaceContext, rhs.m_aNamespaceContext) && m_bUseDoubleQuotesForAttributes == rhs.m_bUseDoubleQuotesForAttributes && m_aBracketModeDeterminator.equals (rhs.m_aBracketModeDeterminator) && m_bSpaceOnSelfClosedElement == rhs.m_bSpaceOnSelfClosedElement && m_eNewLineMode.equals (rhs.m_eNewLineMode) && m_sIndentationString.equals (rhs.m_sIndentationString) && m_bEmitNamespaces == rhs.m_bEmitNamespaces && m_bPutNamespaceContextPrefixesInRoot == rhs.m_bPutNamespaceContextPrefixesInRoot; } @Override public int hashCode () { // namespace context does not necessarily implement equals/hashCode return new HashCodeGenerator (this).append (m_eXMLVersion) .append (m_eSerializeXMLDecl) .append (m_eSerializeDocType) .append (m_eSerializeComments) .append (m_eIndent) .append (m_aIndentDeterminator) .append (m_eIncorrectCharacterHandling) .append (m_aCharset) .append (m_aNamespaceContext) .append (m_bUseDoubleQuotesForAttributes) .append (m_aBracketModeDeterminator) .append (m_bSpaceOnSelfClosedElement) .append (m_eNewLineMode) .append (m_sIndentationString) .append (m_bEmitNamespaces) .append (m_bPutNamespaceContextPrefixesInRoot) .getHashCode (); } @Override public String toString () { if (m_sIndentationStringToString == null) m_sIndentationStringToString = StringHelper.getHexEncoded (CharsetManager.getAsBytes (m_sIndentationString, CCharset.CHARSET_ISO_8859_1_OBJ)); return new ToStringGenerator (this).append ("xmlVersion", m_eXMLVersion) .append ("serializeXMLDecl", m_eSerializeXMLDecl) .append ("serializeDocType", m_eSerializeDocType) .append ("serializeComments", m_eSerializeComments) .append ("indent", m_eIndent) .append ("indentDeterminator", m_aIndentDeterminator) .append ("incorrectCharHandling", m_eIncorrectCharacterHandling) .append ("charset", m_aCharset) .append ("namespaceContext", m_aNamespaceContext) .append ("doubleQuotesForAttrs", m_bUseDoubleQuotesForAttributes) .append ("bracketModeDeterminator", m_aBracketModeDeterminator) .append ("spaceOnSelfClosedElement", m_bSpaceOnSelfClosedElement) .append ("newlineMode", m_eNewLineMode) .append ("indentationString", m_sIndentationStringToString) .append ("emitNamespaces", m_bEmitNamespaces) .append ("putNamespaceContextPrefixesInRoot", m_bPutNamespaceContextPrefixesInRoot) .toString (); } @Nonnull @ReturnsMutableCopy public static XMLWriterSettings createForHTML4 () { return new XMLWriterSettings ().setSerializeVersion (EXMLSerializeVersion.HTML) .setSerializeXMLDeclaration (EXMLSerializeXMLDeclaration.IGNORE) .setIndentDeterminator (new XMLIndentDeterminatorHTML ()) .setBracketModeDeterminator (new XMLBracketModeDeterminatorHTML4 ()) .setSpaceOnSelfClosedElement (true) .setPutNamespaceContextPrefixesInRoot (true); } @Nonnull @ReturnsMutableCopy public static XMLWriterSettings createForXHTML () { return new XMLWriterSettings ().setSerializeVersion (EXMLSerializeVersion.HTML) .setSerializeXMLDeclaration (EXMLSerializeXMLDeclaration.IGNORE) .setIndentDeterminator (new XMLIndentDeterminatorHTML ()) .setBracketModeDeterminator (new XMLBracketModeDeterminatorXML ()) .setSpaceOnSelfClosedElement (true) .setPutNamespaceContextPrefixesInRoot (true); } @Nonnull @ReturnsMutableCopy public static XMLWriterSettings createForHTML5 () { return new XMLWriterSettings ().setSerializeVersion (EXMLSerializeVersion.HTML) .setSerializeXMLDeclaration (EXMLSerializeXMLDeclaration.IGNORE) .setIndentDeterminator (new XMLIndentDeterminatorHTML ()) .setBracketModeDeterminator (new XMLBracketModeDeterminatorHTML5 ()) .setSpaceOnSelfClosedElement (true) .setPutNamespaceContextPrefixesInRoot (true); } }
src/main/java/com/helger/commons/xml/serialize/write/XMLWriterSettings.java
/** * Copyright (C) 2014-2015 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.commons.xml.serialize.write; import java.nio.charset.Charset; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import javax.xml.namespace.NamespaceContext; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Nonempty; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.charset.CCharset; import com.helger.commons.charset.CharsetManager; import com.helger.commons.equals.EqualsHelper; import com.helger.commons.hashcode.HashCodeGenerator; import com.helger.commons.lang.ICloneable; import com.helger.commons.string.StringHelper; import com.helger.commons.string.ToStringGenerator; import com.helger.commons.system.ENewLineMode; import com.helger.commons.xml.EXMLVersion; import com.helger.commons.xml.namespace.MapBasedNamespaceContext; /** * Default implementation of the {@link IXMLWriterSettings} interface.<br> * Describes the export settings for the MicroWriter. Defaults to indented and * aligned XML in the UTF-8 charset. * * @author Philip Helger */ @NotThreadSafe public class XMLWriterSettings implements IXMLWriterSettings, ICloneable <XMLWriterSettings> { // Must be before the IXMLWriterSettings constants! /** The default charset is UTF-8 */ public static final String DEFAULT_XML_CHARSET = CCharset.CHARSET_UTF_8; /** The default charset is UTF-8 */ public static final Charset DEFAULT_XML_CHARSET_OBJ = CCharset.CHARSET_UTF_8_OBJ; /** By default double quotes are used to wrap attribute values */ public static final boolean DEFAULT_USE_DOUBLE_QUOTES_FOR_ATTRIBUTES = true; /** * By default a leading space is inserted before a self closed element (e.g. * <code>&lt;b /&gt;</code> in contrast to <code>&lt;b/&gt;</code>). */ public static final boolean DEFAULT_SPACE_ON_SELF_CLOSED_ELEMENT = true; /** By default indentation happens with 2 spaces */ public static final String DEFAULT_INDENTATION_STRING = " "; /** * By default namespaces are written. */ public static final boolean DEFAULT_EMIT_NAMESPACES = true; /** * By default namespace context prefixes are not put inside the root element * (for backwards compatibility) */ public static final boolean DEFAULT_PUT_NAMESPACE_CONTEXT_PREFIXES_IN_ROOT = false; /** The default settings to use */ public static final IXMLWriterSettings DEFAULT_XML_SETTINGS = new XMLWriterSettings (); private EXMLVersion m_eXMLVersion = EXMLVersion.XML_10; private EXMLSerializeVersion m_eSerializeVersion = EXMLSerializeVersion.XML_10; private EXMLSerializeXMLDeclaration m_eSerializeXMLDecl = EXMLSerializeXMLDeclaration.EMIT; private EXMLSerializeDocType m_eSerializeDocType = EXMLSerializeDocType.EMIT; private EXMLSerializeComments m_eSerializeComments = EXMLSerializeComments.EMIT; private EXMLSerializeIndent m_eIndent = EXMLSerializeIndent.INDENT_AND_ALIGN; private IXMLIndentDeterminator m_aIndentDeterminator = new XMLIndentDeterminatorXML (); private EXMLIncorrectCharacterHandling m_eIncorrectCharacterHandling = EXMLIncorrectCharacterHandling.DO_NOT_WRITE_LOG_WARNING; private Charset m_aCharset = DEFAULT_XML_CHARSET_OBJ; private NamespaceContext m_aNamespaceContext = new MapBasedNamespaceContext (); private boolean m_bUseDoubleQuotesForAttributes = DEFAULT_USE_DOUBLE_QUOTES_FOR_ATTRIBUTES; private IXMLBracketModeDeterminator m_aBracketModeDeterminator = new XMLBracketModeDeterminatorXML (); private boolean m_bSpaceOnSelfClosedElement = DEFAULT_SPACE_ON_SELF_CLOSED_ELEMENT; private ENewLineMode m_eNewLineMode = ENewLineMode.DEFAULT; private String m_sIndentationString = DEFAULT_INDENTATION_STRING; private boolean m_bEmitNamespaces = DEFAULT_EMIT_NAMESPACES; private boolean m_bPutNamespaceContextPrefixesInRoot = DEFAULT_PUT_NAMESPACE_CONTEXT_PREFIXES_IN_ROOT; // Status vars private String m_sIndentationStringToString; /** * Creates a default settings object with the following settings: * <ul> * <li>XML version 1.0</li> * <li>with XML declaration</li> * <li>with document type</li> * <li>with comments</li> * <li>Indented and aligned</li> * <li>Writing invalid characters to the file as is - may result in invalid * XML files</li> * <li>Default character set UTF-8</li> * <li>No namespace context</li> * </ul> */ public XMLWriterSettings () {} /** * Copy constructor. * * @param aOther * The object to copy the settings from. May not be <code>null</code>. */ public XMLWriterSettings (@Nonnull final IXMLWriterSettings aOther) { ValueEnforcer.notNull (aOther, "Other"); setSerializeVersion (aOther.getSerializeVersion ()); setSerializeXMLDeclaration (aOther.getSerializeXMLDeclaration ()); setSerializeDocType (aOther.getSerializeDocType ()); setSerializeComments (aOther.getSerializeComments ()); setIndent (aOther.getIndent ()); setIndentDeterminator (aOther.getIndentDeterminator ()); setIncorrectCharacterHandling (aOther.getIncorrectCharacterHandling ()); setCharset (aOther.getCharsetObj ()); setNamespaceContext (aOther.getNamespaceContext ()); setBracketModeDeterminator (aOther.getBracketModeDeterminator ()); setUseDoubleQuotesForAttributes (aOther.isUseDoubleQuotesForAttributes ()); setSpaceOnSelfClosedElement (aOther.isSpaceOnSelfClosedElement ()); setNewLineMode (aOther.getNewLineMode ()); setIndentationString (aOther.getIndentationString ()); setEmitNamespaces (aOther.isEmitNamespaces ()); setPutNamespaceContextPrefixesInRoot (aOther.isPutNamespaceContextPrefixesInRoot ()); } @Nonnull public EXMLVersion getXMLVersion () { return m_eXMLVersion; } /** * Set the preferred XML version to use. * * @param eSerializeVersion * The XML serialize version. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setSerializeVersion (@Nonnull final EXMLSerializeVersion eSerializeVersion) { m_eSerializeVersion = ValueEnforcer.notNull (eSerializeVersion, "Version"); m_eXMLVersion = eSerializeVersion.getXMLVersionOrDefault (EXMLVersion.XML_10); return this; } @Nonnull public EXMLSerializeVersion getSerializeVersion () { return m_eSerializeVersion; } /** * Set the way how to handle the XML declaration. * * @param eSerializeXMLDecl * XML declaration handling. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setSerializeXMLDeclaration (@Nonnull final EXMLSerializeXMLDeclaration eSerializeXMLDecl) { m_eSerializeXMLDecl = ValueEnforcer.notNull (eSerializeXMLDecl, "SerializeXMLDecl"); return this; } @Nonnull public EXMLSerializeXMLDeclaration getSerializeXMLDeclaration () { return m_eSerializeXMLDecl; } /** * Set the way how to handle the doc type. * * @param eSerializeDocType * Doc type handling. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setSerializeDocType (@Nonnull final EXMLSerializeDocType eSerializeDocType) { m_eSerializeDocType = ValueEnforcer.notNull (eSerializeDocType, "SerializeDocType"); return this; } @Nonnull public EXMLSerializeDocType getSerializeDocType () { return m_eSerializeDocType; } /** * Set the way how comments should be handled. * * @param eSerializeComments * The comment handling. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setSerializeComments (@Nonnull final EXMLSerializeComments eSerializeComments) { m_eSerializeComments = ValueEnforcer.notNull (eSerializeComments, "SerializeComments"); return this; } @Nonnull public EXMLSerializeComments getSerializeComments () { return m_eSerializeComments; } /** * Set the way how to indent/align * * @param eIndent * Indent and align definition. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setIndent (@Nonnull final EXMLSerializeIndent eIndent) { m_eIndent = ValueEnforcer.notNull (eIndent, "Indent"); return this; } @Nonnull public EXMLSerializeIndent getIndent () { return m_eIndent; } /** * Set the dynamic (per-element) indent determinator to be used. * * @param aIndentDeterminator * The object to use. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setIndentDeterminator (@Nonnull final IXMLIndentDeterminator aIndentDeterminator) { m_aIndentDeterminator = ValueEnforcer.notNull (aIndentDeterminator, "IndentDeterminator"); return this; } @Nonnull public IXMLIndentDeterminator getIndentDeterminator () { return m_aIndentDeterminator; } /** * Set the way how to handle invalid characters. * * @param eIncorrectCharacterHandling * The invalid character handling. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setIncorrectCharacterHandling (@Nonnull final EXMLIncorrectCharacterHandling eIncorrectCharacterHandling) { m_eIncorrectCharacterHandling = ValueEnforcer.notNull (eIncorrectCharacterHandling, "IncorrectCharacterHandling"); return this; } @Nonnull public EXMLIncorrectCharacterHandling getIncorrectCharacterHandling () { return m_eIncorrectCharacterHandling; } /** * Set the serialization charset. * * @param aCharset * The charset to be used. May not be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setCharset (@Nonnull final Charset aCharset) { m_aCharset = ValueEnforcer.notNull (aCharset, "Charset"); return this; } @Nonnull public String getCharset () { return m_aCharset.name (); } @Nonnull public Charset getCharsetObj () { return m_aCharset; } /** * Set the namespace context to be used. * * @param aNamespaceContext * The namespace context to be used. May be <code>null</code>. * @return this */ @Nonnull public final XMLWriterSettings setNamespaceContext (@Nullable final NamespaceContext aNamespaceContext) { // A namespace context must always be present, to resolve default namespaces m_aNamespaceContext = aNamespaceContext != null ? aNamespaceContext : new MapBasedNamespaceContext (); return this; } @Nonnull public NamespaceContext getNamespaceContext () { return m_aNamespaceContext; } @Nonnull public final XMLWriterSettings setUseDoubleQuotesForAttributes (final boolean bUseDoubleQuotesForAttributes) { m_bUseDoubleQuotesForAttributes = bUseDoubleQuotesForAttributes; return this; } public boolean isUseDoubleQuotesForAttributes () { return m_bUseDoubleQuotesForAttributes; } @Nonnull public final XMLWriterSettings setBracketModeDeterminator (@Nonnull final IXMLBracketModeDeterminator aBracketModeDeterminator) { ValueEnforcer.notNull (aBracketModeDeterminator, "BracketModeDeterminator"); m_aBracketModeDeterminator = aBracketModeDeterminator; return this; } @Nonnull public IXMLBracketModeDeterminator getBracketModeDeterminator () { return m_aBracketModeDeterminator; } @Nonnull public final XMLWriterSettings setSpaceOnSelfClosedElement (final boolean bSpaceOnSelfClosedElement) { m_bSpaceOnSelfClosedElement = bSpaceOnSelfClosedElement; return this; } public boolean isSpaceOnSelfClosedElement () { return m_bSpaceOnSelfClosedElement; } @Nonnull public final XMLWriterSettings setNewLineMode (@Nonnull final ENewLineMode eNewLineMode) { m_eNewLineMode = ValueEnforcer.notNull (eNewLineMode, "NewLineMode"); return this; } @Nonnull public ENewLineMode getNewLineMode () { return m_eNewLineMode; } @Nonnull @Nonempty public String getNewLineString () { return m_eNewLineMode.getText (); } @Nonnull public final XMLWriterSettings setIndentationString (@Nonnull @Nonempty final String sIndentationString) { m_sIndentationString = ValueEnforcer.notEmpty (sIndentationString, "IndentationString"); m_sIndentationStringToString = null; return this; } @Nonnull @Nonempty public String getIndentationString () { return m_sIndentationString; } @Nonnull public final XMLWriterSettings setEmitNamespaces (final boolean bEmitNamespaces) { m_bEmitNamespaces = bEmitNamespaces; return this; } public boolean isEmitNamespaces () { return m_bEmitNamespaces; } @Nonnull public final XMLWriterSettings setPutNamespaceContextPrefixesInRoot (final boolean bPutNamespaceContextPrefixesInRoot) { m_bPutNamespaceContextPrefixesInRoot = bPutNamespaceContextPrefixesInRoot; return this; } public boolean isPutNamespaceContextPrefixesInRoot () { return m_bPutNamespaceContextPrefixesInRoot; } @Nonnull public XMLWriterSettings getClone () { return new XMLWriterSettings (this); } @Override public boolean equals (final Object o) { if (o == this) return true; if (o == null || !getClass ().equals (o.getClass ())) return false; final XMLWriterSettings rhs = (XMLWriterSettings) o; // namespace context does not necessarily implement equals/hashCode return m_eXMLVersion.equals (rhs.m_eXMLVersion) && m_eSerializeXMLDecl.equals (rhs.m_eSerializeXMLDecl) && m_eSerializeDocType.equals (rhs.m_eSerializeDocType) && m_eSerializeComments.equals (rhs.m_eSerializeComments) && m_eIndent.equals (rhs.m_eIndent) && m_aIndentDeterminator.equals (rhs.m_aIndentDeterminator) && m_eIncorrectCharacterHandling.equals (rhs.m_eIncorrectCharacterHandling) && m_aCharset.equals (rhs.m_aCharset) && EqualsHelper.equals (m_aNamespaceContext, rhs.m_aNamespaceContext) && m_bUseDoubleQuotesForAttributes == rhs.m_bUseDoubleQuotesForAttributes && m_aBracketModeDeterminator.equals (rhs.m_aBracketModeDeterminator) && m_bSpaceOnSelfClosedElement == rhs.m_bSpaceOnSelfClosedElement && m_eNewLineMode.equals (rhs.m_eNewLineMode) && m_sIndentationString.equals (rhs.m_sIndentationString) && m_bEmitNamespaces == rhs.m_bEmitNamespaces && m_bPutNamespaceContextPrefixesInRoot == rhs.m_bPutNamespaceContextPrefixesInRoot; } @Override public int hashCode () { // namespace context does not necessarily implement equals/hashCode return new HashCodeGenerator (this).append (m_eXMLVersion) .append (m_eSerializeXMLDecl) .append (m_eSerializeDocType) .append (m_eSerializeComments) .append (m_eIndent) .append (m_aIndentDeterminator) .append (m_eIncorrectCharacterHandling) .append (m_aCharset) .append (m_aNamespaceContext) .append (m_bUseDoubleQuotesForAttributes) .append (m_aBracketModeDeterminator) .append (m_bSpaceOnSelfClosedElement) .append (m_eNewLineMode) .append (m_sIndentationString) .append (m_bEmitNamespaces) .append (m_bPutNamespaceContextPrefixesInRoot) .getHashCode (); } @Override public String toString () { if (m_sIndentationStringToString == null) m_sIndentationStringToString = StringHelper.getHexEncoded (CharsetManager.getAsBytes (m_sIndentationString, CCharset.CHARSET_ISO_8859_1_OBJ)); return new ToStringGenerator (this).append ("xmlVersion", m_eXMLVersion) .append ("serializeXMLDecl", m_eSerializeXMLDecl) .append ("serializeDocType", m_eSerializeDocType) .append ("serializeComments", m_eSerializeComments) .append ("indent", m_eIndent) .append ("indentDeterminator", m_aIndentDeterminator) .append ("incorrectCharHandling", m_eIncorrectCharacterHandling) .append ("charset", m_aCharset) .append ("namespaceContext", m_aNamespaceContext) .append ("doubleQuotesForAttrs", m_bUseDoubleQuotesForAttributes) .append ("bracketModeDeterminator", m_aBracketModeDeterminator) .append ("spaceOnSelfClosedElement", m_bSpaceOnSelfClosedElement) .append ("newlineMode", m_eNewLineMode) .append ("indentationString", m_sIndentationStringToString) .append ("emitNamespaces", m_bEmitNamespaces) .append ("putNamespaceContextPrefixesInRoot", m_bPutNamespaceContextPrefixesInRoot) .toString (); } @Nonnull @ReturnsMutableCopy public static XMLWriterSettings createForHTML4 () { return new XMLWriterSettings ().setSerializeVersion (EXMLSerializeVersion.HTML) .setSerializeXMLDeclaration (EXMLSerializeXMLDeclaration.IGNORE) .setIndentDeterminator (new XMLIndentDeterminatorHTML ()) .setBracketModeDeterminator (new XMLBracketModeDeterminatorHTML4 ()) .setSpaceOnSelfClosedElement (true) .setPutNamespaceContextPrefixesInRoot (true); } @Nonnull @ReturnsMutableCopy public static XMLWriterSettings createForXHTML () { return new XMLWriterSettings ().setSerializeVersion (EXMLSerializeVersion.HTML) .setSerializeXMLDeclaration (EXMLSerializeXMLDeclaration.IGNORE) .setIndentDeterminator (new XMLIndentDeterminatorHTML ()) .setBracketModeDeterminator (new XMLBracketModeDeterminatorHTML4 ()) .setSpaceOnSelfClosedElement (true) .setPutNamespaceContextPrefixesInRoot (true); } @Nonnull @ReturnsMutableCopy public static XMLWriterSettings createForHTML5 () { return new XMLWriterSettings ().setSerializeVersion (EXMLSerializeVersion.HTML) .setSerializeXMLDeclaration (EXMLSerializeXMLDeclaration.IGNORE) .setIndentDeterminator (new XMLIndentDeterminatorHTML ()) .setBracketModeDeterminator (new XMLBracketModeDeterminatorHTML5 ()) .setSpaceOnSelfClosedElement (true) .setPutNamespaceContextPrefixesInRoot (true); } }
Fixed XML bracket bug in XHTML emitting
src/main/java/com/helger/commons/xml/serialize/write/XMLWriterSettings.java
Fixed XML bracket bug in XHTML emitting
<ide><path>rc/main/java/com/helger/commons/xml/serialize/write/XMLWriterSettings.java <ide> <ide> /** <ide> * Set the dynamic (per-element) indent determinator to be used. <del> * <add> * <ide> * @param aIndentDeterminator <ide> * The object to use. May not be <code>null</code>. <ide> * @return this <ide> return new XMLWriterSettings ().setSerializeVersion (EXMLSerializeVersion.HTML) <ide> .setSerializeXMLDeclaration (EXMLSerializeXMLDeclaration.IGNORE) <ide> .setIndentDeterminator (new XMLIndentDeterminatorHTML ()) <del> .setBracketModeDeterminator (new XMLBracketModeDeterminatorHTML4 ()) <add> .setBracketModeDeterminator (new XMLBracketModeDeterminatorXML ()) <ide> .setSpaceOnSelfClosedElement (true) <ide> .setPutNamespaceContextPrefixesInRoot (true); <ide> }
Java
mit
d115478d104f73337c07f8a89e8f74fa2e4fa6ef
0
mzmine/mzmine3,mzmine/mzmine3
/* * Copyright 2006-2021 The MZmine Development Team * * This file is part of MZmine. * * MZmine 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. * * MZmine 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 MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package io.github.mzmine.modules.visualization.spectra.msn_tree; import io.github.mzmine.datamodel.DataPoint; import io.github.mzmine.datamodel.MassSpectrumType; import io.github.mzmine.datamodel.PrecursorIonTree; import io.github.mzmine.datamodel.PrecursorIonTreeNode; import io.github.mzmine.datamodel.RawDataFile; import io.github.mzmine.datamodel.Scan; import io.github.mzmine.datamodel.impl.SimpleDataPoint; import io.github.mzmine.datamodel.msms.MsMsInfo; import io.github.mzmine.gui.chartbasics.chartgroups.ChartGroup; import io.github.mzmine.gui.chartbasics.gui.wrapper.ChartViewWrapper; import io.github.mzmine.gui.mainwindow.SimpleTab; import io.github.mzmine.main.MZmineCore; import io.github.mzmine.modules.dataprocessing.featdet_massdetection.exactmass.ExactMassDetector; import io.github.mzmine.modules.visualization.spectra.simplespectra.SpectraPlot; import io.github.mzmine.modules.visualization.spectra.simplespectra.datasets.DataPointsDataSet; import io.github.mzmine.modules.visualization.spectra.simplespectra.datasets.RelativeOption; import io.github.mzmine.modules.visualization.spectra.simplespectra.renderers.ArrowRenderer; import io.github.mzmine.modules.visualization.spectra.simplespectra.renderers.PeakRenderer; import io.github.mzmine.util.color.SimpleColorPalette; import io.github.mzmine.util.javafx.FxColorUtil; import io.github.mzmine.util.scans.ScanUtils; import java.awt.Color; import java.awt.Shape; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.HPos; import javafx.geometry.VPos; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.SelectionMode; import javafx.scene.control.SplitPane; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.KeyCode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.RowConstraints; import org.jetbrains.annotations.NotNull; import org.jfree.chart.axis.NumberAxis; import org.jfree.data.xy.AbstractXYDataset; import org.jfree.data.xy.XYDataset; /** * @author Robin Schmid (https://github.com/robinschmid) */ public class MSnTreeTab extends SimpleTab { private final AtomicLong currentThread = new AtomicLong(0L); private final TreeView<PrecursorIonTreeNode> treeView; private final GridPane spectraPane; private final Label legendEnergies; private final CheckBox cbRelative; private final CheckBox cbDenoise; private final List<SpectraPlot> spectraPlots = new ArrayList<>(1); private int lastSelectedItem = -1; private ChartGroup chartGroup; private PrecursorIonTreeNode currentRoot = null; public MSnTreeTab() { super("MSn Tree", true, false); BorderPane main = new BorderPane(); // add tree to the left // buttons over tree HBox buttons = new HBox(5, // add buttons createButton("Expand", e -> expandTreeView(true)), createButton("Collapse", e -> expandTreeView(false))); treeView = new TreeView<>(); ScrollPane treeScroll = new ScrollPane(treeView); // treeScroll.setHbarPolicy(ScrollBarPolicy.NEVER); treeScroll.setFitToHeight(true); treeScroll.setFitToWidth(true); TreeItem<PrecursorIonTreeNode> root = new TreeItem<>(); root.setExpanded(true); treeView.setRoot(root); treeView.setShowRoot(false); treeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); treeView.getSelectionModel().selectedItemProperty() .addListener(((observable, oldValue, newValue) -> showSpectra(newValue))); BorderPane left = new BorderPane(); left.setTop(buttons); left.setCenter(treeScroll); // create spectra grid spectraPane = new GridPane(); final ColumnConstraints col = new ColumnConstraints(200, 350, -1, Priority.ALWAYS, HPos.LEFT, true); spectraPane.getColumnConstraints().add(col); spectraPane.setGridLinesVisible(true); final RowConstraints rowConstraints = new RowConstraints(200, 350, -1, Priority.ALWAYS, VPos.CENTER, true); spectraPane.getRowConstraints().add(rowConstraints); // create first plot and initialize group for zooming etc chartGroup = new ChartGroup(false, false, true, false); chartGroup.setShowCrosshair(true, false); final SpectraPlot plot = new SpectraPlot(); spectraPlots.add(plot); chartGroup.add(new ChartViewWrapper(plot)); spectraPane.add(new BorderPane(spectraPlots.get(0)), 0, 0); ScrollPane scrollSpectra = new ScrollPane(new BorderPane(spectraPane)); scrollSpectra.setFitToHeight(true); scrollSpectra.setFitToWidth(true); scrollSpectra.setVbarPolicy(ScrollBarPolicy.ALWAYS); BorderPane center = new BorderPane(scrollSpectra); // add menu to spectra HBox spectraMenu = new HBox(4); center.setTop(spectraMenu); legendEnergies = new Label(""); cbRelative = new CheckBox("Relative"); cbRelative.selectedProperty().addListener((o, ov, nv) -> changeRelative()); cbDenoise = new CheckBox("Denoise"); cbDenoise.selectedProperty().addListener((o, ov, nv) -> updateCurrentSpectra()); // menu spectraMenu.getChildren().addAll( // menu createButton("Auto range", this::autoRange), // cbRelative, cbDenoise, legendEnergies); SplitPane splitPane = new SplitPane(left, center); splitPane.setDividerPositions(0.22); main.setCenter(splitPane); // add main to tab main.getStyleClass().add("region-match-chart-bg"); this.setContent(main); main.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.DOWN) { nextPrecursor(); main.requestFocus(); e.consume(); } else if (e.getCode() == KeyCode.UP) { previousPrecursor(); main.requestFocus(); e.consume(); } }); } private void changeRelative() { if (currentRoot != null) { for (var p : spectraPlots) { for (int i = 0; i < p.getXYPlot().getDatasetCount(); i++) { final XYDataset data = p.getXYPlot().getDataset(i); if (data instanceof RelativeOption op) { op.setRelative(cbRelative.isSelected()); } } p.getChart().fireChartChanged(); } chartGroup.resetRangeZoom(); } } private void updateCurrentSpectra() { if (currentRoot != null) { showSpectra(currentRoot); } } private void autoRange(ActionEvent actionEvent) { if (chartGroup != null) { chartGroup.resetZoom(); } } private Button createButton(String title, EventHandler<ActionEvent> action) { final Button button = new Button(title); button.setOnAction(action); return button; } /** * Set raw data file and update tree * * @param raw update all views to this raw file */ public synchronized void setRawDataFile(RawDataFile raw) { lastSelectedItem = -1; treeView.getRoot().getChildren().clear(); // spectraPane.getChildren().clear(); // track current thread final long current = currentThread.incrementAndGet(); Thread thread = new Thread(() -> { // run on different thread final List<PrecursorIonTree> trees = ScanUtils.getMSnFragmentTrees(raw); MZmineCore.runLater(() -> { if (current == currentThread.get()) { treeView.getRoot().getChildren() .addAll(trees.stream().map(t -> createTreeItem(t.getRoot())).toList()); expandTreeView(treeView.getRoot(), true); } }); }); thread.start(); } private TreeItem<PrecursorIonTreeNode> createTreeItem(PrecursorIonTreeNode node) { final var item = new TreeItem<>(node); item.getChildren() .addAll(node.getChildPrecursors().stream().map(this::createTreeItem).toList()); return item; } private void showSpectra(TreeItem<PrecursorIonTreeNode> node) { showSpectra(node == null ? null : node.getValue()); } public void showSpectra(PrecursorIonTreeNode any) { spectraPane.getChildren().clear(); spectraPane.getRowConstraints().clear(); spectraPlots.forEach(SpectraPlot::removeAllDataSets); if (any == null) { return; } // add spectra PrecursorIonTreeNode prevRoot = currentRoot; currentRoot = any.getRoot(); boolean rootHasChanged = !Objects.equals(prevRoot, currentRoot); // colors final SimpleColorPalette colors = MZmineCore.getConfiguration().getDefaultColorPalette(); SpectraPlot previousPlot = null; // distribute collision energies in three categories low, med, high final List<Float> collisionEnergies = currentRoot.getAllFragmentScans().stream() .map(Scan::getMsMsInfo).filter(Objects::nonNull).map(MsMsInfo::getActivationEnergy) .filter(Objects::nonNull).distinct().sorted().toList(); float minEnergy = 0f; float maxEnergy = 0f; float medEnergy = 0f; if (!collisionEnergies.isEmpty()) { minEnergy = collisionEnergies.get(0); maxEnergy = collisionEnergies.get(collisionEnergies.size() - 1); medEnergy = collisionEnergies.get(collisionEnergies.size() / 2); // set legend if (minEnergy != maxEnergy) { if (minEnergy != medEnergy && maxEnergy != medEnergy) { legendEnergies.setText( String.format("Activation: ▽≈%.0f △≈%.0f ◇≈%.0f", minEnergy, medEnergy, maxEnergy)); } else { legendEnergies.setText(String.format("Activation: ▽≈%.0f ◇≈%.0f", minEnergy, maxEnergy)); } } else { legendEnergies.setText(String.format("Activation: ◇≈%.0f", maxEnergy)); } } // relative intensities? and denoise? final boolean normalizeIntensities = cbRelative.isSelected(); final boolean denoise = cbDenoise.isSelected(); List<PrecursorIonTreeNode> levelPrecursors = List.of(currentRoot); int levelFromRoot = 0; do { // create one spectra plot for each MS level if (levelFromRoot >= spectraPlots.size()) { final SpectraPlot plot = new SpectraPlot(); spectraPlots.add(plot); chartGroup.add(new ChartViewWrapper(plot)); } SpectraPlot spectraPlot = spectraPlots.get(levelFromRoot); if (spectraPlot.getXYPlot().getRangeAxis() instanceof NumberAxis va) { if (normalizeIntensities) { va.setNumberFormatOverride(new DecimalFormat("0.#")); } else { va.setNumberFormatOverride(MZmineCore.getConfiguration().getIntensityFormat()); } } // create combined dataset for each MS level int c = 0; for (PrecursorIonTreeNode precursor : levelPrecursors) { final Color color = FxColorUtil.fxColorToAWT(colors.get(c % colors.size())); final List<Scan> fragmentScans = precursor.getFragmentScans(); for (final Scan scan : fragmentScans) { AbstractXYDataset data = ensureCentroidDataset(normalizeIntensities, denoise, scan); // add peak renderer to show centroids spectraPlot.addDataSet(data, color, false, false); spectraPlot.getXYPlot() .setRenderer(spectraPlot.getNumOfDataSets() - 1, new PeakRenderer(color, false)); // add shapes spectraPlot.addDataSet(data, color, false, null, false); final Shape shape = getActivationEnergyShape(scan.getMsMsInfo().getActivationEnergy(), minEnergy, medEnergy, maxEnergy); spectraPlot.getXYPlot() .setRenderer(spectraPlot.getNumOfDataSets() - 1, new ArrowRenderer(shape, color)); } // add precursor markers for each different precursor only once spectraPlot.addPrecursorMarkers(precursor.getFragmentScans().get(0), color, 0.25f); c++; } // hide x axis if (previousPlot != null) { previousPlot.getXYPlot().getDomainAxis().setVisible(false); } // add spectraPlot.getXYPlot().getDomainAxis().setVisible(true); spectraPane.getRowConstraints() .add(new RowConstraints(200, 250, -1, Priority.ALWAYS, VPos.CENTER, true)); spectraPane.add(new BorderPane(spectraPlot), 0, levelFromRoot); previousPlot = spectraPlot; // next level levelFromRoot++; levelPrecursors = currentRoot.getPrecursors(levelFromRoot); } while (!levelPrecursors.isEmpty()); if (rootHasChanged) { chartGroup.applyAutoRange(true); } } @NotNull private AbstractXYDataset ensureCentroidDataset(boolean normalizeIntensities, boolean denoise, Scan scan) { final double[][] masses; if (scan.getMassList() != null) { masses = new double[][]{scan.getMassList().getMzValues(new double[0]), scan.getMassList().getIntensityValues(new double[0])}; } else if (!MassSpectrumType.PROFILE.equals(scan.getSpectrumType())) { masses = new double[][]{scan.getMzValues(new double[0]), scan.getIntensityValues(new double[0])}; } else { // profile data run mass detection masses = ExactMassDetector.getMassValues(scan, 0); } List<DataPoint> dps = new ArrayList<>(); if (denoise) { final double[] sortedIntensities = Arrays.stream(masses[1]).filter(v -> v > 0).sorted() .toArray(); double min = sortedIntensities[0]; // remove everything <2xmin for (int i = 0; i < masses[0].length; i++) { if (masses[1][i] > min * 2.5d) { dps.add(new SimpleDataPoint(masses[0][i], masses[1][i])); } } } else { // filter zeros for (int i = 0; i < masses[0].length; i++) { if (masses[1][i] > 0) { dps.add(new SimpleDataPoint(masses[0][i], masses[1][i])); } } } return new DataPointsDataSet("", dps.toArray(DataPoint[]::new), normalizeIntensities); } /** * Three groups of activation energies close to min, median, max * * @param ae current activation energy * @return a shape from the {@link ArrowRenderer} */ private Shape getActivationEnergyShape(Float ae, float minEnergy, float medEnergy, float maxEnergy) { if (ae == null) { return ArrowRenderer.diamond; } final float med = Math.abs(medEnergy - ae); return ae - minEnergy < med ? ArrowRenderer.downArrow : (med < maxEnergy - ae ? ArrowRenderer.upArrow : ArrowRenderer.diamond); } private void expandTreeView(boolean expanded) { expandTreeView(treeView.getRoot(), expanded); } private void expandTreeView(TreeItem<?> item, boolean expanded) { if (item != null && !item.isLeaf()) { item.setExpanded(expanded); for (TreeItem<?> child : item.getChildren()) { expandTreeView(child, expanded); } } treeView.getRoot().setExpanded(true); } public void previousPrecursor() { if (lastSelectedItem > 0) { lastSelectedItem--; treeView.getSelectionModel().select(getMS2Nodes().get(lastSelectedItem)); } } private ObservableList<TreeItem<PrecursorIonTreeNode>> getMS2Nodes() { return treeView.getRoot().getChildren(); } public void nextPrecursor() { if (lastSelectedItem + 1 < getMS2Nodes().size()) { lastSelectedItem++; treeView.getSelectionModel().select(treeView.getRoot().getChildren().get(lastSelectedItem)); } } @Override public void onRawDataFileSelectionChanged(Collection<? extends RawDataFile> rawDataFiles) { if (rawDataFiles != null && rawDataFiles.size() > 0) { setRawDataFile(rawDataFiles.stream().findFirst().get()); } } }
src/main/java/io/github/mzmine/modules/visualization/spectra/msn_tree/MSnTreeTab.java
/* * Copyright 2006-2021 The MZmine Development Team * * This file is part of MZmine. * * MZmine 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. * * MZmine 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 MZmine; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * */ package io.github.mzmine.modules.visualization.spectra.msn_tree; import io.github.mzmine.datamodel.DataPoint; import io.github.mzmine.datamodel.MassSpectrumType; import io.github.mzmine.datamodel.PrecursorIonTree; import io.github.mzmine.datamodel.PrecursorIonTreeNode; import io.github.mzmine.datamodel.RawDataFile; import io.github.mzmine.datamodel.Scan; import io.github.mzmine.datamodel.impl.SimpleDataPoint; import io.github.mzmine.datamodel.msms.MsMsInfo; import io.github.mzmine.gui.chartbasics.chartgroups.ChartGroup; import io.github.mzmine.gui.chartbasics.gui.wrapper.ChartViewWrapper; import io.github.mzmine.gui.mainwindow.SimpleTab; import io.github.mzmine.main.MZmineCore; import io.github.mzmine.modules.dataprocessing.featdet_massdetection.exactmass.ExactMassDetector; import io.github.mzmine.modules.visualization.spectra.simplespectra.SpectraPlot; import io.github.mzmine.modules.visualization.spectra.simplespectra.datasets.DataPointsDataSet; import io.github.mzmine.modules.visualization.spectra.simplespectra.datasets.RelativeOption; import io.github.mzmine.modules.visualization.spectra.simplespectra.renderers.ArrowRenderer; import io.github.mzmine.modules.visualization.spectra.simplespectra.renderers.PeakRenderer; import io.github.mzmine.util.color.SimpleColorPalette; import io.github.mzmine.util.javafx.FxColorUtil; import io.github.mzmine.util.scans.ScanUtils; import java.awt.Color; import java.awt.Shape; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.HPos; import javafx.geometry.VPos; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.SelectionMode; import javafx.scene.control.SplitPane; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.KeyCode; import javafx.scene.layout.BorderPane; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.RowConstraints; import org.jetbrains.annotations.NotNull; import org.jfree.chart.axis.NumberAxis; import org.jfree.data.xy.AbstractXYDataset; import org.jfree.data.xy.XYDataset; /** * @author Robin Schmid (https://github.com/robinschmid) */ public class MSnTreeTab extends SimpleTab { private final AtomicLong currentThread = new AtomicLong(0L); private final TreeView<PrecursorIonTreeNode> treeView; private final GridPane spectraPane; private final Label legendEnergies; private final CheckBox cbRelative; private final CheckBox cbDenoise; private final List<SpectraPlot> spectraPlots = new ArrayList<>(1); private int lastSelectedItem = -1; private ChartGroup chartGroup; private PrecursorIonTreeNode currentRoot = null; public MSnTreeTab() { super("MSn Tree", true, false); BorderPane main = new BorderPane(); // add tree to the left // buttons over tree HBox buttons = new HBox(5, // add buttons createButton("Expand", e -> expandTreeView(true)), createButton("Collapse", e -> expandTreeView(false))); treeView = new TreeView<>(); ScrollPane treeScroll = new ScrollPane(treeView); // treeScroll.setHbarPolicy(ScrollBarPolicy.NEVER); treeScroll.setFitToHeight(true); treeScroll.setFitToWidth(true); TreeItem<PrecursorIonTreeNode> root = new TreeItem<>(); root.setExpanded(true); treeView.setRoot(root); treeView.setShowRoot(false); treeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); treeView.getSelectionModel().selectedItemProperty() .addListener(((observable, oldValue, newValue) -> showSpectra(newValue))); BorderPane left = new BorderPane(); left.setTop(buttons); left.setCenter(treeScroll); // create spectra grid spectraPane = new GridPane(); final ColumnConstraints col = new ColumnConstraints(200, 350, -1, Priority.ALWAYS, HPos.LEFT, true); spectraPane.getColumnConstraints().add(col); spectraPane.setGridLinesVisible(true); final RowConstraints rowConstraints = new RowConstraints(200, 350, -1, Priority.ALWAYS, VPos.CENTER, true); spectraPane.getRowConstraints().add(rowConstraints); // create first plot and initialize group for zooming etc chartGroup = new ChartGroup(false, false, true, false); chartGroup.setShowCrosshair(true, false); final SpectraPlot plot = new SpectraPlot(); spectraPlots.add(plot); chartGroup.add(new ChartViewWrapper(plot)); spectraPane.add(new BorderPane(spectraPlots.get(0)), 0, 0); ScrollPane scrollSpectra = new ScrollPane(new BorderPane(spectraPane)); scrollSpectra.setFitToHeight(true); scrollSpectra.setFitToWidth(true); scrollSpectra.setVbarPolicy(ScrollBarPolicy.ALWAYS); BorderPane center = new BorderPane(scrollSpectra); // add menu to spectra HBox spectraMenu = new HBox(4); center.setTop(spectraMenu); legendEnergies = new Label(""); cbRelative = new CheckBox("Relative"); cbRelative.selectedProperty().addListener((o, ov, nv) -> changeRelative()); cbDenoise = new CheckBox("Denoise"); cbDenoise.selectedProperty().addListener((o, ov, nv) -> updateCurrentSpectra()); // menu spectraMenu.getChildren().addAll( // menu createButton("Auto range", this::autoRange), // cbRelative, cbDenoise, legendEnergies); SplitPane splitPane = new SplitPane(left, center); splitPane.setDividerPositions(0.22); main.setCenter(splitPane); // add main to tab main.getStyleClass().add("region-match-chart-bg"); this.setContent(main); main.setOnKeyPressed(e -> { if (e.getCode() == KeyCode.DOWN) { nextPrecursor(); main.requestFocus(); e.consume(); } else if (e.getCode() == KeyCode.UP) { previousPrecursor(); main.requestFocus(); e.consume(); } }); } private void changeRelative() { if (currentRoot != null) { for (var p : spectraPlots) { for (int i = 0; i < p.getXYPlot().getDatasetCount(); i++) { final XYDataset data = p.getXYPlot().getDataset(i); if (data instanceof RelativeOption op) { op.setRelative(cbRelative.isSelected()); } } p.getChart().fireChartChanged(); } } } private void updateCurrentSpectra() { if (currentRoot != null) { showSpectra(currentRoot); } } private void autoRange(ActionEvent actionEvent) { if (chartGroup != null) { chartGroup.resetZoom(); } } private Button createButton(String title, EventHandler<ActionEvent> action) { final Button button = new Button(title); button.setOnAction(action); return button; } /** * Set raw data file and update tree * * @param raw update all views to this raw file */ public synchronized void setRawDataFile(RawDataFile raw) { lastSelectedItem = -1; treeView.getRoot().getChildren().clear(); // spectraPane.getChildren().clear(); // track current thread final long current = currentThread.incrementAndGet(); Thread thread = new Thread(() -> { // run on different thread final List<PrecursorIonTree> trees = ScanUtils.getMSnFragmentTrees(raw); MZmineCore.runLater(() -> { if (current == currentThread.get()) { treeView.getRoot().getChildren() .addAll(trees.stream().map(t -> createTreeItem(t.getRoot())).toList()); expandTreeView(treeView.getRoot(), true); } }); }); thread.start(); } private TreeItem<PrecursorIonTreeNode> createTreeItem(PrecursorIonTreeNode node) { final var item = new TreeItem<>(node); item.getChildren() .addAll(node.getChildPrecursors().stream().map(this::createTreeItem).toList()); return item; } private void showSpectra(TreeItem<PrecursorIonTreeNode> node) { showSpectra(node == null ? null : node.getValue()); } public void showSpectra(PrecursorIonTreeNode any) { spectraPane.getChildren().clear(); spectraPane.getRowConstraints().clear(); spectraPlots.forEach(SpectraPlot::removeAllDataSets); if (any == null) { return; } // add spectra PrecursorIonTreeNode prevRoot = currentRoot; currentRoot = any.getRoot(); boolean rootHasChanged = !Objects.equals(prevRoot, currentRoot); // colors final SimpleColorPalette colors = MZmineCore.getConfiguration().getDefaultColorPalette(); SpectraPlot previousPlot = null; // distribute collision energies in three categories low, med, high final List<Float> collisionEnergies = currentRoot.getAllFragmentScans().stream() .map(Scan::getMsMsInfo).filter(Objects::nonNull).map(MsMsInfo::getActivationEnergy) .filter(Objects::nonNull).distinct().sorted().toList(); float minEnergy = 0f; float maxEnergy = 0f; float medEnergy = 0f; if (!collisionEnergies.isEmpty()) { minEnergy = collisionEnergies.get(0); maxEnergy = collisionEnergies.get(collisionEnergies.size() - 1); medEnergy = collisionEnergies.get(collisionEnergies.size() / 2); // set legend if (minEnergy != maxEnergy) { if (minEnergy != medEnergy && maxEnergy != medEnergy) { legendEnergies.setText( String.format("Activation: ▽≈%.0f △≈%.0f ◇≈%.0f", minEnergy, medEnergy, maxEnergy)); } else { legendEnergies.setText(String.format("Activation: ▽≈%.0f ◇≈%.0f", minEnergy, maxEnergy)); } } else { legendEnergies.setText(String.format("Activation: ◇≈%.0f", maxEnergy)); } } // relative intensities? and denoise? final boolean normalizeIntensities = cbRelative.isSelected(); final boolean denoise = cbDenoise.isSelected(); List<PrecursorIonTreeNode> levelPrecursors = List.of(currentRoot); int levelFromRoot = 0; do { // create one spectra plot for each MS level if (levelFromRoot >= spectraPlots.size()) { final SpectraPlot plot = new SpectraPlot(); spectraPlots.add(plot); chartGroup.add(new ChartViewWrapper(plot)); } SpectraPlot spectraPlot = spectraPlots.get(levelFromRoot); if (spectraPlot.getXYPlot().getRangeAxis() instanceof NumberAxis va) { if (normalizeIntensities) { va.setNumberFormatOverride(new DecimalFormat("0.#")); } else { va.setNumberFormatOverride(MZmineCore.getConfiguration().getIntensityFormat()); } } // create combined dataset for each MS level int c = 0; for (PrecursorIonTreeNode precursor : levelPrecursors) { final Color color = FxColorUtil.fxColorToAWT(colors.get(c % colors.size())); final List<Scan> fragmentScans = precursor.getFragmentScans(); for (final Scan scan : fragmentScans) { AbstractXYDataset data = ensureCentroidDataset(normalizeIntensities, denoise, scan); // add peak renderer to show centroids spectraPlot.addDataSet(data, color, false, false); spectraPlot.getXYPlot() .setRenderer(spectraPlot.getNumOfDataSets() - 1, new PeakRenderer(color, false)); // add shapes spectraPlot.addDataSet(data, color, false, null, false); final Shape shape = getActivationEnergyShape(scan.getMsMsInfo().getActivationEnergy(), minEnergy, medEnergy, maxEnergy); spectraPlot.getXYPlot() .setRenderer(spectraPlot.getNumOfDataSets() - 1, new ArrowRenderer(shape, color)); } // add precursor markers for each different precursor only once spectraPlot.addPrecursorMarkers(precursor.getFragmentScans().get(0), color, 0.25f); c++; } // hide x axis if (previousPlot != null) { previousPlot.getXYPlot().getDomainAxis().setVisible(false); } // add spectraPlot.getXYPlot().getDomainAxis().setVisible(true); spectraPane.getRowConstraints() .add(new RowConstraints(200, 250, -1, Priority.ALWAYS, VPos.CENTER, true)); spectraPane.add(new BorderPane(spectraPlot), 0, levelFromRoot); previousPlot = spectraPlot; // next level levelFromRoot++; levelPrecursors = currentRoot.getPrecursors(levelFromRoot); } while (!levelPrecursors.isEmpty()); if (rootHasChanged) { chartGroup.applyAutoRange(true); } } @NotNull private AbstractXYDataset ensureCentroidDataset(boolean normalizeIntensities, boolean denoise, Scan scan) { final double[][] masses; if (scan.getMassList() != null) { masses = new double[][]{scan.getMassList().getMzValues(new double[0]), scan.getMassList().getIntensityValues(new double[0])}; } else if (!MassSpectrumType.PROFILE.equals(scan.getSpectrumType())) { masses = new double[][]{scan.getMzValues(new double[0]), scan.getIntensityValues(new double[0])}; } else { // profile data run mass detection masses = ExactMassDetector.getMassValues(scan, 0); } List<DataPoint> dps = new ArrayList<>(); if (denoise) { final double[] sortedIntensities = Arrays.stream(masses[1]).filter(v -> v > 0).sorted() .toArray(); double min = sortedIntensities[0]; // remove everything <2xmin for (int i = 0; i < masses[0].length; i++) { if (masses[1][i] > min * 2.5d) { dps.add(new SimpleDataPoint(masses[0][i], masses[1][i])); } } } else { // filter zeros for (int i = 0; i < masses[0].length; i++) { if (masses[1][i] > 0) { dps.add(new SimpleDataPoint(masses[0][i], masses[1][i])); } } } return new DataPointsDataSet("", dps.toArray(DataPoint[]::new), normalizeIntensities); } /** * Three groups of activation energies close to min, median, max * * @param ae current activation energy * @return a shape from the {@link ArrowRenderer} */ private Shape getActivationEnergyShape(Float ae, float minEnergy, float medEnergy, float maxEnergy) { if (ae == null) { return ArrowRenderer.diamond; } final float med = Math.abs(medEnergy - ae); return ae - minEnergy < med ? ArrowRenderer.downArrow : (med < maxEnergy - ae ? ArrowRenderer.upArrow : ArrowRenderer.diamond); } private void expandTreeView(boolean expanded) { expandTreeView(treeView.getRoot(), expanded); } private void expandTreeView(TreeItem<?> item, boolean expanded) { if (item != null && !item.isLeaf()) { item.setExpanded(expanded); for (TreeItem<?> child : item.getChildren()) { expandTreeView(child, expanded); } } treeView.getRoot().setExpanded(true); } public void previousPrecursor() { if (lastSelectedItem > 0) { lastSelectedItem--; treeView.getSelectionModel().select(getMS2Nodes().get(lastSelectedItem)); } } private ObservableList<TreeItem<PrecursorIonTreeNode>> getMS2Nodes() { return treeView.getRoot().getChildren(); } public void nextPrecursor() { if (lastSelectedItem + 1 < getMS2Nodes().size()) { lastSelectedItem++; treeView.getSelectionModel().select(treeView.getRoot().getChildren().get(lastSelectedItem)); } } @Override public void onRawDataFileSelectionChanged(Collection<? extends RawDataFile> rawDataFiles) { if (rawDataFiles != null && rawDataFiles.size() > 0) { setRawDataFile(rawDataFiles.stream().findFirst().get()); } } }
Auto zoom range
src/main/java/io/github/mzmine/modules/visualization/spectra/msn_tree/MSnTreeTab.java
Auto zoom range
<ide><path>rc/main/java/io/github/mzmine/modules/visualization/spectra/msn_tree/MSnTreeTab.java <ide> } <ide> p.getChart().fireChartChanged(); <ide> } <add> chartGroup.resetRangeZoom(); <ide> } <ide> } <ide>
JavaScript
bsd-3-clause
1e1721e934720c31aaac4f351f40c4adc5605157
0
bonham000/fcc-react-tests-module,bonham000/fcc-react-tests-module
/* eslint-disable */ import assert from 'assert' import { transform } from 'babel-standalone' // snippet for defining HTML: <code>&#60;div /&#62</code> // SET TO TRUE WHEN QA IS COMPLETE: export const QA = false; // ---------------------------- define challenge title ---------------------------- export const challengeTitle = `<span class = 'default'>Challenge: </span>Use Middleware to Handle Asynchronous Actions` // ---------------------------- challenge text ---------------------------- export const challengeText = `<span class = 'default'>Intro: </span>So far we've avoided discussing asynchronous actions but they are an unavoidable part of web development. Of course we will have to call asynchronous endpoints in our Redux app, how do we handle these types of requests? Redux provides some middleware designed specifically for this purpose, Redux Thunk middleware, to be exact. Let's briefly describe how to use this with Redux.<br><br> To include Redux Thunk middleware, we pass it as an argument to <code>Redux.applyMiddleware()</code>, which we provide as a second optional parameter to our <code>createStore()</code> function. Take a look at the code in the editor to see this. Then, to create an asynchronous action, we return a function in our action creator that takes <code>dispatch</code> as an argument. Within this function we can dispatch actions and perform asynchronous requests.<br><br> For instance, in this example we are going to make a pretend asynchronous request with a <code>setTimeout()</code> call. It's common to dispatch an action before initiating any asynchronous behavior so that your application state knows that some data is being requested (this state could display a loading icon, for instance). Then, once you receive the data, you dispatch another action which carries the data as a payload and information that the action is completed.<br><br> Remember how we said we're passing <code>dispatch</code> as a parameter to this special action creator? This is what we'll use to dispatch our actions, we simply pass our action directly to dispatch and the middleware takes care of the rest.` // ---------------------------- challenge instructions ---------------------------- export const challengeInstructions = `<span class = 'default'>Instructions: </span>So in this example we just have to write both dispatches in the <code>handleAsync()</code> action creator. Let's dispatch <code>requestingData()</code> before our <code>setTimeout()</code> (pretend API call) and then, after we receive our (pretend) data, let's dispatch our <code>receivedData()</code> action, passing in this data. And that's it! Now you know how to handle asynchronous actions in Redux. Everything else continues to behave as before.` // ---------------------------- define challenge seed code ---------------------------- export const seedCode = `const REQUESTING_DATA = 'REQUESTING_DATA' const RECEIVED_DATA = 'RECEIVED_DATA' const requestingData = () => { return {type: REQUESTING_DATA} } const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} } const handleAsync = () => { return function(dispatch) { // dispatch request action here setTimeout(function() { let data = { users: ['Jeff', 'William', 'Alice'] } // dispatch received data action here }, 2500); } }; const defaultState = { fetching: false, users: [] }; const asyncDataReducer = (state = defaultState, action) => { switch(action.type) { case REQUESTING_DATA: return { fetching: true, users: [] } case RECEIVED_DATA: return { fetching: false, users: action.users } default: return state; } }; const store = Redux.createStore( asyncDataReducer, Redux.applyMiddleware(ReduxThunk.default) );` // ---------------------------- define challenge solution code ---------------------------- export const solutionCode = `const REQUESTING_DATA = 'REQUESTING_DATA' const RECEIVED_DATA = 'RECEIVED_DATA' const requestingData = () => { return {type: REQUESTING_DATA} } const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} } const handleAsync = () => { return function(dispatch) { dispatch(requestingData()); setTimeout(function() { let data = { users: ['Jeff', 'William', 'Alice'] } dispatch(receivedData(data)); }, 2500); } }; const defaultState = { fetching: false, users: [] }; const asyncDataReducer = (state = defaultState, action) => { switch(action.type) { case REQUESTING_DATA: return { fetching: true, users: [] } case RECEIVED_DATA: return { fetching: false, users: action.users } default: return state; } }; const store = Redux.createStore( asyncDataReducer, Redux.applyMiddleware(ReduxThunk.default) );` // ---------------------------- define challenge tests ---------------------------- export const executeTests = (code) => { const error_0 = 'Your code was transpiled successfully.'; const error_1 = 'The requestingData action creator returns an object of type equal to the value of REQUESTING_DATA.'; const error_2 = 'The receivedData action creator returns an object of type equal to the value of RECEIVED_DATA.'; const error_3 = 'asyncDataReducer is a function.'; const error_4 = 'Dispatching the requestingData action creator updates the store\'s state property of fetching to true.'; const error_5 = 'Dispatching handleAsync dispatches the data request action and then dispatches the received data action after a delay.'; let testResults = [ { test: 0, status: false, condition: error_0 }, { test: 1, status: false, condition: error_1 }, { test: 2, status: false, condition: error_2 }, { test: 3, status: false, condition: error_3 }, { test: 4, status: false, condition: error_4 }, { test: 5, status: false, condition: error_5 } ]; let es5, reduxCode, passed = true; let REQUESTING_DATA, RECEIVED_DATA, requestingData, receivedData, handleAsync, asyncDataReducer, store; // this code hijacks the user input to create an IIFE // which returns the store from Redux as an object // or whatever you need from the client code const prepend = `(function() {` const apend = `;\n return { REQUESTING_DATA, RECEIVED_DATA, requestingData, receivedData, handleAsync, asyncDataReducer, store } })()` const modifiedCode = prepend.concat(code).concat(apend); const shortenedTimeout = modifiedCode.replace('2500', '250'); // test 0: try to transpile JSX, ES6 code to ES5 in browser try { es5 = transform(shortenedTimeout, { presets: [ 'es2015', 'react' ] }).code; testResults[0].status = true; } catch (err) { passed = false; testResults[0].status = false; } // save the store from redux to test here // now you can access the redux store methods try { reduxCode = eval(es5); REQUESTING_DATA = reduxCode.REQUESTING_DATA; RECEIVED_DATA = reduxCode.RECEIVED_DATA; requestingData = reduxCode.requestingData; receivedData = reduxCode.receivedData; handleAsync = reduxCode.handleAsync; asyncDataReducer = reduxCode.asyncDataReducer; store = reduxCode.store; } catch (err) { passed = false; } // test 1: try { assert.strictEqual(requestingData().type, REQUESTING_DATA, error_1); testResults[1].status = true; } catch (err) { passed = false; testResults[1].status = false; } // test 2: try { assert.strictEqual(receivedData('data').type, RECEIVED_DATA, error_2); testResults[2].status = true; } catch (err) { passed = false; testResults[2].status = false; } // test 3: try { assert.strictEqual(typeof asyncDataReducer, 'function', error_3); testResults[3].status = true; } catch (err) { passed = false; testResults[3].status = false; } // test 4: try { const initialState = store.getState(); store.dispatch(requestingData()); const reqState = store.getState(); assert( initialState.fetching === false && reqState.fetching === true, error_4 ); testResults[4].status = true; } catch (err) { passed = false; testResults[4].status = false; } // test 5: try { const noWhiteSpace = handleAsync.toString().replace(/\s/g,''); assert( noWhiteSpace.includes('dispatch(requestingData())') === true && noWhiteSpace.includes('dispatch(receivedData(data))') === true, error_5 ); testResults[5].status = true; } catch (err) { passed = false; testResults[5].status = false; } return { passed, testResults } } // liveRender modifies console.log in user input and returns message data ----------------------- export const liveRender = (code) => { // this code modifies the user input to return all // console.log statements as a message array to be // displayed on the client UI const prepend = ` (function() { let __Custom__Log = [] const message = (msg) => __Custom__Log.push(msg); ` const apend = `;\n return __Custom__Log })();` const consoleReplaced = code.replace(/console.log/g, 'message'); const hijackedCode = prepend.concat(consoleReplaced).concat(apend); let evaluatedCode; try { evaluatedCode = eval(hijackedCode); } catch (err) { console.log(err); } return evaluatedCode; }
src/challenges/redux/curriculum/Redux_12.js
/* eslint-disable */ import assert from 'assert' import { transform } from 'babel-standalone' // snippet for defining HTML: <code>&#60;div /&#62</code> // SET TO TRUE WHEN QA IS COMPLETE: export const QA = false; // ---------------------------- define challenge title ---------------------------- export const challengeTitle = `<span class = 'default'>Challenge: </span>Use Middleware to Handle Asynchronous Actions` // ---------------------------- challenge text ---------------------------- export const challengeText = `<span class = 'default'>Intro: </span>So far we've avoided discussing asynchronous actions but they are an unavoidable part of web development. Of course we will have to call asynchronous endpoints in our Redux app, how do we handle these types of requests? Redux provides some middleware designed specifically for this purpose, Redux Thunk middleware, to be exact. Let's briefly describe how to use this with Redux.<br><br> To include Redux Thunk middleware, we pass it as an argument to <code>Redux.applyMiddleware()</code>, which we provide as a second optional parameter to our <code>creatStore()</code> function. Take a look at the code in the editor to see this. Then, to create an asynchronous action, we return a function in our action creator that takes <code>dispatch</code> as an argument. Within this function we can dispatch actions and perform asynchronous requests.<br><br> For instance, in this example we are going to make a pretend asynchronous request with a <code>setTimeout()</code> call. It's common to dispatch an action before initiating any asynchronous behavior so that your application state knows that some data is being requested (this state could display a loading icon, for instance). Then, once you receive the data, you dispatch another action which carries the data as a payload and information that the action is completed.<br><br> Remember how we said we're passing <code>dispatch</code> as a parameter to this special action creator? This is what we'll use to dispatch our actions, we simply pass our action directly to dispatch and the middleware takes care of the rest.` // ---------------------------- challenge instructions ---------------------------- export const challengeInstructions = `<span class = 'default'>Instructions: </span>So in this example we just have to write both dispatches in the <code>handleAsync()</code> action creator. Let's dispatch <code>requestingData()</code> before our <code>setTimeout()</code> (pretend API call) and then, after we receive our (pretend) data, let's dispatch our <code>receivedData()</code> action, passing in this data. And that's it! Now you know how to handle asynchronous actions in Redux. Everything else continues to behave as before.` // ---------------------------- define challenge seed code ---------------------------- export const seedCode = `const REQUESTING_DATA = 'REQUESTING_DATA' const RECEIVED_DATA = 'RECEIVED_DATA' const requestingData = () => { return {type: REQUESTING_DATA} } const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} } const handleAsync = () => { return function(dispatch) { // dispatch request action here setTimeout(function() { let data = { users: ['Jeff', 'William', 'Alice'] } // dispatch received data action here }, 2500); } }; const defaultState = { fetching: false, users: [] }; const asyncDataReducer = (state = defaultState, action) => { switch(action.type) { case REQUESTING_DATA: return { fetching: true, users: [] } case RECEIVED_DATA: return { fetching: false, users: action.users } default: return state; } }; const store = Redux.createStore( asyncDataReducer, Redux.applyMiddleware(ReduxThunk.default) );` // ---------------------------- define challenge solution code ---------------------------- export const solutionCode = `const REQUESTING_DATA = 'REQUESTING_DATA' const RECEIVED_DATA = 'RECEIVED_DATA' const requestingData = () => { return {type: REQUESTING_DATA} } const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} } const handleAsync = () => { return function(dispatch) { dispatch(requestingData()); setTimeout(function() { let data = { users: ['Jeff', 'William', 'Alice'] } dispatch(receivedData(data)); }, 2500); } }; const defaultState = { fetching: false, users: [] }; const asyncDataReducer = (state = defaultState, action) => { switch(action.type) { case REQUESTING_DATA: return { fetching: true, users: [] } case RECEIVED_DATA: return { fetching: false, users: action.users } default: return state; } }; const store = Redux.createStore( asyncDataReducer, Redux.applyMiddleware(ReduxThunk.default) );` // ---------------------------- define challenge tests ---------------------------- export const executeTests = (code) => { const error_0 = 'Your code was transpiled successfully.'; const error_1 = 'The requestingData action creator returns an object of type equal to the value of REQUESTING_DATA.'; const error_2 = 'The receivedData action creator returns an object of type equal to the value of RECEIVED_DATA.'; const error_3 = 'asyncDataReducer is a function.'; const error_4 = 'Dispatching the requestingData action creator updates the store\'s state property of fetching to true.'; const error_5 = 'Dispatching handleAsync dispatches the data request action and then dispatches the received data action after a delay.'; let testResults = [ { test: 0, status: false, condition: error_0 }, { test: 1, status: false, condition: error_1 }, { test: 2, status: false, condition: error_2 }, { test: 3, status: false, condition: error_3 }, { test: 4, status: false, condition: error_4 }, { test: 5, status: false, condition: error_5 } ]; let es5, reduxCode, passed = true; let REQUESTING_DATA, RECEIVED_DATA, requestingData, receivedData, handleAsync, asyncDataReducer, store; // this code hijacks the user input to create an IIFE // which returns the store from Redux as an object // or whatever you need from the client code const prepend = `(function() {` const apend = `;\n return { REQUESTING_DATA, RECEIVED_DATA, requestingData, receivedData, handleAsync, asyncDataReducer, store } })()` const modifiedCode = prepend.concat(code).concat(apend); const shortenedTimeout = modifiedCode.replace('2500', '250'); // test 0: try to transpile JSX, ES6 code to ES5 in browser try { es5 = transform(shortenedTimeout, { presets: [ 'es2015', 'react' ] }).code; testResults[0].status = true; } catch (err) { passed = false; testResults[0].status = false; } // save the store from redux to test here // now you can access the redux store methods try { reduxCode = eval(es5); REQUESTING_DATA = reduxCode.REQUESTING_DATA; RECEIVED_DATA = reduxCode.RECEIVED_DATA; requestingData = reduxCode.requestingData; receivedData = reduxCode.receivedData; handleAsync = reduxCode.handleAsync; asyncDataReducer = reduxCode.asyncDataReducer; store = reduxCode.store; } catch (err) { passed = false; } // test 1: try { assert.strictEqual(requestingData().type, REQUESTING_DATA, error_1); testResults[1].status = true; } catch (err) { passed = false; testResults[1].status = false; } // test 2: try { assert.strictEqual(receivedData('data').type, RECEIVED_DATA, error_2); testResults[2].status = true; } catch (err) { passed = false; testResults[2].status = false; } // test 3: try { assert.strictEqual(typeof asyncDataReducer, 'function', error_3); testResults[3].status = true; } catch (err) { passed = false; testResults[3].status = false; } // test 4: try { const initialState = store.getState(); store.dispatch(requestingData()); const reqState = store.getState(); assert( initialState.fetching === false && reqState.fetching === true, error_4 ); testResults[4].status = true; } catch (err) { passed = false; testResults[4].status = false; } // test 5: try { const noWhiteSpace = handleAsync.toString().replace(/\s/g,''); assert( noWhiteSpace.includes('dispatch(requestingData())') === true && noWhiteSpace.includes('dispatch(receivedData(data))') === true, error_5 ); testResults[5].status = true; } catch (err) { passed = false; testResults[5].status = false; } return { passed, testResults } } // liveRender modifies console.log in user input and returns message data ----------------------- export const liveRender = (code) => { // this code modifies the user input to return all // console.log statements as a message array to be // displayed on the client UI const prepend = ` (function() { let __Custom__Log = [] const message = (msg) => __Custom__Log.push(msg); ` const apend = `;\n return __Custom__Log })();` const consoleReplaced = code.replace(/console.log/g, 'message'); const hijackedCode = prepend.concat(consoleReplaced).concat(apend); let evaluatedCode; try { evaluatedCode = eval(hijackedCode); } catch (err) { console.log(err); } return evaluatedCode; }
Typo fix, creatStore => createStore
src/challenges/redux/curriculum/Redux_12.js
Typo fix, creatStore => createStore
<ide><path>rc/challenges/redux/curriculum/Redux_12.js <ide> middleware, to be exact. Let's briefly describe how to use this with Redux.<br><br> <ide> <ide> To include Redux Thunk middleware, we pass it as an argument to <code>Redux.applyMiddleware()</code>, which we provide as a <del>second optional parameter to our <code>creatStore()</code> function. Take a look at the code in the editor to see this. Then, <add>second optional parameter to our <code>createStore()</code> function. Take a look at the code in the editor to see this. Then, <ide> to create an asynchronous action, we return a function in our action creator that takes <code>dispatch</code> as an argument. <ide> Within this function we can dispatch actions and perform asynchronous requests.<br><br> <ide>
Java
apache-2.0
66215febcc9f9539de6dbf8be605f5e4e31c2ca0
0
godfreyhe/flink,zjureel/flink,rmetzger/flink,bowenli86/flink,apache/flink,zentol/flink,kl0u/flink,zentol/flink,rmetzger/flink,jinglining/flink,zentol/flink,ueshin/apache-flink,zjureel/flink,mbode/flink,apache/flink,GJL/flink,kaibozhou/flink,sunjincheng121/flink,greghogan/flink,hequn8128/flink,bowenli86/flink,tzulitai/flink,StephanEwen/incubator-flink,kl0u/flink,zjureel/flink,xccui/flink,mylog00/flink,wwjiang007/flink,fhueske/flink,kl0u/flink,kl0u/flink,kaibozhou/flink,StephanEwen/incubator-flink,tzulitai/flink,tony810430/flink,godfreyhe/flink,kaibozhou/flink,zjureel/flink,mbode/flink,mbode/flink,shaoxuan-wang/flink,lincoln-lil/flink,sunjincheng121/flink,shaoxuan-wang/flink,GJL/flink,mylog00/flink,StephanEwen/incubator-flink,rmetzger/flink,lincoln-lil/flink,GJL/flink,zentol/flink,jinglining/flink,greghogan/flink,tzulitai/flink,wwjiang007/flink,darionyaphet/flink,godfreyhe/flink,bowenli86/flink,fhueske/flink,fhueske/flink,clarkyzl/flink,mylog00/flink,zjureel/flink,sunjincheng121/flink,wwjiang007/flink,ueshin/apache-flink,jinglining/flink,mylog00/flink,tillrohrmann/flink,shaoxuan-wang/flink,aljoscha/flink,clarkyzl/flink,bowenli86/flink,lincoln-lil/flink,apache/flink,xccui/flink,aljoscha/flink,hequn8128/flink,tzulitai/flink,xccui/flink,jinglining/flink,apache/flink,twalthr/flink,twalthr/flink,mbode/flink,clarkyzl/flink,twalthr/flink,StephanEwen/incubator-flink,lincoln-lil/flink,tony810430/flink,ueshin/apache-flink,zentol/flink,twalthr/flink,wwjiang007/flink,kaibozhou/flink,greghogan/flink,rmetzger/flink,ueshin/apache-flink,apache/flink,rmetzger/flink,hequn8128/flink,bowenli86/flink,xccui/flink,jinglining/flink,wwjiang007/flink,GJL/flink,clarkyzl/flink,tzulitai/flink,sunjincheng121/flink,gyfora/flink,twalthr/flink,hequn8128/flink,gyfora/flink,tillrohrmann/flink,greghogan/flink,tony810430/flink,tony810430/flink,jinglining/flink,wwjiang007/flink,gyfora/flink,darionyaphet/flink,shaoxuan-wang/flink,kaibozhou/flink,GJL/flink,lincoln-lil/flink,aljoscha/flink,tillrohrmann/flink,fhueske/flink,fhueske/flink,apache/flink,darionyaphet/flink,lincoln-lil/flink,aljoscha/flink,bowenli86/flink,hequn8128/flink,gyfora/flink,GJL/flink,rmetzger/flink,fhueske/flink,xccui/flink,gyfora/flink,greghogan/flink,tillrohrmann/flink,shaoxuan-wang/flink,aljoscha/flink,aljoscha/flink,wwjiang007/flink,kl0u/flink,mylog00/flink,ueshin/apache-flink,tony810430/flink,darionyaphet/flink,mbode/flink,kaibozhou/flink,godfreyhe/flink,twalthr/flink,godfreyhe/flink,xccui/flink,StephanEwen/incubator-flink,StephanEwen/incubator-flink,clarkyzl/flink,rmetzger/flink,tillrohrmann/flink,godfreyhe/flink,tony810430/flink,gyfora/flink,shaoxuan-wang/flink,apache/flink,zjureel/flink,twalthr/flink,godfreyhe/flink,kl0u/flink,sunjincheng121/flink,gyfora/flink,lincoln-lil/flink,greghogan/flink,tony810430/flink,hequn8128/flink,tzulitai/flink,zjureel/flink,darionyaphet/flink,zentol/flink,zentol/flink,xccui/flink,tillrohrmann/flink,sunjincheng121/flink,tillrohrmann/flink
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.jobmanager; import org.apache.flink.api.common.JobID; import org.apache.flink.configuration.AkkaOptions; import org.apache.flink.configuration.CheckpointingOptions; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.JobManagerOptions; import org.apache.flink.configuration.TaskManagerOptions; import org.apache.flink.core.fs.Path; import org.apache.flink.queryablestate.KvStateID; import org.apache.flink.runtime.akka.AkkaUtils; import org.apache.flink.runtime.akka.ListeningBehaviour; import org.apache.flink.runtime.checkpoint.CheckpointDeclineReason; import org.apache.flink.runtime.checkpoint.CheckpointMetaData; import org.apache.flink.runtime.checkpoint.CheckpointMetrics; import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.checkpoint.CheckpointRetentionPolicy; import org.apache.flink.runtime.checkpoint.CheckpointType; import org.apache.flink.runtime.clusterframework.messages.NotifyResourceStarted; import org.apache.flink.runtime.clusterframework.messages.RegisterResourceManager; import org.apache.flink.runtime.clusterframework.messages.RegisterResourceManagerSuccessful; import org.apache.flink.runtime.clusterframework.messages.TriggerRegistrationAtJobManager; import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.runtime.highavailability.HighAvailabilityServices; import org.apache.flink.runtime.highavailability.nonha.embedded.EmbeddedHaServices; import org.apache.flink.runtime.instance.ActorGateway; import org.apache.flink.runtime.instance.AkkaActorGateway; import org.apache.flink.runtime.instance.HardwareDescription; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.JobStatus; import org.apache.flink.runtime.jobgraph.JobVertex; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration; import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings; import org.apache.flink.runtime.jobmanager.JobManagerHARecoveryTest.BlockingStatefulInvokable; import org.apache.flink.runtime.messages.FlinkJobNotFoundException; import org.apache.flink.runtime.messages.JobManagerMessages.CancellationFailure; import org.apache.flink.runtime.messages.JobManagerMessages.CancellationResponse; import org.apache.flink.runtime.messages.JobManagerMessages.CancellationSuccess; import org.apache.flink.runtime.messages.JobManagerMessages.SubmitJob; import org.apache.flink.runtime.messages.JobManagerMessages.TriggerSavepoint; import org.apache.flink.runtime.messages.JobManagerMessages.TriggerSavepointSuccess; import org.apache.flink.runtime.messages.RegistrationMessages; import org.apache.flink.runtime.metrics.NoOpMetricRegistry; import org.apache.flink.runtime.query.KvStateLocation; import org.apache.flink.runtime.query.KvStateMessage.LookupKvStateLocation; import org.apache.flink.runtime.query.KvStateMessage.NotifyKvStateRegistered; import org.apache.flink.runtime.query.KvStateMessage.NotifyKvStateUnregistered; import org.apache.flink.runtime.query.UnknownKvStateLocation; import org.apache.flink.runtime.state.KeyGroupRange; import org.apache.flink.runtime.taskmanager.TaskManager; import org.apache.flink.runtime.taskmanager.TaskManagerLocation; import org.apache.flink.runtime.testingUtils.TestingCluster; import org.apache.flink.runtime.testingUtils.TestingJobManager; import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages; import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.NotifyWhenJobStatus; import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.WaitForAllVerticesToBeRunning; import org.apache.flink.runtime.testingUtils.TestingMemoryArchivist; import org.apache.flink.runtime.testingUtils.TestingTaskManager; import org.apache.flink.runtime.testingUtils.TestingTaskManagerMessages; import org.apache.flink.runtime.testingUtils.TestingUtils; import org.apache.flink.runtime.testtasks.BlockingNoOpInvokable; import org.apache.flink.runtime.util.LeaderRetrievalUtils; import org.apache.flink.util.TestLogger; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; import akka.actor.Status; import akka.testkit.JavaTestKit; import akka.testkit.TestProbe; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Collections; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import scala.Option; import scala.Tuple2; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Deadline; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; import scala.reflect.ClassTag$; import static org.apache.flink.runtime.messages.JobManagerMessages.CancelJobWithSavepoint; import static org.apache.flink.runtime.messages.JobManagerMessages.JobSubmitSuccess; import static org.apache.flink.runtime.messages.JobManagerMessages.LeaderSessionMessage; import static org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.JobStatusIs; import static org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.NotifyWhenAtLeastNumTaskManagerAreRegistered; import static org.apache.flink.runtime.testingUtils.TestingUtils.TESTING_TIMEOUT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; public class JobManagerTest extends TestLogger { @Rule public final TemporaryFolder tmpFolder = new TemporaryFolder(); private static ActorSystem system; private HighAvailabilityServices highAvailabilityServices; @BeforeClass public static void setup() { system = AkkaUtils.createLocalActorSystem(new Configuration()); } @AfterClass public static void teardown() { JavaTestKit.shutdownActorSystem(system); } @Before public void setupTest() { highAvailabilityServices = new EmbeddedHaServices(TestingUtils.defaultExecutor()); } @After public void tearDownTest() throws Exception { highAvailabilityServices.closeAndCleanupAllData(); highAvailabilityServices = null; } /** * Tests that the JobManager handles {@link org.apache.flink.runtime.query.KvStateMessage} * instances as expected. */ @Test public void testKvStateMessages() throws Exception { Deadline deadline = new FiniteDuration(100, TimeUnit.SECONDS).fromNow(); Configuration config = new Configuration(); config.setString(AkkaOptions.ASK_TIMEOUT, "100ms"); ActorRef jobManagerActor = JobManager.startJobManagerActors( config, system, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), highAvailabilityServices, NoOpMetricRegistry.INSTANCE, Option.empty(), TestingJobManager.class, MemoryArchivist.class)._1(); UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), TestingUtils.TESTING_TIMEOUT()); ActorGateway jobManager = new AkkaActorGateway( jobManagerActor, leaderId); Configuration tmConfig = new Configuration(); tmConfig.setString(TaskManagerOptions.MANAGED_MEMORY_SIZE, "4m"); tmConfig.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 8); ActorRef taskManager = TaskManager.startTaskManagerComponentsAndActor( tmConfig, ResourceID.generate(), system, highAvailabilityServices, NoOpMetricRegistry.INSTANCE, "localhost", scala.Option.<String>empty(), true, TestingTaskManager.class); Future<Object> registrationFuture = jobManager .ask(new NotifyWhenAtLeastNumTaskManagerAreRegistered(1), deadline.timeLeft()); Await.ready(registrationFuture, deadline.timeLeft()); // // Location lookup // LookupKvStateLocation lookupNonExistingJob = new LookupKvStateLocation( new JobID(), "any-name"); Future<KvStateLocation> lookupFuture = jobManager .ask(lookupNonExistingJob, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); try { Await.result(lookupFuture, deadline.timeLeft()); fail("Did not throw expected Exception"); } catch (FlinkJobNotFoundException ignored) { // Expected } JobGraph jobGraph = new JobGraph("croissant"); JobVertex jobVertex1 = new JobVertex("cappuccino"); jobVertex1.setParallelism(4); jobVertex1.setMaxParallelism(16); jobVertex1.setInvokableClass(BlockingNoOpInvokable.class); JobVertex jobVertex2 = new JobVertex("americano"); jobVertex2.setParallelism(4); jobVertex2.setMaxParallelism(16); jobVertex2.setInvokableClass(BlockingNoOpInvokable.class); jobGraph.addVertex(jobVertex1); jobGraph.addVertex(jobVertex2); Future<JobSubmitSuccess> submitFuture = jobManager .ask(new SubmitJob(jobGraph, ListeningBehaviour.DETACHED), deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<JobSubmitSuccess>apply(JobSubmitSuccess.class)); Await.result(submitFuture, deadline.timeLeft()); Object lookupUnknownRegistrationName = new LookupKvStateLocation( jobGraph.getJobID(), "unknown"); lookupFuture = jobManager .ask(lookupUnknownRegistrationName, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); try { Await.result(lookupFuture, deadline.timeLeft()); fail("Did not throw expected Exception"); } catch (UnknownKvStateLocation ignored) { // Expected } // // Registration // NotifyKvStateRegistered registerNonExistingJob = new NotifyKvStateRegistered( new JobID(), new JobVertexID(), new KeyGroupRange(0, 0), "any-name", new KvStateID(), new InetSocketAddress(InetAddress.getLocalHost(), 1233)); jobManager.tell(registerNonExistingJob); LookupKvStateLocation lookupAfterRegistration = new LookupKvStateLocation( registerNonExistingJob.getJobId(), registerNonExistingJob.getRegistrationName()); lookupFuture = jobManager .ask(lookupAfterRegistration, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); try { Await.result(lookupFuture, deadline.timeLeft()); fail("Did not throw expected Exception"); } catch (FlinkJobNotFoundException ignored) { // Expected } NotifyKvStateRegistered registerForExistingJob = new NotifyKvStateRegistered( jobGraph.getJobID(), jobVertex1.getID(), new KeyGroupRange(0, 0), "register-me", new KvStateID(), new InetSocketAddress(InetAddress.getLocalHost(), 1293)); jobManager.tell(registerForExistingJob); lookupAfterRegistration = new LookupKvStateLocation( registerForExistingJob.getJobId(), registerForExistingJob.getRegistrationName()); lookupFuture = jobManager .ask(lookupAfterRegistration, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); KvStateLocation location = Await.result(lookupFuture, deadline.timeLeft()); assertNotNull(location); assertEquals(jobGraph.getJobID(), location.getJobId()); assertEquals(jobVertex1.getID(), location.getJobVertexId()); assertEquals(jobVertex1.getMaxParallelism(), location.getNumKeyGroups()); assertEquals(1, location.getNumRegisteredKeyGroups()); KeyGroupRange keyGroupRange = registerForExistingJob.getKeyGroupRange(); assertEquals(1, keyGroupRange.getNumberOfKeyGroups()); assertEquals(registerForExistingJob.getKvStateId(), location.getKvStateID(keyGroupRange.getStartKeyGroup())); assertEquals(registerForExistingJob.getKvStateServerAddress(), location.getKvStateServerAddress(keyGroupRange.getStartKeyGroup())); // // Unregistration // NotifyKvStateUnregistered unregister = new NotifyKvStateUnregistered( registerForExistingJob.getJobId(), registerForExistingJob.getJobVertexId(), registerForExistingJob.getKeyGroupRange(), registerForExistingJob.getRegistrationName()); jobManager.tell(unregister); lookupFuture = jobManager .ask(lookupAfterRegistration, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); try { Await.result(lookupFuture, deadline.timeLeft()); fail("Did not throw expected Exception"); } catch (UnknownKvStateLocation ignored) { // Expected } // // Duplicate registration fails task // NotifyKvStateRegistered register = new NotifyKvStateRegistered( jobGraph.getJobID(), jobVertex1.getID(), new KeyGroupRange(0, 0), "duplicate-me", new KvStateID(), new InetSocketAddress(InetAddress.getLocalHost(), 1293)); NotifyKvStateRegistered duplicate = new NotifyKvStateRegistered( jobGraph.getJobID(), jobVertex2.getID(), // <--- different operator, but... new KeyGroupRange(0, 0), "duplicate-me", // ...same name new KvStateID(), new InetSocketAddress(InetAddress.getLocalHost(), 1293)); Future<TestingJobManagerMessages.JobStatusIs> failedFuture = jobManager .ask(new NotifyWhenJobStatus(jobGraph.getJobID(), JobStatus.FAILED), deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<JobStatusIs>apply(JobStatusIs.class)); jobManager.tell(register); jobManager.tell(duplicate); // Wait for failure JobStatusIs jobStatus = Await.result(failedFuture, deadline.timeLeft()); assertEquals(JobStatus.FAILED, jobStatus.state()); } @Test public void testCancelWithSavepoint() throws Exception { File defaultSavepointDir = tmpFolder.newFolder(); FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS); Configuration config = new Configuration(); config.setString(CheckpointingOptions.SAVEPOINT_DIRECTORY, defaultSavepointDir.toURI().toString()); ActorSystem actorSystem = null; ActorGateway jobManager = null; ActorGateway archiver = null; ActorGateway taskManager = null; try { actorSystem = AkkaUtils.createLocalActorSystem(new Configuration()); Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors( config, actorSystem, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), highAvailabilityServices, NoOpMetricRegistry.INSTANCE, Option.empty(), Option.apply("jm"), Option.apply("arch"), TestingJobManager.class, TestingMemoryArchivist.class); UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), TestingUtils.TESTING_TIMEOUT()); jobManager = new AkkaActorGateway(master._1(), leaderId); archiver = new AkkaActorGateway(master._2(), leaderId); ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor( config, ResourceID.generate(), actorSystem, highAvailabilityServices, NoOpMetricRegistry.INSTANCE, "localhost", Option.apply("tm"), true, TestingTaskManager.class); taskManager = new AkkaActorGateway(taskManagerRef, leaderId); // Wait until connected Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor()); Await.ready(taskManager.ask(msg, timeout), timeout); // Create job graph JobVertex sourceVertex = new JobVertex("Source"); sourceVertex.setInvokableClass(BlockingStatefulInvokable.class); sourceVertex.setParallelism(1); JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), new CheckpointCoordinatorConfiguration( 3600000, 3600000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true), null); jobGraph.setSnapshotSettings(snapshottingSettings); // Submit job graph msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED); Await.result(jobManager.ask(msg, timeout), timeout); // Wait for all tasks to be running msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID()); Await.result(jobManager.ask(msg, timeout), timeout); // Notify when cancelled msg = new NotifyWhenJobStatus(jobGraph.getJobID(), JobStatus.CANCELED); Future<Object> cancelled = jobManager.ask(msg, timeout); // Cancel with savepoint String savepointPath = null; for (int i = 0; i < 10; i++) { msg = new CancelJobWithSavepoint(jobGraph.getJobID(), null); CancellationResponse cancelResp = (CancellationResponse) Await.result(jobManager.ask(msg, timeout), timeout); if (cancelResp instanceof CancellationFailure) { CancellationFailure failure = (CancellationFailure) cancelResp; if (failure.cause().getMessage().contains(CheckpointDeclineReason.NOT_ALL_REQUIRED_TASKS_RUNNING.message())) { Thread.sleep(10); // wait and retry } else { failure.cause().printStackTrace(); fail("Failed to cancel job: " + failure.cause().getMessage()); } } else { savepointPath = ((CancellationSuccess) cancelResp).savepointPath(); break; } } // Verify savepoint path assertNotNull("Savepoint not triggered", savepointPath); // Wait for job status change Await.ready(cancelled, timeout); File savepointFile = new File(new Path(savepointPath).getPath()); assertTrue(savepointFile.exists()); } finally { if (actorSystem != null) { actorSystem.terminate(); } if (archiver != null) { archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (jobManager != null) { jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (taskManager != null) { taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (actorSystem != null) { Await.result(actorSystem.whenTerminated(), TESTING_TIMEOUT()); } } } /** * Tests that a failed savepoint does not cancel the job and new checkpoints are triggered * after the failed cancel-with-savepoint. */ @Test public void testCancelJobWithSavepointFailurePeriodicCheckpoints() throws Exception { File savepointTarget = tmpFolder.newFolder(); // A source that declines savepoints, simulating the behaviour of a // failed savepoint. JobVertex sourceVertex = new JobVertex("Source"); sourceVertex.setInvokableClass(FailOnSavepointSourceTask.class); sourceVertex.setParallelism(1); JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); CheckpointCoordinatorConfiguration coordConfig = new CheckpointCoordinatorConfiguration( 50, 3600000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), coordConfig, null); jobGraph.setSnapshotSettings(snapshottingSettings); final TestingCluster testingCluster = new TestingCluster( new Configuration(), highAvailabilityServices, true, false); try { testingCluster.start(true); FiniteDuration askTimeout = new FiniteDuration(30, TimeUnit.SECONDS); ActorGateway jobManager = testingCluster.getLeaderGateway(askTimeout); testingCluster.submitJobDetached(jobGraph); // Wait for the source to be running otherwise the savepoint // barrier will not reach the task. Future<Object> allTasksAlive = jobManager.ask( new WaitForAllVerticesToBeRunning(jobGraph.getJobID()), askTimeout); Await.ready(allTasksAlive, askTimeout); // Cancel with savepoint. The expected outcome is that cancellation // fails due to a failed savepoint. After this, periodic checkpoints // should resume. Future<Object> cancellationFuture = jobManager.ask( new CancelJobWithSavepoint(jobGraph.getJobID(), savepointTarget.getAbsolutePath()), askTimeout); Object cancellationResponse = Await.result(cancellationFuture, askTimeout); if (cancellationResponse instanceof CancellationFailure) { if (!FailOnSavepointSourceTask.CHECKPOINT_AFTER_SAVEPOINT_LATCH.await(30, TimeUnit.SECONDS)) { fail("No checkpoint was triggered after failed savepoint within expected duration"); } } else { fail("Unexpected cancellation response from JobManager: " + cancellationResponse); } } finally { testingCluster.stop(); } } /** * Tests that a meaningful exception is returned if no savepoint directory is * configured. */ @Test public void testCancelWithSavepointNoDirectoriesConfigured() throws Exception { FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS); Configuration config = new Configuration(); ActorSystem actorSystem = null; ActorGateway jobManager = null; ActorGateway archiver = null; ActorGateway taskManager = null; try { actorSystem = AkkaUtils.createLocalActorSystem(new Configuration()); Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors( config, actorSystem, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), highAvailabilityServices, NoOpMetricRegistry.INSTANCE, Option.empty(), Option.apply("jm"), Option.apply("arch"), TestingJobManager.class, TestingMemoryArchivist.class); UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), TestingUtils.TESTING_TIMEOUT()); jobManager = new AkkaActorGateway(master._1(), leaderId); archiver = new AkkaActorGateway(master._2(), leaderId); ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor( config, ResourceID.generate(), actorSystem, highAvailabilityServices, NoOpMetricRegistry.INSTANCE, "localhost", Option.apply("tm"), true, TestingTaskManager.class); taskManager = new AkkaActorGateway(taskManagerRef, leaderId); // Wait until connected Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor()); Await.ready(taskManager.ask(msg, timeout), timeout); // Create job graph JobVertex sourceVertex = new JobVertex("Source"); sourceVertex.setInvokableClass(BlockingStatefulInvokable.class); sourceVertex.setParallelism(1); JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), new CheckpointCoordinatorConfiguration( 3600000, 3600000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true), null); jobGraph.setSnapshotSettings(snapshottingSettings); // Submit job graph msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED); Await.result(jobManager.ask(msg, timeout), timeout); // Wait for all tasks to be running msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID()); Await.result(jobManager.ask(msg, timeout), timeout); // Cancel with savepoint msg = new CancelJobWithSavepoint(jobGraph.getJobID(), null); CancellationResponse cancelResp = (CancellationResponse) Await.result(jobManager.ask(msg, timeout), timeout); if (cancelResp instanceof CancellationFailure) { CancellationFailure failure = (CancellationFailure) cancelResp; assertTrue(failure.cause() instanceof IllegalStateException); assertTrue(failure.cause().getMessage().contains("savepoint directory")); } else { fail("Unexpected cancellation response from JobManager: " + cancelResp); } } finally { if (actorSystem != null) { actorSystem.terminate(); } if (archiver != null) { archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (jobManager != null) { jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (taskManager != null) { taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } } } /** * Tests that we can trigger a savepoint when periodic checkpoints are disabled. */ @Test public void testSavepointWithDeactivatedPeriodicCheckpointing() throws Exception { File defaultSavepointDir = tmpFolder.newFolder(); FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS); Configuration config = new Configuration(); config.setString(CheckpointingOptions.SAVEPOINT_DIRECTORY, defaultSavepointDir.toURI().toString()); ActorSystem actorSystem = null; ActorGateway jobManager = null; ActorGateway archiver = null; ActorGateway taskManager = null; try { actorSystem = AkkaUtils.createLocalActorSystem(new Configuration()); Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors( config, actorSystem, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), highAvailabilityServices, NoOpMetricRegistry.INSTANCE, Option.empty(), Option.apply("jm"), Option.apply("arch"), TestingJobManager.class, TestingMemoryArchivist.class); UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), TestingUtils.TESTING_TIMEOUT()); jobManager = new AkkaActorGateway(master._1(), leaderId); archiver = new AkkaActorGateway(master._2(), leaderId); ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor( config, ResourceID.generate(), actorSystem, highAvailabilityServices, NoOpMetricRegistry.INSTANCE, "localhost", Option.apply("tm"), true, TestingTaskManager.class); taskManager = new AkkaActorGateway(taskManagerRef, leaderId); // Wait until connected Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor()); Await.ready(taskManager.ask(msg, timeout), timeout); // Create job graph JobVertex sourceVertex = new JobVertex("Source"); sourceVertex.setInvokableClass(BlockingStatefulInvokable.class); sourceVertex.setParallelism(1); JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), new CheckpointCoordinatorConfiguration( Long.MAX_VALUE, // deactivated checkpointing 360000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true), null); jobGraph.setSnapshotSettings(snapshottingSettings); // Submit job graph msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED); Await.result(jobManager.ask(msg, timeout), timeout); // Wait for all tasks to be running msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID()); Await.result(jobManager.ask(msg, timeout), timeout); // Cancel with savepoint File targetDirectory = tmpFolder.newFolder(); msg = new TriggerSavepoint(jobGraph.getJobID(), Option.apply(targetDirectory.getAbsolutePath())); Future<Object> future = jobManager.ask(msg, timeout); Object result = Await.result(future, timeout); assertTrue("Did not trigger savepoint", result instanceof TriggerSavepointSuccess); assertEquals(1, targetDirectory.listFiles().length); } finally { if (actorSystem != null) { actorSystem.terminate(); } if (archiver != null) { archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (jobManager != null) { jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (taskManager != null) { taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (actorSystem != null) { Await.result(actorSystem.whenTerminated(), TestingUtils.TESTING_TIMEOUT()); } } } /** * This tests makes sure that triggering a reconnection from the ResourceManager will stop after a new * ResourceManager has connected. Furthermore it makes sure that there is not endless loop of reconnection * commands (see FLINK-6341). */ @Test public void testResourceManagerConnection() throws TimeoutException, InterruptedException { FiniteDuration testTimeout = new FiniteDuration(30L, TimeUnit.SECONDS); final long reconnectionInterval = 200L; final Configuration configuration = new Configuration(); configuration.setLong(JobManagerOptions.RESOURCE_MANAGER_RECONNECT_INTERVAL, reconnectionInterval); final ActorSystem actorSystem = AkkaUtils.createLocalActorSystem(configuration); try { final ActorGateway jmGateway = TestingUtils.createJobManager( actorSystem, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), configuration, highAvailabilityServices); final TestProbe probe = TestProbe.apply(actorSystem); final AkkaActorGateway rmGateway = new AkkaActorGateway(probe.ref(), HighAvailabilityServices.DEFAULT_LEADER_ID); // wait for the JobManager to become the leader Future<?> leaderFuture = jmGateway.ask(TestingJobManagerMessages.getNotifyWhenLeader(), testTimeout); Await.ready(leaderFuture, testTimeout); jmGateway.tell(new RegisterResourceManager(probe.ref()), rmGateway); LeaderSessionMessage leaderSessionMessage = probe.expectMsgClass(LeaderSessionMessage.class); assertEquals(jmGateway.leaderSessionID(), leaderSessionMessage.leaderSessionID()); assertTrue(leaderSessionMessage.message() instanceof RegisterResourceManagerSuccessful); jmGateway.tell( new RegistrationMessages.RegisterTaskManager( ResourceID.generate(), mock(TaskManagerLocation.class), new HardwareDescription(1, 1L, 1L, 1L), 1)); leaderSessionMessage = probe.expectMsgClass(LeaderSessionMessage.class); assertTrue(leaderSessionMessage.message() instanceof NotifyResourceStarted); // fail the NotifyResourceStarted so that we trigger the reconnection process on the JobManager's side probe.lastSender().tell(new Status.Failure(new Exception("Test exception")), ActorRef.noSender()); Deadline reconnectionDeadline = new FiniteDuration(5L * reconnectionInterval, TimeUnit.MILLISECONDS).fromNow(); boolean registered = false; while (reconnectionDeadline.hasTimeLeft()) { try { leaderSessionMessage = probe.expectMsgClass(reconnectionDeadline.timeLeft(), LeaderSessionMessage.class); } catch (AssertionError ignored) { // expected timeout after the reconnectionDeadline has been exceeded continue; } if (leaderSessionMessage.message() instanceof TriggerRegistrationAtJobManager) { if (registered) { fail("A successful registration should not be followed by another TriggerRegistrationAtJobManager message."); } jmGateway.tell(new RegisterResourceManager(probe.ref()), rmGateway); } else if (leaderSessionMessage.message() instanceof RegisterResourceManagerSuccessful) { // now we should no longer receive TriggerRegistrationAtJobManager messages registered = true; } else { fail("Received unknown message: " + leaderSessionMessage.message() + '.'); } } assertTrue(registered); } finally { // cleanup the actor system and with it all of the started actors if not already terminated actorSystem.terminate(); Await.ready(actorSystem.whenTerminated(), Duration.Inf()); } } /** * A blocking stateful source task that declines savepoints. */ public static class FailOnSavepointSourceTask extends AbstractInvokable { private static final CountDownLatch CHECKPOINT_AFTER_SAVEPOINT_LATCH = new CountDownLatch(1); private boolean receivedSavepoint; /** * Create an Invokable task and set its environment. * * @param environment The environment assigned to this invokable. */ public FailOnSavepointSourceTask(Environment environment) { super(environment); } @Override public void invoke() throws Exception { new CountDownLatch(1).await(); } @Override public boolean triggerCheckpoint( CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) throws Exception { if (checkpointOptions.getCheckpointType() == CheckpointType.SAVEPOINT) { receivedSavepoint = true; return false; } else if (receivedSavepoint) { CHECKPOINT_AFTER_SAVEPOINT_LATCH.countDown(); return true; } return true; } @Override public void triggerCheckpointOnBarrier( CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions, CheckpointMetrics checkpointMetrics) throws Exception { throw new UnsupportedOperationException("This is meant to be used as a source"); } @Override public void abortCheckpointOnBarrier(long checkpointId, Throwable cause) throws Exception { } @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { } } }
flink-runtime/src/test/java/org/apache/flink/runtime/jobmanager/JobManagerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.jobmanager; import org.apache.flink.api.common.JobID; import org.apache.flink.configuration.AkkaOptions; import org.apache.flink.configuration.CheckpointingOptions; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.JobManagerOptions; import org.apache.flink.configuration.TaskManagerOptions; import org.apache.flink.core.fs.Path; import org.apache.flink.queryablestate.KvStateID; import org.apache.flink.runtime.akka.AkkaUtils; import org.apache.flink.runtime.akka.ListeningBehaviour; import org.apache.flink.runtime.checkpoint.CheckpointDeclineReason; import org.apache.flink.runtime.checkpoint.CheckpointMetaData; import org.apache.flink.runtime.checkpoint.CheckpointMetrics; import org.apache.flink.runtime.checkpoint.CheckpointOptions; import org.apache.flink.runtime.checkpoint.CheckpointRetentionPolicy; import org.apache.flink.runtime.checkpoint.CheckpointType; import org.apache.flink.runtime.clusterframework.messages.NotifyResourceStarted; import org.apache.flink.runtime.clusterframework.messages.RegisterResourceManager; import org.apache.flink.runtime.clusterframework.messages.RegisterResourceManagerSuccessful; import org.apache.flink.runtime.clusterframework.messages.TriggerRegistrationAtJobManager; import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.runtime.highavailability.HighAvailabilityServices; import org.apache.flink.runtime.highavailability.nonha.embedded.EmbeddedHaServices; import org.apache.flink.runtime.instance.ActorGateway; import org.apache.flink.runtime.instance.AkkaActorGateway; import org.apache.flink.runtime.instance.HardwareDescription; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.JobStatus; import org.apache.flink.runtime.jobgraph.JobVertex; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration; import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings; import org.apache.flink.runtime.jobmanager.JobManagerHARecoveryTest.BlockingStatefulInvokable; import org.apache.flink.runtime.messages.FlinkJobNotFoundException; import org.apache.flink.runtime.messages.JobManagerMessages.CancelJob; import org.apache.flink.runtime.messages.JobManagerMessages.CancellationFailure; import org.apache.flink.runtime.messages.JobManagerMessages.CancellationResponse; import org.apache.flink.runtime.messages.JobManagerMessages.CancellationSuccess; import org.apache.flink.runtime.messages.JobManagerMessages.SubmitJob; import org.apache.flink.runtime.messages.JobManagerMessages.TriggerSavepoint; import org.apache.flink.runtime.messages.JobManagerMessages.TriggerSavepointSuccess; import org.apache.flink.runtime.messages.RegistrationMessages; import org.apache.flink.runtime.metrics.NoOpMetricRegistry; import org.apache.flink.runtime.query.KvStateLocation; import org.apache.flink.runtime.query.KvStateMessage.LookupKvStateLocation; import org.apache.flink.runtime.query.KvStateMessage.NotifyKvStateRegistered; import org.apache.flink.runtime.query.KvStateMessage.NotifyKvStateUnregistered; import org.apache.flink.runtime.query.UnknownKvStateLocation; import org.apache.flink.runtime.state.KeyGroupRange; import org.apache.flink.runtime.taskmanager.TaskManager; import org.apache.flink.runtime.taskmanager.TaskManagerLocation; import org.apache.flink.runtime.testingUtils.TestingCluster; import org.apache.flink.runtime.testingUtils.TestingJobManager; import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages; import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.NotifyWhenJobStatus; import org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.WaitForAllVerticesToBeRunning; import org.apache.flink.runtime.testingUtils.TestingMemoryArchivist; import org.apache.flink.runtime.testingUtils.TestingTaskManager; import org.apache.flink.runtime.testingUtils.TestingTaskManagerMessages; import org.apache.flink.runtime.testingUtils.TestingUtils; import org.apache.flink.runtime.testtasks.BlockingNoOpInvokable; import org.apache.flink.runtime.util.LeaderRetrievalUtils; import org.apache.flink.util.TestLogger; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.PoisonPill; import akka.actor.Status; import akka.testkit.JavaTestKit; import akka.testkit.TestProbe; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Collections; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import scala.Option; import scala.Tuple2; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Deadline; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; import scala.reflect.ClassTag$; import static org.apache.flink.runtime.messages.JobManagerMessages.CancelJobWithSavepoint; import static org.apache.flink.runtime.messages.JobManagerMessages.JobResultFailure; import static org.apache.flink.runtime.messages.JobManagerMessages.JobSubmitSuccess; import static org.apache.flink.runtime.messages.JobManagerMessages.LeaderSessionMessage; import static org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.JobStatusIs; import static org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.NotifyWhenAtLeastNumTaskManagerAreRegistered; import static org.apache.flink.runtime.testingUtils.TestingUtils.TESTING_TIMEOUT; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; public class JobManagerTest extends TestLogger { @Rule public final TemporaryFolder tmpFolder = new TemporaryFolder(); private static ActorSystem system; private HighAvailabilityServices highAvailabilityServices; @BeforeClass public static void setup() { system = AkkaUtils.createLocalActorSystem(new Configuration()); } @AfterClass public static void teardown() { JavaTestKit.shutdownActorSystem(system); } @Before public void setupTest() { highAvailabilityServices = new EmbeddedHaServices(TestingUtils.defaultExecutor()); } @After public void tearDownTest() throws Exception { highAvailabilityServices.closeAndCleanupAllData(); highAvailabilityServices = null; } /** * Tests that the JobManager handles {@link org.apache.flink.runtime.query.KvStateMessage} * instances as expected. */ @Test public void testKvStateMessages() throws Exception { Deadline deadline = new FiniteDuration(100, TimeUnit.SECONDS).fromNow(); Configuration config = new Configuration(); config.setString(AkkaOptions.ASK_TIMEOUT, "100ms"); ActorRef jobManagerActor = JobManager.startJobManagerActors( config, system, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), highAvailabilityServices, NoOpMetricRegistry.INSTANCE, Option.empty(), TestingJobManager.class, MemoryArchivist.class)._1(); UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), TestingUtils.TESTING_TIMEOUT()); ActorGateway jobManager = new AkkaActorGateway( jobManagerActor, leaderId); Configuration tmConfig = new Configuration(); tmConfig.setString(TaskManagerOptions.MANAGED_MEMORY_SIZE, "4m"); tmConfig.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 8); ActorRef taskManager = TaskManager.startTaskManagerComponentsAndActor( tmConfig, ResourceID.generate(), system, highAvailabilityServices, NoOpMetricRegistry.INSTANCE, "localhost", scala.Option.<String>empty(), true, TestingTaskManager.class); Future<Object> registrationFuture = jobManager .ask(new NotifyWhenAtLeastNumTaskManagerAreRegistered(1), deadline.timeLeft()); Await.ready(registrationFuture, deadline.timeLeft()); // // Location lookup // LookupKvStateLocation lookupNonExistingJob = new LookupKvStateLocation( new JobID(), "any-name"); Future<KvStateLocation> lookupFuture = jobManager .ask(lookupNonExistingJob, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); try { Await.result(lookupFuture, deadline.timeLeft()); fail("Did not throw expected Exception"); } catch (FlinkJobNotFoundException ignored) { // Expected } JobGraph jobGraph = new JobGraph("croissant"); JobVertex jobVertex1 = new JobVertex("cappuccino"); jobVertex1.setParallelism(4); jobVertex1.setMaxParallelism(16); jobVertex1.setInvokableClass(BlockingNoOpInvokable.class); JobVertex jobVertex2 = new JobVertex("americano"); jobVertex2.setParallelism(4); jobVertex2.setMaxParallelism(16); jobVertex2.setInvokableClass(BlockingNoOpInvokable.class); jobGraph.addVertex(jobVertex1); jobGraph.addVertex(jobVertex2); Future<JobSubmitSuccess> submitFuture = jobManager .ask(new SubmitJob(jobGraph, ListeningBehaviour.DETACHED), deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<JobSubmitSuccess>apply(JobSubmitSuccess.class)); Await.result(submitFuture, deadline.timeLeft()); Object lookupUnknownRegistrationName = new LookupKvStateLocation( jobGraph.getJobID(), "unknown"); lookupFuture = jobManager .ask(lookupUnknownRegistrationName, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); try { Await.result(lookupFuture, deadline.timeLeft()); fail("Did not throw expected Exception"); } catch (UnknownKvStateLocation ignored) { // Expected } // // Registration // NotifyKvStateRegistered registerNonExistingJob = new NotifyKvStateRegistered( new JobID(), new JobVertexID(), new KeyGroupRange(0, 0), "any-name", new KvStateID(), new InetSocketAddress(InetAddress.getLocalHost(), 1233)); jobManager.tell(registerNonExistingJob); LookupKvStateLocation lookupAfterRegistration = new LookupKvStateLocation( registerNonExistingJob.getJobId(), registerNonExistingJob.getRegistrationName()); lookupFuture = jobManager .ask(lookupAfterRegistration, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); try { Await.result(lookupFuture, deadline.timeLeft()); fail("Did not throw expected Exception"); } catch (FlinkJobNotFoundException ignored) { // Expected } NotifyKvStateRegistered registerForExistingJob = new NotifyKvStateRegistered( jobGraph.getJobID(), jobVertex1.getID(), new KeyGroupRange(0, 0), "register-me", new KvStateID(), new InetSocketAddress(InetAddress.getLocalHost(), 1293)); jobManager.tell(registerForExistingJob); lookupAfterRegistration = new LookupKvStateLocation( registerForExistingJob.getJobId(), registerForExistingJob.getRegistrationName()); lookupFuture = jobManager .ask(lookupAfterRegistration, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); KvStateLocation location = Await.result(lookupFuture, deadline.timeLeft()); assertNotNull(location); assertEquals(jobGraph.getJobID(), location.getJobId()); assertEquals(jobVertex1.getID(), location.getJobVertexId()); assertEquals(jobVertex1.getMaxParallelism(), location.getNumKeyGroups()); assertEquals(1, location.getNumRegisteredKeyGroups()); KeyGroupRange keyGroupRange = registerForExistingJob.getKeyGroupRange(); assertEquals(1, keyGroupRange.getNumberOfKeyGroups()); assertEquals(registerForExistingJob.getKvStateId(), location.getKvStateID(keyGroupRange.getStartKeyGroup())); assertEquals(registerForExistingJob.getKvStateServerAddress(), location.getKvStateServerAddress(keyGroupRange.getStartKeyGroup())); // // Unregistration // NotifyKvStateUnregistered unregister = new NotifyKvStateUnregistered( registerForExistingJob.getJobId(), registerForExistingJob.getJobVertexId(), registerForExistingJob.getKeyGroupRange(), registerForExistingJob.getRegistrationName()); jobManager.tell(unregister); lookupFuture = jobManager .ask(lookupAfterRegistration, deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<KvStateLocation>apply(KvStateLocation.class)); try { Await.result(lookupFuture, deadline.timeLeft()); fail("Did not throw expected Exception"); } catch (UnknownKvStateLocation ignored) { // Expected } // // Duplicate registration fails task // NotifyKvStateRegistered register = new NotifyKvStateRegistered( jobGraph.getJobID(), jobVertex1.getID(), new KeyGroupRange(0, 0), "duplicate-me", new KvStateID(), new InetSocketAddress(InetAddress.getLocalHost(), 1293)); NotifyKvStateRegistered duplicate = new NotifyKvStateRegistered( jobGraph.getJobID(), jobVertex2.getID(), // <--- different operator, but... new KeyGroupRange(0, 0), "duplicate-me", // ...same name new KvStateID(), new InetSocketAddress(InetAddress.getLocalHost(), 1293)); Future<TestingJobManagerMessages.JobStatusIs> failedFuture = jobManager .ask(new NotifyWhenJobStatus(jobGraph.getJobID(), JobStatus.FAILED), deadline.timeLeft()) .mapTo(ClassTag$.MODULE$.<JobStatusIs>apply(JobStatusIs.class)); jobManager.tell(register); jobManager.tell(duplicate); // Wait for failure JobStatusIs jobStatus = Await.result(failedFuture, deadline.timeLeft()); assertEquals(JobStatus.FAILED, jobStatus.state()); } @Test public void testCancelWithSavepoint() throws Exception { File defaultSavepointDir = tmpFolder.newFolder(); FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS); Configuration config = new Configuration(); config.setString(CheckpointingOptions.SAVEPOINT_DIRECTORY, defaultSavepointDir.toURI().toString()); ActorSystem actorSystem = null; ActorGateway jobManager = null; ActorGateway archiver = null; ActorGateway taskManager = null; try { actorSystem = AkkaUtils.createLocalActorSystem(new Configuration()); Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors( config, actorSystem, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), highAvailabilityServices, NoOpMetricRegistry.INSTANCE, Option.empty(), Option.apply("jm"), Option.apply("arch"), TestingJobManager.class, TestingMemoryArchivist.class); UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), TestingUtils.TESTING_TIMEOUT()); jobManager = new AkkaActorGateway(master._1(), leaderId); archiver = new AkkaActorGateway(master._2(), leaderId); ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor( config, ResourceID.generate(), actorSystem, highAvailabilityServices, NoOpMetricRegistry.INSTANCE, "localhost", Option.apply("tm"), true, TestingTaskManager.class); taskManager = new AkkaActorGateway(taskManagerRef, leaderId); // Wait until connected Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor()); Await.ready(taskManager.ask(msg, timeout), timeout); // Create job graph JobVertex sourceVertex = new JobVertex("Source"); sourceVertex.setInvokableClass(BlockingStatefulInvokable.class); sourceVertex.setParallelism(1); JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), new CheckpointCoordinatorConfiguration( 3600000, 3600000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true), null); jobGraph.setSnapshotSettings(snapshottingSettings); // Submit job graph msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED); Await.result(jobManager.ask(msg, timeout), timeout); // Wait for all tasks to be running msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID()); Await.result(jobManager.ask(msg, timeout), timeout); // Notify when cancelled msg = new NotifyWhenJobStatus(jobGraph.getJobID(), JobStatus.CANCELED); Future<Object> cancelled = jobManager.ask(msg, timeout); // Cancel with savepoint String savepointPath = null; for (int i = 0; i < 10; i++) { msg = new CancelJobWithSavepoint(jobGraph.getJobID(), null); CancellationResponse cancelResp = (CancellationResponse) Await.result(jobManager.ask(msg, timeout), timeout); if (cancelResp instanceof CancellationFailure) { CancellationFailure failure = (CancellationFailure) cancelResp; if (failure.cause().getMessage().contains(CheckpointDeclineReason.NOT_ALL_REQUIRED_TASKS_RUNNING.message())) { Thread.sleep(10); // wait and retry } else { failure.cause().printStackTrace(); fail("Failed to cancel job: " + failure.cause().getMessage()); } } else { savepointPath = ((CancellationSuccess) cancelResp).savepointPath(); break; } } // Verify savepoint path assertNotNull("Savepoint not triggered", savepointPath); // Wait for job status change Await.ready(cancelled, timeout); File savepointFile = new File(new Path(savepointPath).getPath()); assertTrue(savepointFile.exists()); } finally { if (actorSystem != null) { actorSystem.terminate(); } if (archiver != null) { archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (jobManager != null) { jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (taskManager != null) { taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (actorSystem != null) { Await.result(actorSystem.whenTerminated(), TESTING_TIMEOUT()); } } } /** * Tests that a failed savepoint does not cancel the job and new checkpoints are triggered * after the failed cancel-with-savepoint. */ @Test public void testCancelJobWithSavepointFailurePeriodicCheckpoints() throws Exception { File savepointTarget = tmpFolder.newFolder(); // A source that declines savepoints, simulating the behaviour of a // failed savepoint. JobVertex sourceVertex = new JobVertex("Source"); sourceVertex.setInvokableClass(FailOnSavepointSourceTask.class); sourceVertex.setParallelism(1); JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); CheckpointCoordinatorConfiguration coordConfig = new CheckpointCoordinatorConfiguration( 50, 3600000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), coordConfig, null); jobGraph.setSnapshotSettings(snapshottingSettings); final TestingCluster testingCluster = new TestingCluster( new Configuration(), highAvailabilityServices, true, false); try { testingCluster.start(true); FiniteDuration askTimeout = new FiniteDuration(30, TimeUnit.SECONDS); ActorGateway jobManager = testingCluster.getLeaderGateway(askTimeout); testingCluster.submitJobDetached(jobGraph); // Wait for the source to be running otherwise the savepoint // barrier will not reach the task. Future<Object> allTasksAlive = jobManager.ask( new WaitForAllVerticesToBeRunning(jobGraph.getJobID()), askTimeout); Await.ready(allTasksAlive, askTimeout); // Cancel with savepoint. The expected outcome is that cancellation // fails due to a failed savepoint. After this, periodic checkpoints // should resume. Future<Object> cancellationFuture = jobManager.ask( new CancelJobWithSavepoint(jobGraph.getJobID(), savepointTarget.getAbsolutePath()), askTimeout); Object cancellationResponse = Await.result(cancellationFuture, askTimeout); if (cancellationResponse instanceof CancellationFailure) { if (!FailOnSavepointSourceTask.CHECKPOINT_AFTER_SAVEPOINT_LATCH.await(30, TimeUnit.SECONDS)) { fail("No checkpoint was triggered after failed savepoint within expected duration"); } } else { fail("Unexpected cancellation response from JobManager: " + cancellationResponse); } } finally { testingCluster.stop(); } } /** * Tests that a meaningful exception is returned if no savepoint directory is * configured. */ @Test public void testCancelWithSavepointNoDirectoriesConfigured() throws Exception { FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS); Configuration config = new Configuration(); ActorSystem actorSystem = null; ActorGateway jobManager = null; ActorGateway archiver = null; ActorGateway taskManager = null; try { actorSystem = AkkaUtils.createLocalActorSystem(new Configuration()); Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors( config, actorSystem, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), highAvailabilityServices, NoOpMetricRegistry.INSTANCE, Option.empty(), Option.apply("jm"), Option.apply("arch"), TestingJobManager.class, TestingMemoryArchivist.class); UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), TestingUtils.TESTING_TIMEOUT()); jobManager = new AkkaActorGateway(master._1(), leaderId); archiver = new AkkaActorGateway(master._2(), leaderId); ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor( config, ResourceID.generate(), actorSystem, highAvailabilityServices, NoOpMetricRegistry.INSTANCE, "localhost", Option.apply("tm"), true, TestingTaskManager.class); taskManager = new AkkaActorGateway(taskManagerRef, leaderId); // Wait until connected Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor()); Await.ready(taskManager.ask(msg, timeout), timeout); // Create job graph JobVertex sourceVertex = new JobVertex("Source"); sourceVertex.setInvokableClass(BlockingStatefulInvokable.class); sourceVertex.setParallelism(1); JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), new CheckpointCoordinatorConfiguration( 3600000, 3600000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true), null); jobGraph.setSnapshotSettings(snapshottingSettings); // Submit job graph msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED); Await.result(jobManager.ask(msg, timeout), timeout); // Wait for all tasks to be running msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID()); Await.result(jobManager.ask(msg, timeout), timeout); // Cancel with savepoint msg = new CancelJobWithSavepoint(jobGraph.getJobID(), null); CancellationResponse cancelResp = (CancellationResponse) Await.result(jobManager.ask(msg, timeout), timeout); if (cancelResp instanceof CancellationFailure) { CancellationFailure failure = (CancellationFailure) cancelResp; assertTrue(failure.cause() instanceof IllegalStateException); assertTrue(failure.cause().getMessage().contains("savepoint directory")); } else { fail("Unexpected cancellation response from JobManager: " + cancelResp); } } finally { if (actorSystem != null) { actorSystem.terminate(); } if (archiver != null) { archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (jobManager != null) { jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (taskManager != null) { taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } } } /** * Tests that we can trigger a savepoint when periodic checkpoints are disabled. */ @Test public void testSavepointWithDeactivatedPeriodicCheckpointing() throws Exception { File defaultSavepointDir = tmpFolder.newFolder(); FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS); Configuration config = new Configuration(); config.setString(CheckpointingOptions.SAVEPOINT_DIRECTORY, defaultSavepointDir.toURI().toString()); ActorSystem actorSystem = null; ActorGateway jobManager = null; ActorGateway archiver = null; ActorGateway taskManager = null; try { actorSystem = AkkaUtils.createLocalActorSystem(new Configuration()); Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors( config, actorSystem, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), highAvailabilityServices, NoOpMetricRegistry.INSTANCE, Option.empty(), Option.apply("jm"), Option.apply("arch"), TestingJobManager.class, TestingMemoryArchivist.class); UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), TestingUtils.TESTING_TIMEOUT()); jobManager = new AkkaActorGateway(master._1(), leaderId); archiver = new AkkaActorGateway(master._2(), leaderId); ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor( config, ResourceID.generate(), actorSystem, highAvailabilityServices, NoOpMetricRegistry.INSTANCE, "localhost", Option.apply("tm"), true, TestingTaskManager.class); taskManager = new AkkaActorGateway(taskManagerRef, leaderId); // Wait until connected Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor()); Await.ready(taskManager.ask(msg, timeout), timeout); // Create job graph JobVertex sourceVertex = new JobVertex("Source"); sourceVertex.setInvokableClass(BlockingStatefulInvokable.class); sourceVertex.setParallelism(1); JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), new CheckpointCoordinatorConfiguration( Long.MAX_VALUE, // deactivated checkpointing 360000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true), null); jobGraph.setSnapshotSettings(snapshottingSettings); // Submit job graph msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED); Await.result(jobManager.ask(msg, timeout), timeout); // Wait for all tasks to be running msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID()); Await.result(jobManager.ask(msg, timeout), timeout); // Cancel with savepoint File targetDirectory = tmpFolder.newFolder(); msg = new TriggerSavepoint(jobGraph.getJobID(), Option.apply(targetDirectory.getAbsolutePath())); Future<Object> future = jobManager.ask(msg, timeout); Object result = Await.result(future, timeout); assertTrue("Did not trigger savepoint", result instanceof TriggerSavepointSuccess); assertEquals(1, targetDirectory.listFiles().length); } finally { if (actorSystem != null) { actorSystem.terminate(); } if (archiver != null) { archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (jobManager != null) { jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (taskManager != null) { taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (actorSystem != null) { Await.result(actorSystem.whenTerminated(), TestingUtils.TESTING_TIMEOUT()); } } } /** * Tests that configured {@link SavepointRestoreSettings} are respected. */ @Test public void testSavepointRestoreSettings() throws Exception { FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS); ActorSystem actorSystem = null; ActorGateway jobManager = null; ActorGateway archiver = null; ActorGateway taskManager = null; try { actorSystem = AkkaUtils.createLocalActorSystem(new Configuration()); Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors( new Configuration(), actorSystem, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), highAvailabilityServices, NoOpMetricRegistry.INSTANCE, Option.empty(), Option.apply("jm"), Option.apply("arch"), TestingJobManager.class, TestingMemoryArchivist.class); UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), TestingUtils.TESTING_TIMEOUT()); jobManager = new AkkaActorGateway(master._1(), leaderId); archiver = new AkkaActorGateway(master._2(), leaderId); Configuration tmConfig = new Configuration(); tmConfig.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 4); ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor( tmConfig, ResourceID.generate(), actorSystem, highAvailabilityServices, NoOpMetricRegistry.INSTANCE, "localhost", Option.apply("tm"), true, TestingTaskManager.class); taskManager = new AkkaActorGateway(taskManagerRef, leaderId); // Wait until connected Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor()); Await.ready(taskManager.ask(msg, timeout), timeout); // Create job graph JobVertex sourceVertex = new JobVertex("Source"); sourceVertex.setInvokableClass(BlockingStatefulInvokable.class); sourceVertex.setParallelism(1); JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), Collections.singletonList(sourceVertex.getID()), new CheckpointCoordinatorConfiguration( Long.MAX_VALUE, // deactivated checkpointing 360000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true), null); jobGraph.setSnapshotSettings(snapshottingSettings); // Submit job graph msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED); Await.result(jobManager.ask(msg, timeout), timeout); // Wait for all tasks to be running msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID()); Await.result(jobManager.ask(msg, timeout), timeout); // Trigger savepoint File targetDirectory = tmpFolder.newFolder(); msg = new TriggerSavepoint(jobGraph.getJobID(), Option.apply(targetDirectory.getAbsolutePath())); Future<Object> future = jobManager.ask(msg, timeout); Object result = Await.result(future, timeout); String savepointPath = ((TriggerSavepointSuccess) result).savepointPath(); // Cancel because of restarts msg = new TestingJobManagerMessages.NotifyWhenJobRemoved(jobGraph.getJobID()); Future<?> removedFuture = jobManager.ask(msg, timeout); Future<?> cancelFuture = jobManager.ask(new CancelJob(jobGraph.getJobID()), timeout); Object response = Await.result(cancelFuture, timeout); assertTrue("Unexpected response: " + response, response instanceof CancellationSuccess); Await.ready(removedFuture, timeout); // Adjust the job (we need a new operator ID) JobVertex newSourceVertex = new JobVertex("NewSource"); newSourceVertex.setInvokableClass(BlockingStatefulInvokable.class); newSourceVertex.setParallelism(1); JobGraph newJobGraph = new JobGraph("NewTestingJob", newSourceVertex); JobCheckpointingSettings newSnapshottingSettings = new JobCheckpointingSettings( Collections.singletonList(newSourceVertex.getID()), Collections.singletonList(newSourceVertex.getID()), Collections.singletonList(newSourceVertex.getID()), new CheckpointCoordinatorConfiguration( Long.MAX_VALUE, // deactivated checkpointing 360000, 0, Integer.MAX_VALUE, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true), null); newJobGraph.setSnapshotSettings(newSnapshottingSettings); SavepointRestoreSettings restoreSettings = SavepointRestoreSettings.forPath(savepointPath, false); newJobGraph.setSavepointRestoreSettings(restoreSettings); msg = new SubmitJob(newJobGraph, ListeningBehaviour.DETACHED); response = Await.result(jobManager.ask(msg, timeout), timeout); assertTrue("Unexpected response: " + response, response instanceof JobResultFailure); JobResultFailure failure = (JobResultFailure) response; Throwable cause = failure.cause().deserializeError(ClassLoader.getSystemClassLoader()); assertTrue(cause instanceof IllegalStateException); assertTrue(cause.getMessage().contains("allowNonRestoredState")); // Wait until removed msg = new TestingJobManagerMessages.NotifyWhenJobRemoved(newJobGraph.getJobID()); Await.ready(jobManager.ask(msg, timeout), timeout); // Resubmit, but allow non restored state now restoreSettings = SavepointRestoreSettings.forPath(savepointPath, true); newJobGraph.setSavepointRestoreSettings(restoreSettings); msg = new SubmitJob(newJobGraph, ListeningBehaviour.DETACHED); response = Await.result(jobManager.ask(msg, timeout), timeout); assertTrue("Unexpected response: " + response, response instanceof JobSubmitSuccess); } finally { if (actorSystem != null) { actorSystem.terminate(); } if (archiver != null) { archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (jobManager != null) { jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (taskManager != null) { taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); } if (actorSystem != null) { Await.ready(actorSystem.whenTerminated(), TestingUtils.TESTING_TIMEOUT()); } } } /** * This tests makes sure that triggering a reconnection from the ResourceManager will stop after a new * ResourceManager has connected. Furthermore it makes sure that there is not endless loop of reconnection * commands (see FLINK-6341). */ @Test public void testResourceManagerConnection() throws TimeoutException, InterruptedException { FiniteDuration testTimeout = new FiniteDuration(30L, TimeUnit.SECONDS); final long reconnectionInterval = 200L; final Configuration configuration = new Configuration(); configuration.setLong(JobManagerOptions.RESOURCE_MANAGER_RECONNECT_INTERVAL, reconnectionInterval); final ActorSystem actorSystem = AkkaUtils.createLocalActorSystem(configuration); try { final ActorGateway jmGateway = TestingUtils.createJobManager( actorSystem, TestingUtils.defaultExecutor(), TestingUtils.defaultExecutor(), configuration, highAvailabilityServices); final TestProbe probe = TestProbe.apply(actorSystem); final AkkaActorGateway rmGateway = new AkkaActorGateway(probe.ref(), HighAvailabilityServices.DEFAULT_LEADER_ID); // wait for the JobManager to become the leader Future<?> leaderFuture = jmGateway.ask(TestingJobManagerMessages.getNotifyWhenLeader(), testTimeout); Await.ready(leaderFuture, testTimeout); jmGateway.tell(new RegisterResourceManager(probe.ref()), rmGateway); LeaderSessionMessage leaderSessionMessage = probe.expectMsgClass(LeaderSessionMessage.class); assertEquals(jmGateway.leaderSessionID(), leaderSessionMessage.leaderSessionID()); assertTrue(leaderSessionMessage.message() instanceof RegisterResourceManagerSuccessful); jmGateway.tell( new RegistrationMessages.RegisterTaskManager( ResourceID.generate(), mock(TaskManagerLocation.class), new HardwareDescription(1, 1L, 1L, 1L), 1)); leaderSessionMessage = probe.expectMsgClass(LeaderSessionMessage.class); assertTrue(leaderSessionMessage.message() instanceof NotifyResourceStarted); // fail the NotifyResourceStarted so that we trigger the reconnection process on the JobManager's side probe.lastSender().tell(new Status.Failure(new Exception("Test exception")), ActorRef.noSender()); Deadline reconnectionDeadline = new FiniteDuration(5L * reconnectionInterval, TimeUnit.MILLISECONDS).fromNow(); boolean registered = false; while (reconnectionDeadline.hasTimeLeft()) { try { leaderSessionMessage = probe.expectMsgClass(reconnectionDeadline.timeLeft(), LeaderSessionMessage.class); } catch (AssertionError ignored) { // expected timeout after the reconnectionDeadline has been exceeded continue; } if (leaderSessionMessage.message() instanceof TriggerRegistrationAtJobManager) { if (registered) { fail("A successful registration should not be followed by another TriggerRegistrationAtJobManager message."); } jmGateway.tell(new RegisterResourceManager(probe.ref()), rmGateway); } else if (leaderSessionMessage.message() instanceof RegisterResourceManagerSuccessful) { // now we should no longer receive TriggerRegistrationAtJobManager messages registered = true; } else { fail("Received unknown message: " + leaderSessionMessage.message() + '.'); } } assertTrue(registered); } finally { // cleanup the actor system and with it all of the started actors if not already terminated actorSystem.terminate(); Await.ready(actorSystem.whenTerminated(), Duration.Inf()); } } /** * A blocking stateful source task that declines savepoints. */ public static class FailOnSavepointSourceTask extends AbstractInvokable { private static final CountDownLatch CHECKPOINT_AFTER_SAVEPOINT_LATCH = new CountDownLatch(1); private boolean receivedSavepoint; /** * Create an Invokable task and set its environment. * * @param environment The environment assigned to this invokable. */ public FailOnSavepointSourceTask(Environment environment) { super(environment); } @Override public void invoke() throws Exception { new CountDownLatch(1).await(); } @Override public boolean triggerCheckpoint( CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) throws Exception { if (checkpointOptions.getCheckpointType() == CheckpointType.SAVEPOINT) { receivedSavepoint = true; return false; } else if (receivedSavepoint) { CHECKPOINT_AFTER_SAVEPOINT_LATCH.countDown(); return true; } return true; } @Override public void triggerCheckpointOnBarrier( CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions, CheckpointMetrics checkpointMetrics) throws Exception { throw new UnsupportedOperationException("This is meant to be used as a source"); } @Override public void abortCheckpointOnBarrier(long checkpointId, Throwable cause) throws Exception { } @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { } } }
[FLINK-10406] (Part 4) testSavepointRestoreSettings testSavepointRestoreSettings is covered by JobMaster#testRestoringFromSavepoint the triggerSavepoint part is covered by JobMasterTriggerSavepointIT, and the submit failure part should be taken care of when port JobSubmitTest, which has a test testAnswerFailureWhenSavepointReadFails
flink-runtime/src/test/java/org/apache/flink/runtime/jobmanager/JobManagerTest.java
[FLINK-10406] (Part 4) testSavepointRestoreSettings
<ide><path>link-runtime/src/test/java/org/apache/flink/runtime/jobmanager/JobManagerTest.java <ide> import org.apache.flink.runtime.jobgraph.JobStatus; <ide> import org.apache.flink.runtime.jobgraph.JobVertex; <ide> import org.apache.flink.runtime.jobgraph.JobVertexID; <del>import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings; <ide> import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; <ide> import org.apache.flink.runtime.jobgraph.tasks.CheckpointCoordinatorConfiguration; <ide> import org.apache.flink.runtime.jobgraph.tasks.JobCheckpointingSettings; <ide> import org.apache.flink.runtime.jobmanager.JobManagerHARecoveryTest.BlockingStatefulInvokable; <ide> import org.apache.flink.runtime.messages.FlinkJobNotFoundException; <del>import org.apache.flink.runtime.messages.JobManagerMessages.CancelJob; <ide> import org.apache.flink.runtime.messages.JobManagerMessages.CancellationFailure; <ide> import org.apache.flink.runtime.messages.JobManagerMessages.CancellationResponse; <ide> import org.apache.flink.runtime.messages.JobManagerMessages.CancellationSuccess; <ide> import scala.reflect.ClassTag$; <ide> <ide> import static org.apache.flink.runtime.messages.JobManagerMessages.CancelJobWithSavepoint; <del>import static org.apache.flink.runtime.messages.JobManagerMessages.JobResultFailure; <ide> import static org.apache.flink.runtime.messages.JobManagerMessages.JobSubmitSuccess; <ide> import static org.apache.flink.runtime.messages.JobManagerMessages.LeaderSessionMessage; <ide> import static org.apache.flink.runtime.testingUtils.TestingJobManagerMessages.JobStatusIs; <ide> } <ide> <ide> /** <del> * Tests that configured {@link SavepointRestoreSettings} are respected. <del> */ <del> @Test <del> public void testSavepointRestoreSettings() throws Exception { <del> FiniteDuration timeout = new FiniteDuration(30, TimeUnit.SECONDS); <del> <del> ActorSystem actorSystem = null; <del> ActorGateway jobManager = null; <del> ActorGateway archiver = null; <del> ActorGateway taskManager = null; <del> try { <del> actorSystem = AkkaUtils.createLocalActorSystem(new Configuration()); <del> <del> Tuple2<ActorRef, ActorRef> master = JobManager.startJobManagerActors( <del> new Configuration(), <del> actorSystem, <del> TestingUtils.defaultExecutor(), <del> TestingUtils.defaultExecutor(), <del> highAvailabilityServices, <del> NoOpMetricRegistry.INSTANCE, <del> Option.empty(), <del> Option.apply("jm"), <del> Option.apply("arch"), <del> TestingJobManager.class, <del> TestingMemoryArchivist.class); <del> <del> UUID leaderId = LeaderRetrievalUtils.retrieveLeaderSessionId( <del> highAvailabilityServices.getJobManagerLeaderRetriever(HighAvailabilityServices.DEFAULT_JOB_ID), <del> TestingUtils.TESTING_TIMEOUT()); <del> <del> jobManager = new AkkaActorGateway(master._1(), leaderId); <del> archiver = new AkkaActorGateway(master._2(), leaderId); <del> <del> Configuration tmConfig = new Configuration(); <del> tmConfig.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 4); <del> <del> ActorRef taskManagerRef = TaskManager.startTaskManagerComponentsAndActor( <del> tmConfig, <del> ResourceID.generate(), <del> actorSystem, <del> highAvailabilityServices, <del> NoOpMetricRegistry.INSTANCE, <del> "localhost", <del> Option.apply("tm"), <del> true, <del> TestingTaskManager.class); <del> <del> taskManager = new AkkaActorGateway(taskManagerRef, leaderId); <del> <del> // Wait until connected <del> Object msg = new TestingTaskManagerMessages.NotifyWhenRegisteredAtJobManager(jobManager.actor()); <del> Await.ready(taskManager.ask(msg, timeout), timeout); <del> <del> // Create job graph <del> JobVertex sourceVertex = new JobVertex("Source"); <del> sourceVertex.setInvokableClass(BlockingStatefulInvokable.class); <del> sourceVertex.setParallelism(1); <del> <del> JobGraph jobGraph = new JobGraph("TestingJob", sourceVertex); <del> <del> JobCheckpointingSettings snapshottingSettings = new JobCheckpointingSettings( <del> Collections.singletonList(sourceVertex.getID()), <del> Collections.singletonList(sourceVertex.getID()), <del> Collections.singletonList(sourceVertex.getID()), <del> new CheckpointCoordinatorConfiguration( <del> Long.MAX_VALUE, // deactivated checkpointing <del> 360000, <del> 0, <del> Integer.MAX_VALUE, <del> CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, <del> true), <del> null); <del> <del> jobGraph.setSnapshotSettings(snapshottingSettings); <del> <del> // Submit job graph <del> msg = new SubmitJob(jobGraph, ListeningBehaviour.DETACHED); <del> Await.result(jobManager.ask(msg, timeout), timeout); <del> <del> // Wait for all tasks to be running <del> msg = new TestingJobManagerMessages.WaitForAllVerticesToBeRunning(jobGraph.getJobID()); <del> Await.result(jobManager.ask(msg, timeout), timeout); <del> <del> // Trigger savepoint <del> File targetDirectory = tmpFolder.newFolder(); <del> msg = new TriggerSavepoint(jobGraph.getJobID(), Option.apply(targetDirectory.getAbsolutePath())); <del> Future<Object> future = jobManager.ask(msg, timeout); <del> Object result = Await.result(future, timeout); <del> <del> String savepointPath = ((TriggerSavepointSuccess) result).savepointPath(); <del> <del> // Cancel because of restarts <del> msg = new TestingJobManagerMessages.NotifyWhenJobRemoved(jobGraph.getJobID()); <del> Future<?> removedFuture = jobManager.ask(msg, timeout); <del> <del> Future<?> cancelFuture = jobManager.ask(new CancelJob(jobGraph.getJobID()), timeout); <del> Object response = Await.result(cancelFuture, timeout); <del> assertTrue("Unexpected response: " + response, response instanceof CancellationSuccess); <del> <del> Await.ready(removedFuture, timeout); <del> <del> // Adjust the job (we need a new operator ID) <del> JobVertex newSourceVertex = new JobVertex("NewSource"); <del> newSourceVertex.setInvokableClass(BlockingStatefulInvokable.class); <del> newSourceVertex.setParallelism(1); <del> <del> JobGraph newJobGraph = new JobGraph("NewTestingJob", newSourceVertex); <del> <del> JobCheckpointingSettings newSnapshottingSettings = new JobCheckpointingSettings( <del> Collections.singletonList(newSourceVertex.getID()), <del> Collections.singletonList(newSourceVertex.getID()), <del> Collections.singletonList(newSourceVertex.getID()), <del> new CheckpointCoordinatorConfiguration( <del> Long.MAX_VALUE, // deactivated checkpointing <del> 360000, <del> 0, <del> Integer.MAX_VALUE, <del> CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, <del> true), <del> null); <del> <del> newJobGraph.setSnapshotSettings(newSnapshottingSettings); <del> <del> SavepointRestoreSettings restoreSettings = SavepointRestoreSettings.forPath(savepointPath, false); <del> newJobGraph.setSavepointRestoreSettings(restoreSettings); <del> <del> msg = new SubmitJob(newJobGraph, ListeningBehaviour.DETACHED); <del> response = Await.result(jobManager.ask(msg, timeout), timeout); <del> <del> assertTrue("Unexpected response: " + response, response instanceof JobResultFailure); <del> <del> JobResultFailure failure = (JobResultFailure) response; <del> Throwable cause = failure.cause().deserializeError(ClassLoader.getSystemClassLoader()); <del> <del> assertTrue(cause instanceof IllegalStateException); <del> assertTrue(cause.getMessage().contains("allowNonRestoredState")); <del> <del> // Wait until removed <del> msg = new TestingJobManagerMessages.NotifyWhenJobRemoved(newJobGraph.getJobID()); <del> Await.ready(jobManager.ask(msg, timeout), timeout); <del> <del> // Resubmit, but allow non restored state now <del> restoreSettings = SavepointRestoreSettings.forPath(savepointPath, true); <del> newJobGraph.setSavepointRestoreSettings(restoreSettings); <del> <del> msg = new SubmitJob(newJobGraph, ListeningBehaviour.DETACHED); <del> response = Await.result(jobManager.ask(msg, timeout), timeout); <del> <del> assertTrue("Unexpected response: " + response, response instanceof JobSubmitSuccess); <del> } finally { <del> if (actorSystem != null) { <del> actorSystem.terminate(); <del> } <del> <del> if (archiver != null) { <del> archiver.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); <del> } <del> <del> if (jobManager != null) { <del> jobManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); <del> } <del> <del> if (taskManager != null) { <del> taskManager.actor().tell(PoisonPill.getInstance(), ActorRef.noSender()); <del> } <del> <del> if (actorSystem != null) { <del> Await.ready(actorSystem.whenTerminated(), TestingUtils.TESTING_TIMEOUT()); <del> } <del> } <del> } <del> <del> /** <ide> * This tests makes sure that triggering a reconnection from the ResourceManager will stop after a new <ide> * ResourceManager has connected. Furthermore it makes sure that there is not endless loop of reconnection <ide> * commands (see FLINK-6341).
Java
mit
2c98b25c8a60089e704429d186814865e2c3788f
0
jenkinsci/warnings-plugin,jenkinsci/warnings-plugin,jenkinsci/warnings-plugin
package io.jenkins.plugins.analysis.warnings; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.recipes.WithTimeout; import org.xml.sax.SAXException; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.google.errorprone.annotations.CanIgnoreReturnValue; import io.jenkins.plugins.analysis.core.model.AnalysisResult; import static io.jenkins.plugins.analysis.core.model.Assertions.*; import io.jenkins.plugins.analysis.core.model.StaticAnalysisTool; import io.jenkins.plugins.analysis.core.steps.IssuesRecorder; import io.jenkins.plugins.analysis.core.steps.ToolConfiguration; import io.jenkins.plugins.analysis.core.testutil.IntegrationTest; import io.jenkins.plugins.analysis.core.views.ResultAction; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; /** * Integration tests of the warnings plug-in in freestyle jobs. Tests the new recorder {@link IssuesRecorder}. * * @author Ullrich Hafner */ public class IssuesRecorderITest extends IntegrationTest { /** * Runs the Eclipse parser on an empty workspace: the build should report 0 issues and an error message. */ @Test public void shouldCreateEmptyResult() { FreeStyleProject project = createJob(); enableWarnings(project); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS); assertThat(result).hasTotalSize(0); assertThat(result).hasErrorMessages("No files found for pattern '**/*issues.txt'. Configuration error?"); } /** * Runs the Eclipse parser on an output file that contains several issues: the build should report 8 issues. */ @Test public void shouldCreateResultWithWarnings() { FreeStyleProject project = createJobWithWorkspaceFile("eclipse.txt"); enableWarnings(project); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS); assertThat(result).hasTotalSize(8); assertThat(result).hasInfoMessages("Resolved module names for 8 issues", "Resolved package names of 4 affected files"); } /** * Sets the UNSTABLE threshold to 8 and parse a file that contains exactly 8 warnings: the build should be * unstable. */ @Test public void shouldCreateUnstableResult() { FreeStyleProject project = createJobWithWorkspaceFile("eclipse.txt"); enableWarnings(project, publisher -> publisher.setUnstableTotalAll(7)); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.UNSTABLE); assertThat(result).hasTotalSize(8); assertThat(result).hasOverallResult(Result.UNSTABLE); HtmlPage page = getWebPage(result); assertThat(page.getElementsByIdAndOrName("statistics")).hasSize(1); } private HtmlPage getWebPage(final AnalysisResult result) { try { WebClient webClient = j.createWebClient(); webClient.setJavaScriptEnabled(false); return webClient.getPage(result.getOwner(), "eclipseResult"); } catch (SAXException | IOException e) { throw new AssertionError(e); } } /** * Creates a new {@link FreeStyleProject freestyle job}. The job will get a generated name. * * @return the created job */ private FreeStyleProject createJob() { try { return j.createFreeStyleProject(); } catch (IOException e) { throw new AssertionError(e); } } /** * Creates a new {@link FreeStyleProject freestyle job} and copies the specified resources to the workspace folder. * The job will get a generated name. * * @param fileNames * the files to copy to the workspace * * @return the created job */ private FreeStyleProject createJobWithWorkspaceFile(final String... fileNames) { FreeStyleProject job = createJob(); copyFilesToWorkspace(job, fileNames); return job; } /** * Enables the warnings plugin for the specified job. I.e., it registers a new {@link IssuesRecorder } recorder for * the job. * * @param job * the job to register the recorder for * * @return the created recorder */ @CanIgnoreReturnValue private IssuesRecorder enableWarnings(final FreeStyleProject job) { IssuesRecorder publisher = new IssuesRecorder(); publisher.setTools(Collections.singletonList(new ToolConfiguration("**/*issues.txt", new Eclipse()))); job.getPublishersList().add(publisher); return publisher; } /** * Enables the warnings plugin for the specified job. I.e., it registers a new {@link IssuesRecorder } recorder for * the job. * * @param job * the job to register the recorder for * @param checkbox * aggregation is true or false * @param toolPattern1 * the first new filename in the workspace * @param tool1 * class of the first tool * @param toolPattern2 * the second new filename in the workspace * @param tool2 * class of the second tool */ @CanIgnoreReturnValue private void enableWarningsAggregation(final FreeStyleProject job, final boolean checkbox, final String toolPattern1, final StaticAnalysisTool tool1, final String toolPattern2, final StaticAnalysisTool tool2) { IssuesRecorder publisher = new IssuesRecorder(); publisher.setAggregatingResults(checkbox); List<ToolConfiguration> toolList = new ArrayList<>(); toolList.add(new ToolConfiguration(toolPattern1, tool1)); toolList.add(new ToolConfiguration(toolPattern2, tool2)); publisher.setTools(toolList); job.getPublishersList().add(publisher); } /** * Enables the warnings plugin for the specified job. I.e., it registers a new {@link IssuesRecorder } recorder for * the job. * * @param job * the job to register the recorder for * @param configuration * configuration of the recorder * * @return the created recorder */ @CanIgnoreReturnValue private IssuesRecorder enableWarnings(final FreeStyleProject job, final Consumer<IssuesRecorder> configuration) { IssuesRecorder publisher = enableWarnings(job); configuration.accept(publisher); return publisher; } /** * Schedules a new build for the specified job and returns the created {@link AnalysisResult} after the build has * been finished. * * @param job * the job to schedule * @param status * the expected result for the build * * @return the created {@link ResultAction} */ @SuppressWarnings({"illegalcatch", "OverlyBroadCatchBlock"}) private AnalysisResult scheduleBuildAndAssertStatus(final FreeStyleProject job, final Result status) { try { FreeStyleBuild build = j.assertBuildStatus(status, job.scheduleBuild2(0)); ResultAction action = build.getAction(ResultAction.class); assertThat(action).isNotNull(); return action.getResult(); } catch (Exception e) { throw new AssertionError(e); } } /** * Schedules a new build for the specified job and returns the created {@link List<AnalysisResult>} after the build * has been finished as one result of both tools. * * @param job * the job to schedule * @param status * the expected result of both tools for the build * * @return the created {@link List<ResultAction>} */ @SuppressWarnings({"illegalcatch", "OverlyBroadCatchBlock"}) private List<AnalysisResult> scheduleBuildAndAssertStatusForBothTools(final FreeStyleProject job, final Result status) { try { FreeStyleBuild build = j.assertBuildStatus(status, job.scheduleBuild2(0)); List<ResultAction> actions = build.getActions(ResultAction.class); List<AnalysisResult> results = new ArrayList<>(); for (ResultAction elements : actions) { results.add(elements.getResult()); } return results; } catch (Exception e) { throw new AssertionError(e); } } /** * Runs the CheckStyle and PMD tools on an output file that contains several issues: the build should report 6 and 4 * issues. */ @Test @WithTimeout(1000) public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateFalse() { FreeStyleProject project = createJobWithWorkspaceFile("checkstyle.xml", "pmd-warnings.xml"); enableWarningsAggregation(project, false, "**/checkstyle-issues.txt", new CheckStyle(), "**/pmd-warnings-issues.txt", new Pmd()); List<AnalysisResult> results = scheduleBuildAndAssertStatusForBothTools(project, Result.SUCCESS); for (AnalysisResult element : results) { if (element.getId().equals("checkstyle")) { assertThat(element.getTotalSize()).isEqualTo(6); } else { assertThat(element.getId()).isEqualTo("pmd"); assertThat(element.getTotalSize()).isEqualTo(4); } assertThat(element).hasOverallResult(Result.SUCCESS); } } /** * Runs the CheckStyle and PMD tools on an output file that contains one issue: the build should report 10 issues. */ @Test @WithTimeout(1000) public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateTrue() { FreeStyleProject project = createJobWithWorkspaceFile("checkstyle.xml", "pmd-warnings.xml"); enableWarningsAggregation(project, true, "**/checkstyle-issues.txt", new CheckStyle(), "**/pmd-warnings-issues.txt", new Pmd()); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS); assertThat(result).hasTotalSize(10); assertThat(result.getSizePerOrigin()).containsKeys("checkstyle", "pmd"); assertThat(result).hasOverallResult(Result.SUCCESS); } /** * Runs only the CheckStyle tool multiple times on an output file that contains not several issues and produce a * failure. */ @Test @WithTimeout(1000) public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateFalseAndSameTool() { FreeStyleProject project = createJobWithWorkspaceFile("checkstyle2.xml", "checkstyle3.xml"); enableWarningsAggregation(project, false, "**/checkstyle2-issues.txt", new CheckStyle(), "**/checkstyle3-issues.txt", new CheckStyle()); List<AnalysisResult> results = scheduleBuildAndAssertStatusForBothTools(project, Result.FAILURE); for (AnalysisResult elements : results) { assertThat(elements).hasErrorMessages(); } } /** * Runs only the CheckStyle tool multiple times on an output file that contains one issues: the build should report * 6 issues. */ @Test @WithTimeout(1000) public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateTrueAndSameTool() { FreeStyleProject project = createJobWithWorkspaceFile("checkstyle2.xml", "checkstyle3.xml"); enableWarningsAggregation(project, true, "**/checkstyle2-issues.txt", new CheckStyle(), "**/checkstyle3-issues.txt", new CheckStyle()); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS); assertThat(result).hasTotalSize(6); assertThat(result.getSizePerOrigin()).containsKeys("checkstyle"); assertThat(result).hasOverallResult(Result.SUCCESS); } }
src/test/java/io/jenkins/plugins/analysis/warnings/IssuesRecorderITest.java
package io.jenkins.plugins.analysis.warnings; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.recipes.WithTimeout; import org.xml.sax.SAXException; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.google.errorprone.annotations.CanIgnoreReturnValue; import io.jenkins.plugins.analysis.core.model.AnalysisResult; import static io.jenkins.plugins.analysis.core.model.Assertions.*; import io.jenkins.plugins.analysis.core.model.StaticAnalysisTool; import io.jenkins.plugins.analysis.core.steps.IssuesRecorder; import io.jenkins.plugins.analysis.core.steps.ToolConfiguration; import io.jenkins.plugins.analysis.core.testutil.IntegrationTest; import io.jenkins.plugins.analysis.core.views.ResultAction; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; /** * Integration tests of the warnings plug-in in freestyle jobs. Tests the new recorder {@link IssuesRecorder}. * * @author Ullrich Hafner */ public class IssuesRecorderITest extends IntegrationTest { /** * Runs the Eclipse parser on an empty workspace: the build should report 0 issues and an error message. */ @Test public void shouldCreateEmptyResult() { FreeStyleProject project = createJob(); enableWarnings(project); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS); assertThat(result).hasTotalSize(0); assertThat(result).hasErrorMessages("No files found for pattern '**/*issues.txt'. Configuration error?"); } /** * Runs the Eclipse parser on an output file that contains several issues: the build should report 8 issues. */ @Test public void shouldCreateResultWithWarnings() { FreeStyleProject project = createJobWithWorkspaceFile("eclipse.txt"); enableWarnings(project); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS); assertThat(result).hasTotalSize(8); assertThat(result).hasInfoMessages("Resolved module names for 8 issues", "Resolved package names of 4 affected files"); } /** * Sets the UNSTABLE threshold to 8 and parse a file that contains exactly 8 warnings: the build should be * unstable. */ @Test public void shouldCreateUnstableResult() { FreeStyleProject project = createJobWithWorkspaceFile("eclipse.txt"); enableWarnings(project, publisher -> publisher.setUnstableTotalAll(7)); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.UNSTABLE); assertThat(result).hasTotalSize(8); assertThat(result).hasOverallResult(Result.UNSTABLE); HtmlPage page = getWebPage(result); assertThat(page.getElementsByIdAndOrName("statistics")).hasSize(1); } private HtmlPage getWebPage(final AnalysisResult result) { try { WebClient webClient = j.createWebClient(); webClient.setJavaScriptEnabled(false); return webClient.getPage(result.getOwner(), "eclipseResult"); } catch (SAXException | IOException e) { throw new AssertionError(e); } } /** * Creates a new {@link FreeStyleProject freestyle job}. The job will get a generated name. * * @return the created job */ private FreeStyleProject createJob() { try { return j.createFreeStyleProject(); } catch (IOException e) { throw new AssertionError(e); } } /** * Creates a new {@link FreeStyleProject freestyle job} and copies the specified resources to the workspace folder. * The job will get a generated name. * * @param fileNames * the files to copy to the workspace * * @return the created job */ private FreeStyleProject createJobWithWorkspaceFile(final String... fileNames) { FreeStyleProject job = createJob(); copyFilesToWorkspace(job, fileNames); return job; } /** * Enables the warnings plugin for the specified job. I.e., it registers a new {@link IssuesRecorder } recorder for * the job. * * @param job * the job to register the recorder for * * @return the created recorder */ @CanIgnoreReturnValue private IssuesRecorder enableWarnings(final FreeStyleProject job) { IssuesRecorder publisher = new IssuesRecorder(); publisher.setTools(Collections.singletonList(new ToolConfiguration("**/*issues.txt", new Eclipse()))); job.getPublishersList().add(publisher); return publisher; } /** * Enables the warnings plugin for the specified job. I.e., it registers a new {@link IssuesRecorder } recorder for * the job. * * @param job * the job to register the recorder for * @param checkbox * aggregation is true or false * @param toolPattern1 * the first new filename in the workspace * @param tool1 * class of the first tool * @param toolPattern2 * the second new filename in the workspace * @param tool2 * class of the second tool * * @return the created recorder */ @CanIgnoreReturnValue private IssuesRecorder enableWarningsAggregation(final FreeStyleProject job, final boolean checkbox, final String toolPattern1, final StaticAnalysisTool tool1, final String toolPattern2, final StaticAnalysisTool tool2) { IssuesRecorder publisher = new IssuesRecorder(); publisher.setAggregatingResults(checkbox); List<ToolConfiguration> toolList = new ArrayList<>(); toolList.add(new ToolConfiguration(toolPattern1, tool1)); toolList.add(new ToolConfiguration(toolPattern2, tool2)); publisher.setTools(toolList); job.getPublishersList().add(publisher); return publisher; } /** * Enables the warnings plugin for the specified job. I.e., it registers a new {@link IssuesRecorder } recorder for * the job. * * @param job * the job to register the recorder for * @param configuration * configuration of the recorder * * @return the created recorder */ @CanIgnoreReturnValue private IssuesRecorder enableWarnings(final FreeStyleProject job, final Consumer<IssuesRecorder> configuration) { IssuesRecorder publisher = enableWarnings(job); configuration.accept(publisher); return publisher; } /** * Schedules a new build for the specified job and returns the created {@link AnalysisResult} after the build has * been finished. * * @param job * the job to schedule * @param status * the expected result for the build * * @return the created {@link ResultAction} */ @SuppressWarnings({"illegalcatch", "OverlyBroadCatchBlock"}) private AnalysisResult scheduleBuildAndAssertStatus(final FreeStyleProject job, final Result status) { try { FreeStyleBuild build = j.assertBuildStatus(status, job.scheduleBuild2(0)); ResultAction action = build.getAction(ResultAction.class); assertThat(action).isNotNull(); return action.getResult(); } catch (Exception e) { throw new AssertionError(e); } } /** * Schedules a new build for the specified job and returns the created {@link List<AnalysisResult>} after the build * has been finished as one result of both tools. * * @param job * the job to schedule * @param status * the expected result of both tools for the build * * @return the created {@link List<ResultAction>} */ @SuppressWarnings({"illegalcatch", "OverlyBroadCatchBlock"}) private List<AnalysisResult> scheduleBuildAndAssertStatusForBothTools(final FreeStyleProject job, final Result status) { try { FreeStyleBuild build = j.assertBuildStatus(status, job.scheduleBuild2(0)); List<ResultAction> actions = build.getActions(ResultAction.class); List<AnalysisResult> results = new ArrayList<>(); for (ResultAction elements : actions) { results.add(elements.getResult()); } return results; } catch (Exception e) { throw new AssertionError(e); } } /** * Runs the CheckStyle and PMD tools on an output file that contains several issues: the build should report 6 and 4 * issues. */ @Test @WithTimeout(1000) public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateFalse() { FreeStyleProject project = createJobWithWorkspaceFile("checkstyle.xml", "pmd-warnings.xml"); enableWarningsAggregation(project, false, "**/checkstyle-issues.txt", new CheckStyle(), "**/pmd-warnings-issues.txt", new Pmd()); List<AnalysisResult> results = scheduleBuildAndAssertStatusForBothTools(project, Result.SUCCESS); for (AnalysisResult element : results) { if (element.getId().equals("checkstyle")) { assertThat(element.getTotalSize()).isEqualTo(6); } else { assertThat(element.getId()).isEqualTo("pmd"); assertThat(element.getTotalSize()).isEqualTo(4); } assertThat(element).hasOverallResult(Result.SUCCESS); } } /** * Runs the CheckStyle and PMD tools on an output file that contains one issue: the build should report 10 issues. */ @Test @WithTimeout(1000) public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateTrue() { FreeStyleProject project = createJobWithWorkspaceFile("checkstyle.xml", "pmd-warnings.xml"); enableWarningsAggregation(project, true, "**/checkstyle-issues.txt", new CheckStyle(), "**/pmd-warnings-issues.txt", new Pmd()); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS); assertThat(result).hasTotalSize(10); assertThat(result.getSizePerOrigin()).containsKeys("checkstyle", "pmd"); assertThat(result.getSizePerOrigin().get("checkstyle").equals(6)); assertThat(result.getSizePerOrigin().get("pmd").equals(4)); assertThat(result).hasOverallResult(Result.SUCCESS); } /** * Runs only the CheckStyle tool multiple times on an output file that contains not several issues and produce a * failure. */ @Test @WithTimeout(1000) public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateFalseAndSameTool() { FreeStyleProject project = createJobWithWorkspaceFile("checkstyle2.xml", "checkstyle3.xml"); enableWarningsAggregation(project, false, "**/checkstyle2-issues.txt", new CheckStyle(), "**/checkstyle3-issues.txt", new CheckStyle()); List<AnalysisResult> results = scheduleBuildAndAssertStatusForBothTools(project, Result.FAILURE); for (AnalysisResult elements : results) { assertThat(elements).hasErrorMessages(); } } /** * Runs only the CheckStyle tool multiple times on an output file that contains one issues: the build should report * 6 issues. */ @Test @WithTimeout(1000) public void shouldCreateMultipleToolsAndAggregationResultWithWarningsAggregateTrueAndSameTool() { FreeStyleProject project = createJobWithWorkspaceFile("checkstyle2.xml", "checkstyle3.xml"); enableWarningsAggregation(project, true, "**/checkstyle2-issues.txt", new CheckStyle(), "**/checkstyle3-issues.txt", new CheckStyle()); AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS); assertThat(result).hasTotalSize(6); assertThat(result.getSizePerOrigin()).containsKeys("checkstyle"); assertThat(result.getSizePerOrigin().get("checkstyle").equals(6)); assertThat(result).hasOverallResult(Result.SUCCESS); } }
Improvement of the tests and eliminate of the warnings
src/test/java/io/jenkins/plugins/analysis/warnings/IssuesRecorderITest.java
Improvement of the tests and eliminate of the warnings
<ide><path>rc/test/java/io/jenkins/plugins/analysis/warnings/IssuesRecorderITest.java <ide> * the second new filename in the workspace <ide> * @param tool2 <ide> * class of the second tool <del> * <del> * @return the created recorder <ide> */ <ide> @CanIgnoreReturnValue <del> private IssuesRecorder enableWarningsAggregation(final FreeStyleProject job, final boolean checkbox, <add> private void enableWarningsAggregation(final FreeStyleProject job, final boolean checkbox, <ide> final String toolPattern1, final StaticAnalysisTool tool1, final String toolPattern2, <ide> final StaticAnalysisTool tool2) { <ide> IssuesRecorder publisher = new IssuesRecorder(); <ide> publisher.setTools(toolList); <ide> <ide> job.getPublishersList().add(publisher); <del> return publisher; <ide> } <ide> <ide> /** <ide> FreeStyleProject project = createJobWithWorkspaceFile("checkstyle.xml", "pmd-warnings.xml"); <ide> enableWarningsAggregation(project, true, "**/checkstyle-issues.txt", new CheckStyle(), <ide> "**/pmd-warnings-issues.txt", new Pmd()); <add> <ide> AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS); <ide> <ide> assertThat(result).hasTotalSize(10); <ide> assertThat(result.getSizePerOrigin()).containsKeys("checkstyle", "pmd"); <del> assertThat(result.getSizePerOrigin().get("checkstyle").equals(6)); <del> assertThat(result.getSizePerOrigin().get("pmd").equals(4)); <ide> assertThat(result).hasOverallResult(Result.SUCCESS); <ide> } <ide> <ide> FreeStyleProject project = createJobWithWorkspaceFile("checkstyle2.xml", "checkstyle3.xml"); <ide> enableWarningsAggregation(project, false, "**/checkstyle2-issues.txt", new CheckStyle(), <ide> "**/checkstyle3-issues.txt", new CheckStyle()); <add> <ide> List<AnalysisResult> results = scheduleBuildAndAssertStatusForBothTools(project, Result.FAILURE); <ide> <ide> for (AnalysisResult elements : results) { <ide> <ide> assertThat(result).hasTotalSize(6); <ide> assertThat(result.getSizePerOrigin()).containsKeys("checkstyle"); <del> assertThat(result.getSizePerOrigin().get("checkstyle").equals(6)); <ide> assertThat(result).hasOverallResult(Result.SUCCESS); <ide> } <ide> }
Java
apache-2.0
be4f77ae335e0bba90abd8020777203926b434fd
0
ndeloof/docker-java,tejksat/docker-java,docker-java/docker-java,sabre1041/docker-java,292388900/docker-java,DICE-UNC/docker-java,tschoots/docker-java,MarcoLotz/docker-java,camunda-ci/docker-java,rockzeng/docker-java,hermeswaldemarin/docker-java,netvl/docker-java,gesellix/docker-java,nfsantos/docker-java,metavige/docker-java,SpazioDati/docker-java,carlossg/docker-java,DICE-UNC/docker-java,292388900/docker-java,jamesmarva/docker-java,carlossg/docker-java,gesellix/docker-java,marcust/docker-java,alesj/docker-java,metavige/docker-java,marto/docker-java,chenchun/docker-java,sabre1041/docker-java,klesgidis/docker-java,llamahunter/docker-java,rancher/docker-java,klesgidis/docker-java,KostyaSha/docker-java,llamahunter/docker-java,ollie314/docker-java,dflemstr/docker-java,KostyaSha/docker-java,tschoots/docker-java,netvl/docker-java,ollie314/docker-java,tejksat/docker-java,magnayn/docker-java,IrfanAnsari/docker-java,marto/docker-java,arthurtsang/docker-java,vjuranek/docker-java,alesj/docker-java,signalfx/docker-java,docker-java/docker-java,chenchun/docker-java,rohitkadam19/docker-java,dianping/docker-java,MarcoLotz/docker-java,rohitkadam19/docker-java,signalfx/docker-java,dflemstr/docker-java,vjuranek/docker-java,camunda-ci/docker-java,tourea/docker-java,marcust/docker-java,rancher/docker-java,jamesmarva/docker-java,hermeswaldemarin/docker-java,magnayn/docker-java,nfsantos/docker-java,IrfanAnsari/docker-java,arthurtsang/docker-java,ndeloof/docker-java,dianping/docker-java,rockzeng/docker-java,tourea/docker-java,SpazioDati/docker-java
package com.github.dockerjava.client.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import java.lang.reflect.Method; import java.util.Arrays; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.ContainerCreateResponse; import com.github.dockerjava.client.model.ContainerInspectResponse; import com.github.dockerjava.client.model.Volume; public class CreateContainerCmdTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); } @AfterTest public void afterTest() { super.afterTest(); } @BeforeMethod public void beforeMethod(Method method) { super.beforeMethod(method); } @AfterMethod public void afterMethod(ITestResult result) { super.afterMethod(result); } @Test public void createContainerWithVolume() throws DockerException { ContainerCreateResponse container = dockerClient .createContainerCmd("busybox").withVolumes(new Volume("/var/log")).withCmd("true").exec(); tmpContainers.add(container.getId()); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); LOG.info("Inspect container {}", containerInspectResponse.getConfig().getVolumes()); assertThat(containerInspectResponse.getConfig().getVolumes().keySet(), contains("/var/log")); } @Test public void createContainerWithEnv() throws DockerException { ContainerCreateResponse container = dockerClient .createContainerCmd("busybox").withEnv("VARIABLE=success").withCmd("env").exec(); tmpContainers.add(container.getId()); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); assertThat(Arrays.asList(containerInspectResponse.getConfig().getEnv()), contains("VARIABLE=success","HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")); dockerClient.startContainerCmd(container.getId()).exec(); assertThat(logResponseStream(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("VARIABLE=success")); } @Test public void createContainerWithHostname() throws DockerException { ContainerCreateResponse container = dockerClient .createContainerCmd("busybox").withHostName("docker-java").withCmd("env").exec(); tmpContainers.add(container.getId()); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); assertThat(containerInspectResponse.getConfig().getHostName(), equalTo("docker-java")); dockerClient.startContainerCmd(container.getId()).exec(); assertThat(logResponseStream(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("HOSTNAME=docker-java")); } }
src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java
package com.github.dockerjava.client.command; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; import java.lang.reflect.Method; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.dockerjava.client.AbstractDockerClientTest; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.ContainerCreateResponse; import com.github.dockerjava.client.model.ContainerInspectResponse; import com.github.dockerjava.client.model.Volume; public class CreateContainerCmdTest extends AbstractDockerClientTest { @BeforeTest public void beforeTest() throws DockerException { super.beforeTest(); } @AfterTest public void afterTest() { super.afterTest(); } @BeforeMethod public void beforeMethod(Method method) { super.beforeMethod(method); } @AfterMethod public void afterMethod(ITestResult result) { super.afterMethod(result); } @Test public void createContainer() throws DockerException { ContainerCreateResponse container = dockerClient .createContainerCmd("busybox").withVolumes(new Volume("/var/log")).withCmd("true").exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(isEmptyString())); ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); LOG.info("Inspect container {}", containerInspectResponse.getConfig().getVolumes()); assertThat(containerInspectResponse.getConfig().getVolumes().keySet(), contains("/var/log")); tmpContainers.add(container.getId()); } }
Added tests for ENV and HOSTNAME
src/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java
Added tests for ENV and HOSTNAME
<ide><path>rc/test/java/com/github/dockerjava/client/command/CreateContainerCmdTest.java <ide> package com.github.dockerjava.client.command; <ide> <ide> import static org.hamcrest.MatcherAssert.assertThat; <del>import static org.hamcrest.Matchers.contains; <del>import static org.hamcrest.Matchers.isEmptyString; <del>import static org.hamcrest.Matchers.not; <add>import static org.hamcrest.Matchers.*; <add> <ide> <ide> import java.lang.reflect.Method; <add>import java.util.Arrays; <ide> <ide> import org.testng.ITestResult; <ide> import org.testng.annotations.AfterMethod; <ide> } <ide> <ide> @Test <del> public void createContainer() throws DockerException { <add> public void createContainerWithVolume() throws DockerException { <ide> <ide> ContainerCreateResponse container = dockerClient <ide> .createContainerCmd("busybox").withVolumes(new Volume("/var/log")).withCmd("true").exec(); <ide> <add> tmpContainers.add(container.getId()); <add> <ide> LOG.info("Created container {}", container.toString()); <ide> <ide> assertThat(container.getId(), not(isEmptyString())); <ide> <ide> assertThat(containerInspectResponse.getConfig().getVolumes().keySet(), contains("/var/log")); <ide> <del> tmpContainers.add(container.getId()); <add> <ide> } <ide> <add> @Test <add> public void createContainerWithEnv() throws DockerException { <add> <add> ContainerCreateResponse container = dockerClient <add> .createContainerCmd("busybox").withEnv("VARIABLE=success").withCmd("env").exec(); <add> <add> tmpContainers.add(container.getId()); <add> <add> LOG.info("Created container {}", container.toString()); <add> <add> assertThat(container.getId(), not(isEmptyString())); <add> <add> ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); <add> <add> assertThat(Arrays.asList(containerInspectResponse.getConfig().getEnv()), contains("VARIABLE=success","HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")); <add> <add> dockerClient.startContainerCmd(container.getId()).exec(); <add> <add> assertThat(logResponseStream(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("VARIABLE=success")); <add> } <add> <add> @Test <add> public void createContainerWithHostname() throws DockerException { <add> <add> ContainerCreateResponse container = dockerClient <add> .createContainerCmd("busybox").withHostName("docker-java").withCmd("env").exec(); <add> <add> tmpContainers.add(container.getId()); <add> <add> LOG.info("Created container {}", container.toString()); <add> <add> assertThat(container.getId(), not(isEmptyString())); <add> <add> ContainerInspectResponse containerInspectResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); <add> <add> assertThat(containerInspectResponse.getConfig().getHostName(), equalTo("docker-java")); <add> <add> dockerClient.startContainerCmd(container.getId()).exec(); <add> <add> assertThat(logResponseStream(dockerClient.logContainerCmd(container.getId()).withStdOut().exec()), containsString("HOSTNAME=docker-java")); <add> } <ide> <ide> <ide> }
JavaScript
mit
c9175eba7c6c999e1cbfd36451d3f20cbd5dd8ff
0
brycesub/silvia-pi,brycesub/silvia-pi,brycesub/silvia-pi,brycesub/silvia-pi
var curtemp = new TimeSeries(); var settemp = new TimeSeries(); var settempm = new TimeSeries(); var settempp = new TimeSeries(); var pterm = new TimeSeries(); var iterm = new TimeSeries(); var dterm = new TimeSeries(); var pidval = new TimeSeries(); var avgpid = new TimeSeries(); var lastreqdone = 1; $(document).ready(function(){ $(".adv").hide(); createTimeline(); $("#toggleadv").click(function(){ $(".adv").toggle(); }); }); setInterval(function() { if (lastreqdone == 1) { $.getJSON({ url: "/allstats", success: function ( resp ) { curtemp.append(new Date().getTime(), resp.tempf); settemp.append(new Date().getTime(), resp.settemp); settempm.append(new Date().getTime(), resp.settemp-4); settempp.append(new Date().getTime(), resp.settemp+4); pterm.append(new Date().getTime(), resp.pterm); iterm.append(new Date().getTime(), resp.iterm); dterm.append(new Date().getTime(), resp.dterm); pidval.append(new Date().getTime(), resp.pidval); avgpid.append(new Date().getTime(), resp.avgpid); $("#curtemp").html(resp.tempf.toFixed(2)); $("#settemp").html(resp.settemp.toFixed(2)); $("#pterm").html(resp.pterm.toFixed(2)); $("#iterm").html(resp.iterm.toFixed(2)); $("#dterm").html(resp.dterm.toFixed(2)); $("#pidval").html(resp.pidval.toFixed(2)); $("#avgpid").html(resp.avgpid.toFixed(2)); lastreqdone = 1; } }); lastreqdone = 0; } }, 100); function createTimeline() { var chart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05}), canvas = document.getElementById('chart'), series = new TimeSeries(); chart.addTimeSeries(settemp, {lineWidth:1,strokeStyle:'#ffff00'}); chart.addTimeSeries(settempm, {lineWidth:1,strokeStyle:'#ffffff'}); chart.addTimeSeries(settempp, {lineWidth:1,strokeStyle:'#ffffff'}); chart.addTimeSeries(curtemp, {lineWidth:3,strokeStyle:'#ff0000'}); chart.streamTo(document.getElementById("chart"), 500); var pidchart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05}), canvas = document.getElementById('pidchart'), series = new TimeSeries(); pidchart.addTimeSeries(pterm, {lineWidth:2,strokeStyle:'#ff0000'}); pidchart.addTimeSeries(iterm, {lineWidth:2,strokeStyle:'#00ff00'}); pidchart.addTimeSeries(dterm, {lineWidth:2,strokeStyle:'#0000ff'}); pidchart.addTimeSeries(pidval, {lineWidth:2,strokeStyle:'#ffff00'}); pidchart.addTimeSeries(avgpid, {lineWidth:2,strokeStyle:'#00ffff'}); pidchart.streamTo(document.getElementById("pidchart"), 500); }
www/index.js
var curtemp = new TimeSeries(); var settemp = new TimeSeries(); var settempm = new TimeSeries(); var settempp = new TimeSeries(); var pterm = new TimeSeries(); var iterm = new TimeSeries(); var dterm = new TimeSeries(); var pidval = new TimeSeries(); var avgpid = new TimeSeries(); $(document).ready(function(){ $(".adv").hide(); createTimeline(); $("#toggleadv").click(function(){ $(".adv").toggle(); }); }); setInterval(function() { $.getJSON({ url: "/allstats", success: function ( resp ) { curtemp.append(new Date().getTime(), resp.tempf); settemp.append(new Date().getTime(), resp.settemp); settempm.append(new Date().getTime(), resp.settemp-4); settempp.append(new Date().getTime(), resp.settemp+4); pterm.append(new Date().getTime(), resp.pterm); iterm.append(new Date().getTime(), resp.iterm); dterm.append(new Date().getTime(), resp.dterm); pidval.append(new Date().getTime(), resp.pidval); avgpid.append(new Date().getTime(), resp.avgpid); $("#curtemp").html(resp.tempf.toFixed(2)); $("#settemp").html(resp.settemp.toFixed(2)); $("#pterm").html(resp.pterm.toFixed(2)); $("#iterm").html(resp.iterm.toFixed(2)); $("#dterm").html(resp.dterm.toFixed(2)); $("#pidval").html(resp.pidval.toFixed(2)); $("#avgpid").html(resp.avgpid.toFixed(2)); } }); }, 250); function createTimeline() { var chart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05}), canvas = document.getElementById('chart'), series = new TimeSeries(); chart.addTimeSeries(settemp, {lineWidth:1,strokeStyle:'#ffff00'}); chart.addTimeSeries(settempm, {lineWidth:1,strokeStyle:'#ffffff'}); chart.addTimeSeries(settempp, {lineWidth:1,strokeStyle:'#ffffff'}); chart.addTimeSeries(curtemp, {lineWidth:3,strokeStyle:'#ff0000'}); chart.streamTo(document.getElementById("chart"), 500); var pidchart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05}), canvas = document.getElementById('pidchart'), series = new TimeSeries(); pidchart.addTimeSeries(pterm, {lineWidth:2,strokeStyle:'#ff0000'}); pidchart.addTimeSeries(iterm, {lineWidth:2,strokeStyle:'#00ff00'}); pidchart.addTimeSeries(dterm, {lineWidth:2,strokeStyle:'#0000ff'}); pidchart.addTimeSeries(pidval, {lineWidth:2,strokeStyle:'#ffff00'}); pidchart.addTimeSeries(avgpid, {lineWidth:2,strokeStyle:'#00ffff'}); pidchart.streamTo(document.getElementById("pidchart"), 500); }
new ajax request wont go out until last one returns
www/index.js
new ajax request wont go out until last one returns
<ide><path>ww/index.js <ide> var dterm = new TimeSeries(); <ide> var pidval = new TimeSeries(); <ide> var avgpid = new TimeSeries(); <add>var lastreqdone = 1; <ide> <ide> $(document).ready(function(){ <ide> $(".adv").hide(); <ide> }); <ide> <ide> setInterval(function() { <del> $.getJSON({ <del> url: "/allstats", <del> success: function ( resp ) { <del> curtemp.append(new Date().getTime(), resp.tempf); <del> settemp.append(new Date().getTime(), resp.settemp); <del> settempm.append(new Date().getTime(), resp.settemp-4); <del> settempp.append(new Date().getTime(), resp.settemp+4); <del> pterm.append(new Date().getTime(), resp.pterm); <del> iterm.append(new Date().getTime(), resp.iterm); <del> dterm.append(new Date().getTime(), resp.dterm); <del> pidval.append(new Date().getTime(), resp.pidval); <del> avgpid.append(new Date().getTime(), resp.avgpid); <del> $("#curtemp").html(resp.tempf.toFixed(2)); <del> $("#settemp").html(resp.settemp.toFixed(2)); <del> $("#pterm").html(resp.pterm.toFixed(2)); <del> $("#iterm").html(resp.iterm.toFixed(2)); <del> $("#dterm").html(resp.dterm.toFixed(2)); <del> $("#pidval").html(resp.pidval.toFixed(2)); <del> $("#avgpid").html(resp.avgpid.toFixed(2)); <del> } <del> }); <del>}, 250); <add> if (lastreqdone == 1) { <add> $.getJSON({ <add> url: "/allstats", <add> success: function ( resp ) { <add> curtemp.append(new Date().getTime(), resp.tempf); <add> settemp.append(new Date().getTime(), resp.settemp); <add> settempm.append(new Date().getTime(), resp.settemp-4); <add> settempp.append(new Date().getTime(), resp.settemp+4); <add> pterm.append(new Date().getTime(), resp.pterm); <add> iterm.append(new Date().getTime(), resp.iterm); <add> dterm.append(new Date().getTime(), resp.dterm); <add> pidval.append(new Date().getTime(), resp.pidval); <add> avgpid.append(new Date().getTime(), resp.avgpid); <add> $("#curtemp").html(resp.tempf.toFixed(2)); <add> $("#settemp").html(resp.settemp.toFixed(2)); <add> $("#pterm").html(resp.pterm.toFixed(2)); <add> $("#iterm").html(resp.iterm.toFixed(2)); <add> $("#dterm").html(resp.dterm.toFixed(2)); <add> $("#pidval").html(resp.pidval.toFixed(2)); <add> $("#avgpid").html(resp.avgpid.toFixed(2)); <add> lastreqdone = 1; <add> } <add> }); <add> lastreqdone = 0; <add> } <add>}, 100); <ide> <ide> function createTimeline() { <ide> var chart = new SmoothieChart({grid:{verticalSections:3},minValueScale:1.05,maxValueScale:1.05}),
Java
bsd-3-clause
8e847cdb1bf551d99443a458c8a0b633af45dd60
0
ztx1491/jcabi-aspects,dmzaytsev/jcabi-aspects,krzyk/jcabi-aspects,childRon/jcabi-aspects,shelan/jcabi-aspects,pecko/jcabi-aspects,xialiushao/jcabi-aspects,54uso/jcabi-aspects,YamStranger/jcabi-aspects
/** * Copyright (c) 2012-2014, jcabi.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the jcabi.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jcabi.aspects.aj; import com.jcabi.aspects.Immutable; import com.jcabi.log.Logger; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; /** * Checks for class immutability. * * <p>The class is thread-safe. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @since 0.7.8 */ @Aspect public final class ImmutabilityChecker { /** * Already checked immutable classes. */ private final transient Set<Class<?>> immutable = new HashSet<Class<?>>(); /** * Catch instantiation and validate class. * * <p>Try NOT to change the signature of this method, in order to keep * it backward compatible. * * @param point Joint point */ @After("initialization((@com.jcabi.aspects.Immutable *).new(..))") public void after(final JoinPoint point) { final Object object = point.getTarget(); final Class<?> type = object.getClass(); try { this.check(object, type); } catch (final ImmutabilityChecker.Violation ex) { throw new IllegalStateException( String.format( // @checkstyle LineLength (1 line) "%s is not immutable, can't use it (jcabi-aspects ${project.version}/${buildNumber})", type ), ex ); } } /** * This class is immutable? * @param obj The object to check * @param type The class to check * @throws ImmutabilityChecker.Violation If it is mutable */ private void check(final Object obj, final Class<?> type) throws ImmutabilityChecker.Violation { synchronized (this.immutable) { if (!this.ignore(type)) { if (type.isInterface() && !type.isAnnotationPresent(Immutable.class)) { throw new ImmutabilityChecker.Violation( String.format( "Interface '%s' is not annotated with @Immutable", type.getName() ) ); } if (!type.isInterface() && !Modifier.isFinal(type.getModifiers())) { throw new Violation( String.format( "Class '%s' is not final", type.getName() ) ); } try { this.fields(obj, type); } catch (final ImmutabilityChecker.Violation ex) { throw new ImmutabilityChecker.Violation( String.format("Class '%s' is mutable", type.getName()), ex ); } this.immutable.add(type); Logger.debug(this, "#check(%s): immutability checked", type); } } } /** * This array field immutable? * @param obj The object which has the array * @param field The field to check * @throws Violation If it is mutable. */ private void checkArray(final Object obj, final Field field) throws Violation { field.setAccessible(true); if (field.isAnnotationPresent(Immutable.Array.class)) { try { this.check(field.get(obj), field.getType().getComponentType()); } catch (final ImmutabilityChecker.Violation ex) { throw new ImmutabilityChecker.Violation( String.format( "Field array component type '%s' is mutable", field.getType().getComponentType().getName() ), ex ); } catch (final IllegalAccessException ex) { this.throwViolationFieldNotAccessible(field); } } else { // @checkstyle LineLength (3 lines) throw new ImmutabilityChecker.Violation( String.format( "Field '%s' is an array and is not annotated with @Immutable.Array", field.getName() ) ); } } /** * This class should be ignored and never checked any more? * @param type The type to check * @return TRUE if this class shouldn't be checked */ private boolean ignore(final Class<?> type) { // @checkstyle BooleanExpressionComplexity (5 lines) return type.getName().startsWith("java.lang.") || type.isPrimitive() || type.getName().startsWith("org.aspectj.runtime.reflect.") || this.immutable.contains(type); } /** * All its fields are safe? * @param obj The object to check * @param type Type to check * @throws ImmutabilityChecker.Violation If it is mutable */ private void fields(final Object obj, final Class<?> type) throws ImmutabilityChecker.Violation { final Field[] fields = type.getDeclaredFields(); for (int pos = 0; pos < fields.length; ++pos) { final Field field = fields[pos]; if (Modifier.isStatic(field.getModifiers())) { continue; } if (!Modifier.isFinal(field.getModifiers())) { throw new ImmutabilityChecker.Violation( String.format( "field '%s' is not final", field ) ); } try { this.checkDeclaredAndActualTypes(obj, field, type); if (field.getType().isArray()) { this.checkArray(obj, field); } } catch (final ImmutabilityChecker.Violation ex) { throw new ImmutabilityChecker.Violation( String.format( "field '%s' is mutable", field ), ex ); } } } /** * Checks if both declared and actual types of the field within the object * are immutable. * * @param obj The given object * @param field The given field * @param type The type to be skipped * @throws ImmutabilityChecker.Violation If they are mutable */ private void checkDeclaredAndActualTypes(final Object obj, final Field field, final Class<?> type) throws ImmutabilityChecker.Violation { field.setAccessible(true); if (field.getType() != type) { this.check(obj, field.getType()); } Object fieldValue = null; try { fieldValue = field.get(obj); } catch (IllegalAccessException e) { this.throwViolationFieldNotAccessible(field); } if (fieldValue != null && !field.getType().equals(fieldValue.getClass())) { this.check(obj, fieldValue.getClass()); } } /** * Throws an {@link Violation} exception with text about unaccessibility of * the field. * * @param field The field * @throws ImmutabilityChecker.Violation Always */ private void throwViolationFieldNotAccessible(final Field field) throws ImmutabilityChecker.Violation { throw new ImmutabilityChecker.Violation( String.format( "Field '%s' is not accessible", field ) ); } /** * Immutability violation. */ private static final class Violation extends Exception { /** * Serialization marker. */ private static final long serialVersionUID = 1L; /** * Public ctor. * @param msg Message */ public Violation(final String msg) { super(msg); } /** * Public ctor. * @param msg Message * @param cause Cause of it */ public Violation(final String msg, final ImmutabilityChecker.Violation cause) { super(msg, cause); } } }
src/main/java/com/jcabi/aspects/aj/ImmutabilityChecker.java
/** * Copyright (c) 2012-2014, jcabi.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the jcabi.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jcabi.aspects.aj; import com.jcabi.aspects.Immutable; import com.jcabi.log.Logger; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; /** * Checks for class immutability. * * <p>The class is thread-safe. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ * @since 0.7.8 */ @Aspect public final class ImmutabilityChecker { /** * Already checked immutable classes. */ private final transient Set<Class<?>> immutable = new HashSet<Class<?>>(); /** * Catch instantiation and validate class. * * <p>Try NOT to change the signature of this method, in order to keep * it backward compatible. * * @param point Joint point */ @After("initialization((@com.jcabi.aspects.Immutable *).new(..))") public void after(final JoinPoint point) { final Object object = point.getTarget(); final Class<?> type = object.getClass(); try { this.check(object, type); } catch (final ImmutabilityChecker.Violation ex) { throw new IllegalStateException( String.format( // @checkstyle LineLength (1 line) "%s is not immutable, can't use it (jcabi-aspects ${project.version}/${buildNumber})", type ), ex ); } } /** * This class is immutable? * @param obj The object to check * @param type The class to check * @throws ImmutabilityChecker.Violation If it is mutable */ private void check(final Object obj, final Class<?> type) throws ImmutabilityChecker.Violation { synchronized (this.immutable) { if (!this.ignore(type)) { if (type.isInterface() && !type.isAnnotationPresent(Immutable.class)) { throw new ImmutabilityChecker.Violation( String.format( "Interface '%s' is not annotated with @Immutable", type.getName() ) ); } if (!type.isInterface() && !Modifier.isFinal(type.getModifiers())) { throw new Violation( String.format( "Class '%s' is not final", type.getName() ) ); } try { this.fields(obj, type); } catch (final ImmutabilityChecker.Violation ex) { throw new ImmutabilityChecker.Violation( String.format("Class '%s' is mutable", type.getName()), ex ); } this.immutable.add(type); Logger.debug(this, "#check(%s): immutability checked", type); } } } /** * This array field immutable? * @param obj The object which has the array * @param field The field to check * @throws Violation If it is mutable. */ private void checkArray(final Object obj, final Field field) throws Violation { field.setAccessible(true); if (field.isAnnotationPresent(Immutable.Array.class)) { try { this.check(field.get(obj), field.getType().getComponentType()); } catch (final ImmutabilityChecker.Violation ex) { throw new ImmutabilityChecker.Violation( String.format( "Field array component type '%s' is mutable", field.getType().getComponentType().getName() ), ex ); } catch (final IllegalAccessException ex) { this.throwViolationFieldNotAccessible(field); } } else { // @checkstyle LineLength (3 lines) throw new ImmutabilityChecker.Violation( String.format( "Field '%s' is an array and is not annotated with @Immutable.Array", field.getName() ) ); } } /** * This class should be ignored and never checked any more? * @param type The type to check * @return TRUE if this class shouldn't be checked */ private boolean ignore(final Class<?> type) { // @checkstyle BooleanExpressionComplexity (5 lines) return type.getName().startsWith("java.lang.") || type.isPrimitive() || type.getName().startsWith("org.aspectj.runtime.reflect.") || this.immutable.contains(type); } /** * All its fields are safe? * @param obj The object to check * @param type Type to check * @throws ImmutabilityChecker.Violation If it is mutable */ private void fields(final Object obj, final Class<?> type) throws ImmutabilityChecker.Violation { final Field[] fields = type.getDeclaredFields(); for (int pos = 0; pos < fields.length; ++pos) { final Field field = fields[pos]; if (Modifier.isStatic(field.getModifiers())) { continue; } if (!Modifier.isFinal(field.getModifiers())) { throw new ImmutabilityChecker.Violation( String.format( "field '%s' is not final", field ) ); } try { field.setAccessible(true); if (field.getType() != type) { this.check(obj, field.getType()); final Object fieldValue = field.get(obj); if (fieldValue != null && !field.getType().equals(fieldValue.getClass())) { this.check(obj, fieldValue.getClass()); } } if (field.getType().isArray()) { this.checkArray(obj, field); } } catch (final ImmutabilityChecker.Violation ex) { throw new ImmutabilityChecker.Violation( String.format( "field '%s' is mutable", field ), ex ); } catch (final IllegalAccessException ex) { this.throwViolationFieldNotAccessible(field); } } } /** * Throws an {@link Violation} exception with text about unaccessibility of * the field. * * @param field The field * @throws ImmutabilityChecker.Violation Always */ private void throwViolationFieldNotAccessible(final Field field) throws ImmutabilityChecker.Violation { throw new ImmutabilityChecker.Violation( String.format( "Field '%s' is not accessible", field ) ); } /** * Immutability violation. */ private static final class Violation extends Exception { /** * Serialization marker. */ private static final long serialVersionUID = 1L; /** * Public ctor. * @param msg Message */ public Violation(final String msg) { super(msg); } /** * Public ctor. * @param msg Message * @param cause Cause of it */ public Violation(final String msg, final ImmutabilityChecker.Violation cause) { super(msg, cause); } } }
#118 fixed CyclomaticComplexity
src/main/java/com/jcabi/aspects/aj/ImmutabilityChecker.java
#118 fixed CyclomaticComplexity
<ide><path>rc/main/java/com/jcabi/aspects/aj/ImmutabilityChecker.java <ide> ); <ide> } <ide> try { <del> field.setAccessible(true); <del> if (field.getType() != type) { <del> this.check(obj, field.getType()); <del> final Object fieldValue = field.get(obj); <del> if (fieldValue != null <del> && !field.getType().equals(fieldValue.getClass())) { <del> this.check(obj, fieldValue.getClass()); <del> } <del> } <add> this.checkDeclaredAndActualTypes(obj, field, type); <ide> if (field.getType().isArray()) { <ide> this.checkArray(obj, field); <ide> } <ide> ), <ide> ex <ide> ); <del> } catch (final IllegalAccessException ex) { <del> this.throwViolationFieldNotAccessible(field); <del> } <add> } <add> } <add> } <add> <add> /** <add> * Checks if both declared and actual types of the field within the object <add> * are immutable. <add> * <add> * @param obj The given object <add> * @param field The given field <add> * @param type The type to be skipped <add> * @throws ImmutabilityChecker.Violation If they are mutable <add> */ <add> private void checkDeclaredAndActualTypes(final Object obj, <add> final Field field, final Class<?> type) <add> throws ImmutabilityChecker.Violation { <add> field.setAccessible(true); <add> if (field.getType() != type) { <add> this.check(obj, field.getType()); <add> } <add> Object fieldValue = null; <add> try { <add> fieldValue = field.get(obj); <add> } catch (IllegalAccessException e) { <add> this.throwViolationFieldNotAccessible(field); <add> } <add> if (fieldValue != null <add> && !field.getType().equals(fieldValue.getClass())) { <add> this.check(obj, fieldValue.getClass()); <ide> } <ide> } <ide>
Java
apache-2.0
c205015223e6c6aad98a58ec17692d339dff90a3
0
strapdata/elassandra-test,strapdata/elassandra-test,strapdata/elassandra-test,strapdata/elassandra-test,strapdata/elassandra-test,strapdata/elassandra-test,strapdata/elassandra-test
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.common; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.logging.Loggers; import java.util.HashSet; /** * Holds a field that can be found in a request while parsing and its different variants, which may be deprecated. */ public class ParseField { private static final DeprecationLogger DEPRECATION_LOGGER = new DeprecationLogger(Loggers.getLogger(ParseField.class)); private final String underscoreName; private final String[] deprecatedNames; private String allReplacedWith = null; public ParseField(String value, String... deprecatedNames) { underscoreName = Strings.toUnderscoreCase(value); final HashSet<String> set = new HashSet<>(); String camelCaseName = Strings.toCamelCase(value); if (camelCaseName.equals(value) == false) { set.add(camelCaseName); } for (String depName : deprecatedNames) { set.add(Strings.toCamelCase(depName)); set.add(Strings.toUnderscoreCase(depName)); } this.deprecatedNames = set.toArray(new String[set.size()]); } public String getPreferredName(){ return underscoreName; } public String[] getAllNamesIncludedDeprecated() { String[] allNames = new String[1 + deprecatedNames.length]; allNames[0] = underscoreName; for (int i = 0; i < deprecatedNames.length; i++) { allNames[i + 1] = deprecatedNames[i]; } return allNames; } public ParseField withDeprecation(String... deprecatedNames) { return new ParseField(this.underscoreName, deprecatedNames); } /** * Return a new ParseField where all field names are deprecated and replaced with {@code allReplacedWith}. */ public ParseField withAllDeprecated(String allReplacedWith) { ParseField parseField = this.withDeprecation(getAllNamesIncludedDeprecated()); parseField.allReplacedWith = allReplacedWith; return parseField; } boolean match(String currentFieldName, boolean strict) { if (allReplacedWith == null && currentFieldName.equals(underscoreName)) { return true; } String msg; for (String depName : deprecatedNames) { if (currentFieldName.equals(depName)) { msg = "Deprecated field [" + currentFieldName + "] used, expected [" + underscoreName + "] instead"; if (allReplacedWith != null) { msg = "Deprecated field [" + currentFieldName + "] used, replaced by [" + allReplacedWith + "]"; } if (strict) { throw new IllegalArgumentException(msg); } else { DEPRECATION_LOGGER.deprecated(msg); } return true; } } return false; } @Override public String toString() { return getPreferredName(); } }
core/src/main/java/org/elasticsearch/common/ParseField.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.common; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.logging.Loggers; import java.util.HashSet; /** * Holds a field that can be found in a request while parsing and its different variants, which may be deprecated. */ public class ParseField { private static final DeprecationLogger DEPRECATION_LOGGER = new DeprecationLogger(Loggers.getLogger(ParseField.class)); private final String underscoreName; private final String[] deprecatedNames; private String allReplacedWith = null; public ParseField(String value, String... deprecatedNames) { underscoreName = Strings.toUnderscoreCase(value); final HashSet<String> set = new HashSet<>(); set.add(Strings.toCamelCase(value)); for (String depName : deprecatedNames) { set.add(Strings.toCamelCase(depName)); set.add(Strings.toUnderscoreCase(depName)); } this.deprecatedNames = set.toArray(new String[set.size()]); } public String getPreferredName(){ return underscoreName; } public String[] getAllNamesIncludedDeprecated() { String[] allNames = new String[1 + deprecatedNames.length]; allNames[0] = underscoreName; for (int i = 0; i < deprecatedNames.length; i++) { allNames[i + 1] = deprecatedNames[i]; } return allNames; } public ParseField withDeprecation(String... deprecatedNames) { return new ParseField(this.underscoreName, deprecatedNames); } /** * Return a new ParseField where all field names are deprecated and replaced with {@code allReplacedWith}. */ public ParseField withAllDeprecated(String allReplacedWith) { ParseField parseField = this.withDeprecation(getAllNamesIncludedDeprecated()); parseField.allReplacedWith = allReplacedWith; return parseField; } boolean match(String currentFieldName, boolean strict) { if (allReplacedWith == null && currentFieldName.equals(underscoreName)) { return true; } String msg; for (String depName : deprecatedNames) { if (currentFieldName.equals(depName)) { msg = "Deprecated field [" + currentFieldName + "] used, expected [" + underscoreName + "] instead"; if (allReplacedWith != null) { msg = "Deprecated field [" + currentFieldName + "] used, replaced by [" + allReplacedWith + "]"; } if (strict) { throw new IllegalArgumentException(msg); } else { DEPRECATION_LOGGER.deprecated(msg); } return true; } } return false; } @Override public String toString() { return getPreferredName(); } }
Guard adding camelCase deprecated when the same as regulard name
core/src/main/java/org/elasticsearch/common/ParseField.java
Guard adding camelCase deprecated when the same as regulard name
<ide><path>ore/src/main/java/org/elasticsearch/common/ParseField.java <ide> public ParseField(String value, String... deprecatedNames) { <ide> underscoreName = Strings.toUnderscoreCase(value); <ide> final HashSet<String> set = new HashSet<>(); <del> set.add(Strings.toCamelCase(value)); <add> String camelCaseName = Strings.toCamelCase(value); <add> if (camelCaseName.equals(value) == false) { <add> set.add(camelCaseName); <add> } <ide> for (String depName : deprecatedNames) { <ide> set.add(Strings.toCamelCase(depName)); <ide> set.add(Strings.toUnderscoreCase(depName));
Java
agpl-3.0
50ad520f9ce6c04d2dc119636888cb0e2d5e003a
0
ProtocolSupport/ProtocolSupport,ridalarry/ProtocolSupport
package protocolsupport.protocol.v_1_5.serverboundtransformer; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import java.io.IOException; import net.minecraft.server.v1_8_R1.BlockPosition; import net.minecraft.server.v1_8_R1.ChatComponentText; import net.minecraft.server.v1_8_R1.ChatSerializer; import net.minecraft.server.v1_8_R1.EnumProtocol; import net.minecraft.server.v1_8_R1.EnumProtocolDirection; import net.minecraft.server.v1_8_R1.Packet; import org.bukkit.event.inventory.InventoryType; import protocolsupport.protocol.PacketDataSerializer; import protocolsupport.utils.Utils; public class PlayPacketTransformer implements PacketTransformer { @Override public Packet[] tranform(Channel channel, int packetId, PacketDataSerializer serializer) throws IOException { PacketDataSerializer packetdata = new PacketDataSerializer(Unpooled.buffer(), serializer.getVersion()); boolean useOriginalStream = false; Packet packet = null; switch (packetId) { case 0x00: { //PacketPlayInKeepAlive packet = getPacketById(0x00); packetdata.writeVarInt(serializer.readInt()); break; } case 0x03: { //PacketPlayInChat packet = getPacketById(0x01); useOriginalStream = true; break; } case 0x07: { //PacketPlayInUseEntity serializer.readInt(); int entityId = serializer.readInt(); boolean isLeftClick = serializer.readBoolean(); //if player interacts with the entity he is riding than he wants to unmont it if (!isLeftClick) { //reading is async so this is potentially dangerous org.bukkit.entity.Entity vehicle = Utils.getPlayer(channel).getVehicle(); if (vehicle != null && vehicle.getEntityId() == entityId) { packet = getPacketById(0x0C); packetdata.writeFloat(0); packetdata.writeFloat(0); packetdata.writeByte(1 << 1); } else { packet = getPacketById(0x02); packetdata.writeVarInt(entityId); packetdata.writeVarInt(isLeftClick ? 1 : 0); } } else { packet = getPacketById(0x02); packetdata.writeVarInt(entityId); packetdata.writeVarInt(isLeftClick ? 1 : 0); } break; } case 0x0A: { //PacketPlayInFlying packet = getPacketById(0x03); useOriginalStream = true; break; } case 0x0B: { //PacketPlayInPosition packet = getPacketById(0x04); packetdata.writeDouble(serializer.readDouble()); packetdata.writeDouble(serializer.readDouble()); serializer.readDouble(); packetdata.writeDouble(serializer.readDouble()); packetdata.writeBoolean(serializer.readBoolean()); break; } case 0x0C: { //PacketPlayInLook packet = getPacketById(0x05); useOriginalStream = true; break; } case 0x0D: { //PacketPlayInPositionLook double x = serializer.readDouble(); double yfeet = serializer.readDouble(); double y = serializer.readDouble(); double z = serializer.readDouble(); float yaw = serializer.readFloat(); float pitch = serializer.readFloat(); boolean onGroud = serializer.readBoolean(); //when y is -999.0D than it means that client actually tries to control vehicle movement if (yfeet == -999.0D && y == -999.0D) { Packet[] packets = new Packet[2]; Packet playerlook = getPacketById(0x05); packetdata.writeFloat(yaw); packetdata.writeFloat(pitch); packetdata.writeBoolean(onGroud); playerlook.a(packetdata); packets[0] = playerlook; packetdata.clear(); Packet steervehicle = getPacketById(0x0C); //TODO: convert motX and motZ to strafes packetdata.writeFloat(0.0F); packetdata.writeFloat(0.0F); packetdata.writeByte(0); steervehicle.a(packetdata); packets[1] = steervehicle; return packets; } else { packet = getPacketById(0x06); packetdata.writeDouble(x); packetdata.writeDouble(yfeet); packetdata.writeDouble(z); packetdata.writeFloat(yaw); packetdata.writeFloat(pitch); packetdata.writeBoolean(onGroud); } break; } case 0x0E: { //PacketPlayInBlockDig packet = getPacketById(0x07); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.a(new BlockPosition(serializer.readInt(), serializer.readUnsignedByte(), serializer.readInt())); packetdata.writeByte(serializer.readUnsignedByte()); break; } case 0x0F: { //PacketPlayInBlockPlace packet = getPacketById(0x08); packetdata.a(new BlockPosition(serializer.readInt(), serializer.readUnsignedByte(), serializer.readInt())); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.writeItemStack(serializer.readItemStack()); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.writeByte(serializer.readUnsignedByte()); break; } case 0x10: { //PacketPlayInHeldItemSlot packet = getPacketById(0x09); useOriginalStream = true; break; } case 0x12: { //PacketPlayInArmAnimation packet = getPacketById(0x0A); break; } case 0x13: { //PacketPlayInEntityAction packet = getPacketById(0x0B); packetdata.writeVarInt(serializer.readInt()); packetdata.writeVarInt(serializer.readByte()); packetdata.writeVarInt(0); break; } case 0x65: { //PacketPlayInCloseWindow packet = getPacketById(0x0D); useOriginalStream = true; break; } case 0x66: { //PacketPlayInWindowClick packet = getPacketById(0x0E); if (Utils.getPlayer(channel).getOpenInventory().getType() == InventoryType.ENCHANTING) { packetdata.writeByte(serializer.readByte()); int slot = serializer.readShort(); if (slot > 0) { slot++; } packetdata.writeShort(slot); packetdata.writeByte(serializer.readByte()); packetdata.writeShort(serializer.readShort()); packetdata.writeByte(serializer.readByte()); packetdata.writeItemStack(serializer.readItemStack()); } else { useOriginalStream = true; } break; } case 0x6A: { //PacketPlayInTransaction packet = getPacketById(0x0F); useOriginalStream = true; break; } case 0x6B: { //PacketPlayInSetCreativeSlot packet = getPacketById(0x10); useOriginalStream = true; break; } case 0x6C: { //PacketPlayInEnchantItem packet = getPacketById(0x11); useOriginalStream = true; break; } case 0x82: { //PacketPlayInUpdateSign packet = getPacketById(0x12); packetdata.a(new BlockPosition(serializer.readInt(), serializer.readShort(), serializer.readInt())); for (int i = 0; i < 4; i++) { packetdata.writeString(ChatSerializer.a(new ChatComponentText(serializer.readString(15)))); } break; } case 0xCA: { //PacketPlayInAbilities packet = getPacketById(0x13); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.writeFloat(serializer.readByte() / 255.0F); packetdata.writeFloat(serializer.readByte() / 255.0F); break; } case 0xCB: { //PacketPlayInTabComplete packet = getPacketById(0x14); packetdata.writeString(serializer.readString(32767)); packetdata.writeBoolean(false); break; } case 0xCC: { //PacketPlayInSettings packet = getPacketById(0x15); packetdata.writeString(serializer.readString(32767)); packetdata.writeByte(serializer.readByte()); int chatState = serializer.readByte(); packetdata.writeByte(chatState & 7); packetdata.writeBoolean((chatState & 8) == 8); serializer.readByte(); serializer.readBoolean(); packetdata.writeByte(0); break; } case 0xCD: { //PacketPlayInClientCommand packet = getPacketById(0x16); packetdata.writeVarInt(0); serializer.readByte(); break; } case 0xFA: { //PacketPlayInCustomPayload packet = getPacketById(0x17); String tag = serializer.readString(20); packetdata.writeString(tag); ByteBuf buf = serializer.readBytes(serializer.readShort()); //special handle for anvil renaming, in 1.8 it reads string from serializer, but in 1.7 and before it just reads bytes and converts it to string if (tag.equalsIgnoreCase("MC|ItemName")) { packetdata.writeVarInt(buf.readableBytes()); } packetdata.writeBytes(buf); break; } case 0xFF: { //No corresponding packet serializer.readString(32767); return new Packet[0]; } } if (packet != null) { packet.a(useOriginalStream ? serializer : packetdata); return new Packet[] {packet}; } return null; } private Packet getPacketById(int realPacketId) { return EnumProtocol.PLAY.a(EnumProtocolDirection.SERVERBOUND, realPacketId); } }
src/protocolsupport/protocol/v_1_5/serverboundtransformer/PlayPacketTransformer.java
package protocolsupport.protocol.v_1_5.serverboundtransformer; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import java.io.IOException; import net.minecraft.server.v1_8_R1.BlockPosition; import net.minecraft.server.v1_8_R1.ChatComponentText; import net.minecraft.server.v1_8_R1.ChatSerializer; import net.minecraft.server.v1_8_R1.EnumProtocol; import net.minecraft.server.v1_8_R1.EnumProtocolDirection; import net.minecraft.server.v1_8_R1.Packet; import org.bukkit.event.inventory.InventoryType; import protocolsupport.protocol.PacketDataSerializer; import protocolsupport.utils.Utils; public class PlayPacketTransformer implements PacketTransformer { @Override public Packet[] tranform(Channel channel, int packetId, PacketDataSerializer serializer) throws IOException { PacketDataSerializer packetdata = new PacketDataSerializer(Unpooled.buffer(), serializer.getVersion()); boolean useOriginalStream = false; Packet packet = null; switch (packetId) { case 0x00: { //PacketPlayInKeepAlive packet = getPacketById(0x00); packetdata.writeVarInt(serializer.readInt()); break; } case 0x03: { //PacketPlayInChat packet = getPacketById(0x01); useOriginalStream = true; break; } case 0x07: { //PacketPlayInUseEntity packet = getPacketById(0x02); serializer.readInt(); packetdata.writeVarInt(serializer.readInt()); packetdata.writeVarInt(serializer.readBoolean() ? 1 : 0); break; } case 0x0A: { //PacketPlayInFlying packet = getPacketById(0x03); useOriginalStream = true; break; } case 0x0B: { //PacketPlayInPosition packet = getPacketById(0x04); packetdata.writeDouble(serializer.readDouble()); packetdata.writeDouble(serializer.readDouble()); serializer.readDouble(); packetdata.writeDouble(serializer.readDouble()); packetdata.writeBoolean(serializer.readBoolean()); break; } case 0x0C: { //PacketPlayInLook packet = getPacketById(0x05); useOriginalStream = true; break; } case 0x0D: { //PacketPlayInPositionLook packet = getPacketById(0x06); packetdata.writeDouble(serializer.readDouble()); packetdata.writeDouble(serializer.readDouble()); serializer.readDouble(); packetdata.writeDouble(serializer.readDouble()); packetdata.writeFloat(serializer.readFloat()); packetdata.writeFloat(serializer.readFloat()); packetdata.writeBoolean(serializer.readBoolean()); break; } case 0x0E: { //PacketPlayInBlockDig packet = getPacketById(0x07); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.a(new BlockPosition(serializer.readInt(), serializer.readUnsignedByte(), serializer.readInt())); packetdata.writeByte(serializer.readUnsignedByte()); break; } case 0x0F: { //PacketPlayInBlockPlace packet = getPacketById(0x08); packetdata.a(new BlockPosition(serializer.readInt(), serializer.readUnsignedByte(), serializer.readInt())); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.writeItemStack(serializer.readItemStack()); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.writeByte(serializer.readUnsignedByte()); break; } case 0x10: { //PacketPlayInHeldItemSlot packet = getPacketById(0x09); useOriginalStream = true; break; } case 0x12: { //PacketPlayInArmAnimation packet = getPacketById(0x0A); break; } case 0x13: { //PacketPlayInEntityAction packet = getPacketById(0x0B); packetdata.writeVarInt(serializer.readInt()); packetdata.writeVarInt(serializer.readByte()); packetdata.writeVarInt(0); break; } case 0x65: { //PacketPlayInCloseWindow packet = getPacketById(0x0D); useOriginalStream = true; break; } case 0x66: { //PacketPlayInWindowClick packet = getPacketById(0x0E); if (Utils.getPlayer(channel).getOpenInventory().getType() == InventoryType.ENCHANTING) { packetdata.writeByte(serializer.readByte()); int slot = serializer.readShort(); if (slot > 0) { slot++; } packetdata.writeShort(slot); packetdata.writeByte(serializer.readByte()); packetdata.writeShort(serializer.readShort()); packetdata.writeByte(serializer.readByte()); packetdata.writeItemStack(serializer.readItemStack()); } else { useOriginalStream = true; } break; } case 0x6A: { //PacketPlayInTransaction packet = getPacketById(0x0F); useOriginalStream = true; break; } case 0x6B: { //PacketPlayInSetCreativeSlot packet = getPacketById(0x10); useOriginalStream = true; break; } case 0x6C: { //PacketPlayInEnchantItem packet = getPacketById(0x11); useOriginalStream = true; break; } case 0x82: { //PacketPlayInUpdateSign packet = getPacketById(0x12); packetdata.a(new BlockPosition(serializer.readInt(), serializer.readShort(), serializer.readInt())); for (int i = 0; i < 4; i++) { packetdata.writeString(ChatSerializer.a(new ChatComponentText(serializer.readString(15)))); } break; } case 0xCA: { //PacketPlayInAbilities packet = getPacketById(0x13); packetdata.writeByte(serializer.readUnsignedByte()); packetdata.writeFloat(serializer.readByte() / 255.0F); packetdata.writeFloat(serializer.readByte() / 255.0F); break; } case 0xCB: { //PacketPlayInTabComplete packet = getPacketById(0x14); packetdata.writeString(serializer.readString(32767)); packetdata.writeBoolean(false); break; } case 0xCC: { //PacketPlayInSettings packet = getPacketById(0x15); packetdata.writeString(serializer.readString(32767)); packetdata.writeByte(serializer.readByte()); int chatState = serializer.readByte(); packetdata.writeByte(chatState & 7); packetdata.writeBoolean((chatState & 8) == 8); serializer.readByte(); serializer.readBoolean(); packetdata.writeByte(0); break; } case 0xCD: { //PacketPlayInClientCommand packet = getPacketById(0x16); packetdata.writeVarInt(0); serializer.readByte(); break; } case 0xFA: { //PacketPlayInCustomPayload packet = getPacketById(0x17); String tag = serializer.readString(20); packetdata.writeString(tag); ByteBuf buf = serializer.readBytes(serializer.readShort()); //special handle for anvil renaming, in 1.8 it reads string from serializer, but in 1.7 and before it just reads bytes and converts it to string if (tag.equalsIgnoreCase("MC|ItemName")) { packetdata.writeVarInt(buf.readableBytes()); } packetdata.writeBytes(buf); break; } case 0xFF: { //No corresponding packet serializer.readString(32767); return new Packet[0]; } } if (packet != null) { packet.a(useOriginalStream ? serializer : packetdata); return new Packet[] {packet}; } return null; } private Packet getPacketById(int realPacketId) { return EnumProtocol.PLAY.a(EnumProtocolDirection.SERVERBOUND, realPacketId); } }
Partially fix vehicle riing for 1.5.2
src/protocolsupport/protocol/v_1_5/serverboundtransformer/PlayPacketTransformer.java
Partially fix vehicle riing for 1.5.2
<ide><path>rc/protocolsupport/protocol/v_1_5/serverboundtransformer/PlayPacketTransformer.java <ide> break; <ide> } <ide> case 0x07: { //PacketPlayInUseEntity <del> packet = getPacketById(0x02); <ide> serializer.readInt(); <del> packetdata.writeVarInt(serializer.readInt()); <del> packetdata.writeVarInt(serializer.readBoolean() ? 1 : 0); <add> int entityId = serializer.readInt(); <add> boolean isLeftClick = serializer.readBoolean(); <add> //if player interacts with the entity he is riding than he wants to unmont it <add> if (!isLeftClick) { <add> //reading is async so this is potentially dangerous <add> org.bukkit.entity.Entity vehicle = Utils.getPlayer(channel).getVehicle(); <add> if (vehicle != null && vehicle.getEntityId() == entityId) { <add> packet = getPacketById(0x0C); <add> packetdata.writeFloat(0); <add> packetdata.writeFloat(0); <add> packetdata.writeByte(1 << 1); <add> } else { <add> packet = getPacketById(0x02); <add> packetdata.writeVarInt(entityId); <add> packetdata.writeVarInt(isLeftClick ? 1 : 0); <add> } <add> } else { <add> packet = getPacketById(0x02); <add> packetdata.writeVarInt(entityId); <add> packetdata.writeVarInt(isLeftClick ? 1 : 0); <add> } <ide> break; <ide> } <ide> case 0x0A: { //PacketPlayInFlying <ide> break; <ide> } <ide> case 0x0D: { //PacketPlayInPositionLook <del> packet = getPacketById(0x06); <del> packetdata.writeDouble(serializer.readDouble()); <del> packetdata.writeDouble(serializer.readDouble()); <del> serializer.readDouble(); <del> packetdata.writeDouble(serializer.readDouble()); <del> packetdata.writeFloat(serializer.readFloat()); <del> packetdata.writeFloat(serializer.readFloat()); <del> packetdata.writeBoolean(serializer.readBoolean()); <add> double x = serializer.readDouble(); <add> double yfeet = serializer.readDouble(); <add> double y = serializer.readDouble(); <add> double z = serializer.readDouble(); <add> float yaw = serializer.readFloat(); <add> float pitch = serializer.readFloat(); <add> boolean onGroud = serializer.readBoolean(); <add> //when y is -999.0D than it means that client actually tries to control vehicle movement <add> if (yfeet == -999.0D && y == -999.0D) { <add> Packet[] packets = new Packet[2]; <add> Packet playerlook = getPacketById(0x05); <add> packetdata.writeFloat(yaw); <add> packetdata.writeFloat(pitch); <add> packetdata.writeBoolean(onGroud); <add> playerlook.a(packetdata); <add> packets[0] = playerlook; <add> packetdata.clear(); <add> Packet steervehicle = getPacketById(0x0C); <add> //TODO: convert motX and motZ to strafes <add> packetdata.writeFloat(0.0F); <add> packetdata.writeFloat(0.0F); <add> packetdata.writeByte(0); <add> steervehicle.a(packetdata); <add> packets[1] = steervehicle; <add> return packets; <add> } else { <add> packet = getPacketById(0x06); <add> packetdata.writeDouble(x); <add> packetdata.writeDouble(yfeet); <add> packetdata.writeDouble(z); <add> packetdata.writeFloat(yaw); <add> packetdata.writeFloat(pitch); <add> packetdata.writeBoolean(onGroud); <add> } <ide> break; <ide> } <ide> case 0x0E: { //PacketPlayInBlockDig
Java
apache-2.0
e67a6c22595e7538a46d395fe10f3ba431428a40
0
hito-asa/HikariCP,yaojuncn/HikariCP,newsky/HikariCP,mwegrz/HikariCP,785468931/HikariCP,udayshnk/HikariCP,squidsolutions/HikariCP,sridhar-newsdistill/HikariCP,nitincchauhan/HikariCP,guai/HikariCP,Violantic/HikariCP,guai/HikariCP,brettwooldridge/HikariCP,polpot78/HikariCP,brettwooldridge/HikariCP,schlosna/HikariCP,kschmit90/HikariCP,ams2990/HikariCP,barrysun/HikariCP,openbouquet/HikariCP,ligzy/HikariCP,atschx/HikariCP,zhuyihao/HikariCP,junlapong/HikariCP
/* * Copyright (C) 2013, 2014 Brett Wooldridge * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zaxxer.hikari; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Before; import com.zaxxer.hikari.util.UtilityElf; /** * This test is meant to be run manually and interactively and was * build for issue #159. * * @author Brett Wooldridge */ public class PostgresTest { //@Test public void testCase1() throws Exception { HikariConfig config = new HikariConfig(); config.setMinimumIdle(3); config.setMaximumPoolSize(10); config.setConnectionTimeout(3000); config.setIdleTimeout(TimeUnit.SECONDS.toMillis(10)); config.setValidationTimeout(TimeUnit.SECONDS.toMillis(2)); config.setJdbcUrl("jdbc:pgsql://localhost:5432/test"); config.setUsername("brettw"); try (final HikariDataSource ds = new HikariDataSource(config)) { final long start = System.currentTimeMillis(); do { Thread t = new Thread() { public void run() { try (Connection connection = ds.getConnection()) { System.err.println("Obtained connection " + connection); UtilityElf.quietlySleep(TimeUnit.SECONDS.toMillis((long)(10 + (Math.random() * 20)))); } catch (SQLException e) { e.printStackTrace(); } } }; t.setDaemon(true); t.start(); UtilityElf.quietlySleep(TimeUnit.SECONDS.toMillis((long)((Math.random() * 20)))); } while (UtilityElf.elapsedTimeMs(start) < TimeUnit.MINUTES.toMillis(15)); } } //@Test public void testCase2() throws Exception { HikariConfig config = new HikariConfig(); config.setMinimumIdle(3); config.setMaximumPoolSize(10); config.setConnectionTimeout(1000); config.setIdleTimeout(TimeUnit.SECONDS.toMillis(60)); config.setJdbcUrl("jdbc:pgsql://localhost:5432/test"); config.setUsername("brettw"); try (HikariDataSource ds = new HikariDataSource(config)) { try (Connection conn = ds.getConnection()) { System.err.println("\nGot a connection, and released it. Now, enable the firewall."); } TestElf.getPool(ds).logPoolState(); UtilityElf.quietlySleep(5000L); System.err.println("\nNow attempting another getConnection(), expecting a timeout..."); long start = System.currentTimeMillis(); try (Connection conn = ds.getConnection()) { System.err.println("\nOpps, got a connection. Did you enable the firewall? " + conn); Assert.fail("Opps, got a connection. Did you enable the firewall?"); } catch (SQLException e) { Assert.assertTrue("Timeout less than expected " + (System.currentTimeMillis() - start) + "ms", (System.currentTimeMillis() - start) > 5000); } System.err.println("\nOk, so far so good. Now, disable the firewall again. Attempting connection in 5 seconds..."); UtilityElf.quietlySleep(5000L); TestElf.getPool(ds).logPoolState(); try (Connection conn = ds.getConnection()) { System.err.println("\nGot a connection, and released it."); } } System.err.println("\nPassed."); } //@Test public void testCase3() throws Exception { HikariConfig config = new HikariConfig(); config.setMinimumIdle(3); config.setMaximumPoolSize(10); config.setConnectionTimeout(1000); config.setIdleTimeout(TimeUnit.SECONDS.toMillis(60)); config.setJdbcUrl("jdbc:pgsql://localhost:5432/test"); config.setUsername("brettw"); try (final HikariDataSource ds = new HikariDataSource(config)) { for (int i = 0; i < 10; i++) { new Thread() { public void run() { try (Connection conn = ds.getConnection()) { System.err.println("ERROR: should not have acquired connection."); } catch (SQLException e) { // expected } }; }.start(); } UtilityElf.quietlySleep(5000L); System.err.println("Now, bring the DB online. Checking pool in 15 seconds."); UtilityElf.quietlySleep(15000L); TestElf.getPool(ds).logPoolState(); } } @Before public void before() { System.err.println("\n"); } }
hikaricp/src/test/java/com/zaxxer/hikari/PostgresTest.java
/* * Copyright (C) 2013, 2014 Brett Wooldridge * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zaxxer.hikari; import java.sql.Connection; import java.sql.SQLException; import org.junit.Assert; import org.junit.Before; import com.zaxxer.hikari.util.UtilityElf; /** * This test is meant to be run manually and interactively and was * build for issue #159. * * @author Brett Wooldridge */ public class PostgresTest { //@Test public void testCase1() throws Exception { HikariConfig config = new HikariConfig(); config.setMinimumIdle(0); config.setMaximumPoolSize(10); config.setConnectionTimeout(5000); config.setConnectionTestQuery("VALUES 1"); config.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource"); config.addDataSourceProperty("serverName", "192.168.0.114"); config.addDataSourceProperty("portNumber", "5432"); config.addDataSourceProperty("databaseName", "test"); config.addDataSourceProperty("user", "brettw"); config.addDataSourceProperty("tcpKeepAlive", true); try (HikariDataSource ds = new HikariDataSource(config)) { System.err.println("\nMake sure the firewall is enabled. Attempting connection in 5 seconds..."); UtilityElf.quietlySleep(5000L); TestElf.getPool(ds).logPoolState(); System.err.println("\nNow attempting getConnection(), expecting a timeout..."); long start = System.currentTimeMillis(); try (Connection conn = ds.getConnection()) { System.err.println("\nOpps, got a connection. Are you sure the firewall is enabled?"); } catch (SQLException e) { Assert.assertTrue("Timeout less than expected " + (System.currentTimeMillis() - start) + "ms", (System.currentTimeMillis() - start) > 5000); } } System.err.println("\nPassed."); } //@Test public void testCase2() throws Exception { HikariConfig config = new HikariConfig(); config.setMinimumIdle(0); config.setMaximumPoolSize(10); config.setConnectionTimeout(5000); config.setConnectionTestQuery("VALUES 1"); config.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource"); config.addDataSourceProperty("serverName", "192.168.0.114"); config.addDataSourceProperty("portNumber", "5432"); config.addDataSourceProperty("databaseName", "test"); config.addDataSourceProperty("user", "brettw"); config.addDataSourceProperty("tcpKeepAlive", true); try (HikariDataSource ds = new HikariDataSource(config)) { System.err.println("\nDisable the firewall, please. Starting test in 5 seconds..."); UtilityElf.quietlySleep(5000L); try (Connection conn = ds.getConnection()) { System.err.println("\nGot a connection, and released it. Now, enable the firewall."); } TestElf.getPool(ds).logPoolState(); UtilityElf.quietlySleep(5000L); System.err.println("\nNow attempting another getConnection(), expecting a timeout..."); long start = System.currentTimeMillis(); try (Connection conn = ds.getConnection()) { System.err.println("\nOpps, got a connection. Did you enable the firewall? " + conn); Assert.fail("Opps, got a connection. Did you enable the firewall?"); } catch (SQLException e) { Assert.assertTrue("Timeout less than expected " + (System.currentTimeMillis() - start) + "ms", (System.currentTimeMillis() - start) > 5000); } System.err.println("\nOk, so far so good. Now, disable the firewall again. Attempting connection in 5 seconds..."); UtilityElf.quietlySleep(5000L); TestElf.getPool(ds).logPoolState(); try (Connection conn = ds.getConnection()) { System.err.println("\nGot a connection, and released it."); } } System.err.println("\nPassed."); } //@Test public void testCase3() throws Exception { HikariConfig config = new HikariConfig(); config.setMinimumIdle(0); config.setMaximumPoolSize(10); config.setInitializationFailFast(false); config.setConnectionTimeout(2000); config.setConnectionTestQuery("VALUES 1"); config.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource"); config.addDataSourceProperty("serverName", "192.168.0.114"); config.addDataSourceProperty("portNumber", "5432"); config.addDataSourceProperty("databaseName", "test"); config.addDataSourceProperty("user", "brettw"); config.addDataSourceProperty("tcpKeepAlive", true); System.err.println("\nShutdown the database, please. Starting test in 15 seconds..."); UtilityElf.quietlySleep(15000L); try (final HikariDataSource ds = new HikariDataSource(config)) { for (int i = 0; i < 10; i++) { new Thread() { public void run() { try (Connection conn = ds.getConnection()) { System.err.println("ERROR: should not have acquired connection."); } catch (SQLException e) { // expected } }; }.start(); } UtilityElf.quietlySleep(5000L); System.err.println("Now, bring the DB online. Checking pool in 15 seconds."); UtilityElf.quietlySleep(15000L); TestElf.getPool(ds).logPoolState(); } } @Before public void before() { System.err.println("\n"); } }
PostgreSQL test tweaks...
hikaricp/src/test/java/com/zaxxer/hikari/PostgresTest.java
PostgreSQL test tweaks...
<ide><path>ikaricp/src/test/java/com/zaxxer/hikari/PostgresTest.java <ide> <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <add>import java.util.concurrent.TimeUnit; <ide> <ide> import org.junit.Assert; <ide> import org.junit.Before; <ide> public void testCase1() throws Exception <ide> { <ide> HikariConfig config = new HikariConfig(); <del> config.setMinimumIdle(0); <add> config.setMinimumIdle(3); <ide> config.setMaximumPoolSize(10); <del> config.setConnectionTimeout(5000); <del> config.setConnectionTestQuery("VALUES 1"); <add> config.setConnectionTimeout(3000); <add> config.setIdleTimeout(TimeUnit.SECONDS.toMillis(10)); <add> config.setValidationTimeout(TimeUnit.SECONDS.toMillis(2)); <ide> <del> config.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource"); <del> config.addDataSourceProperty("serverName", "192.168.0.114"); <del> config.addDataSourceProperty("portNumber", "5432"); <del> config.addDataSourceProperty("databaseName", "test"); <del> config.addDataSourceProperty("user", "brettw"); <del> config.addDataSourceProperty("tcpKeepAlive", true); <add> config.setJdbcUrl("jdbc:pgsql://localhost:5432/test"); <add> config.setUsername("brettw"); <ide> <del> try (HikariDataSource ds = new HikariDataSource(config)) { <add> try (final HikariDataSource ds = new HikariDataSource(config)) { <add> final long start = System.currentTimeMillis(); <add> do { <add> Thread t = new Thread() { <add> public void run() { <add> try (Connection connection = ds.getConnection()) { <add> System.err.println("Obtained connection " + connection); <add> UtilityElf.quietlySleep(TimeUnit.SECONDS.toMillis((long)(10 + (Math.random() * 20)))); <add> } <add> catch (SQLException e) { <add> e.printStackTrace(); <add> } <add> } <add> }; <add> t.setDaemon(true); <add> t.start(); <ide> <del> System.err.println("\nMake sure the firewall is enabled. Attempting connection in 5 seconds..."); <del> UtilityElf.quietlySleep(5000L); <del> <del> TestElf.getPool(ds).logPoolState(); <del> <del> System.err.println("\nNow attempting getConnection(), expecting a timeout..."); <del> <del> long start = System.currentTimeMillis(); <del> try (Connection conn = ds.getConnection()) { <del> System.err.println("\nOpps, got a connection. Are you sure the firewall is enabled?"); <del> } <del> catch (SQLException e) <del> { <del> Assert.assertTrue("Timeout less than expected " + (System.currentTimeMillis() - start) + "ms", (System.currentTimeMillis() - start) > 5000); <del> } <add> UtilityElf.quietlySleep(TimeUnit.SECONDS.toMillis((long)((Math.random() * 20)))); <add> } while (UtilityElf.elapsedTimeMs(start) < TimeUnit.MINUTES.toMillis(15)); <ide> } <del> <del> System.err.println("\nPassed."); <ide> } <ide> <ide> //@Test <ide> public void testCase2() throws Exception <ide> { <ide> HikariConfig config = new HikariConfig(); <del> config.setMinimumIdle(0); <add> config.setMinimumIdle(3); <ide> config.setMaximumPoolSize(10); <del> config.setConnectionTimeout(5000); <del> config.setConnectionTestQuery("VALUES 1"); <add> config.setConnectionTimeout(1000); <add> config.setIdleTimeout(TimeUnit.SECONDS.toMillis(60)); <ide> <del> config.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource"); <del> config.addDataSourceProperty("serverName", "192.168.0.114"); <del> config.addDataSourceProperty("portNumber", "5432"); <del> config.addDataSourceProperty("databaseName", "test"); <del> config.addDataSourceProperty("user", "brettw"); <del> config.addDataSourceProperty("tcpKeepAlive", true); <add> config.setJdbcUrl("jdbc:pgsql://localhost:5432/test"); <add> config.setUsername("brettw"); <ide> <ide> try (HikariDataSource ds = new HikariDataSource(config)) { <del> <del> System.err.println("\nDisable the firewall, please. Starting test in 5 seconds..."); <del> UtilityElf.quietlySleep(5000L); <ide> <ide> try (Connection conn = ds.getConnection()) { <ide> System.err.println("\nGot a connection, and released it. Now, enable the firewall."); <ide> public void testCase3() throws Exception <ide> { <ide> HikariConfig config = new HikariConfig(); <del> config.setMinimumIdle(0); <add> config.setMinimumIdle(3); <ide> config.setMaximumPoolSize(10); <del> config.setInitializationFailFast(false); <del> config.setConnectionTimeout(2000); <del> config.setConnectionTestQuery("VALUES 1"); <add> config.setConnectionTimeout(1000); <add> config.setIdleTimeout(TimeUnit.SECONDS.toMillis(60)); <ide> <del> config.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource"); <del> config.addDataSourceProperty("serverName", "192.168.0.114"); <del> config.addDataSourceProperty("portNumber", "5432"); <del> config.addDataSourceProperty("databaseName", "test"); <del> config.addDataSourceProperty("user", "brettw"); <del> config.addDataSourceProperty("tcpKeepAlive", true); <del> <del> System.err.println("\nShutdown the database, please. Starting test in 15 seconds..."); <del> UtilityElf.quietlySleep(15000L); <add> config.setJdbcUrl("jdbc:pgsql://localhost:5432/test"); <add> config.setUsername("brettw"); <ide> <ide> try (final HikariDataSource ds = new HikariDataSource(config)) { <ide> for (int i = 0; i < 10; i++) {
Java
agpl-3.0
b489645636d421758e9647a09c28b68a911bf07b
0
elki-project/elki,elki-project/elki,elki-project/elki
package experimentalcode.erich.visualization.svg; /** * Color scheme interface * * @author Erich Schubert * */ public interface ColorLibrary { /** * Return the number of native colors available. These are guaranteed to be unique. * * @return number of native colors */ public int getNumberOfNativeColors(); /** * Return the i'th color. * * @param index color index * @return color in hexadecimal notation (#aabbcc) or color name ("red") as valid in CSS and SVG. */ public String getColor(int index); }
src/experimentalcode/erich/visualization/svg/ColorLibrary.java
package experimentalcode.erich.visualization.svg; /** * Color scheme interface * * @author Erich Schubert * */ public interface ColorLibrary { /** * Return the number of native colors available. These are guaranteed to be unique. * * @return number of native colors */ public int getNumberOfNativeColors(); /** * Return the i'th color. * * @param index color index * @return color in hexadecimal notation (#aabbcc) (CSS/SVG/HTML) */ public String getColor(int index); }
javadoc
src/experimentalcode/erich/visualization/svg/ColorLibrary.java
javadoc
<ide><path>rc/experimentalcode/erich/visualization/svg/ColorLibrary.java <ide> * Return the i'th color. <ide> * <ide> * @param index color index <del> * @return color in hexadecimal notation (#aabbcc) (CSS/SVG/HTML) <add> * @return color in hexadecimal notation (#aabbcc) or color name ("red") as valid in CSS and SVG. <ide> */ <ide> public String getColor(int index); <ide> }
Java
apache-2.0
7ae8b5e105ba4f0441156b2192547ec7e7aac3fe
0
anhtu1995ok/seaglass
/* * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr. * * This file is part of the SeaGlass Pluggable Look and Feel. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ */ package com.seaglasslookandfeel.painter; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import javax.swing.JComponent; import com.seaglasslookandfeel.painter.AbstractRegionPainter.PaintContext.CacheMode; /** * Nimbus's ScrollPanePainter. */ public final class ScrollPanePainter extends AbstractRegionPainter { public static enum Which { BACKGROUND_ENABLED, BORDER_ENABLED, BORDER_ENABLED_FOCUSED, CORNER_ENABLED, } private static final Insets insets = new Insets(5, 5, 5, 5); private static final Dimension dimension = new Dimension(122, 24); private static final CacheMode cacheMode = CacheMode.FIXED_SIZES; private static final Double maxH = Double.POSITIVE_INFINITY; private static final Double maxV = Double.POSITIVE_INFINITY; private Which state; private PaintContext ctx; private Rectangle2D rect = new Rectangle2D.Double(); private Path2D path = new Path2D.Float(); private Color borderColor = decodeColor("nimbusBorder", 0.0f, 0.0f, 0.0f, 0); private Color focusColor = decodeColor("nimbusFocus", 0.0f, 0.0f, 0.0f, 0); private Color cornerBorder = new Color(192, 192, 192); private Color cornerColor1 = new Color(240, 240, 240); private Color cornerColor2 = new Color(212, 212, 212); public ScrollPanePainter(Which state) { super(); this.state = state; this.ctx = new PaintContext(insets, dimension, false, cacheMode, maxH, maxV); } protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) { switch (state) { case BORDER_ENABLED: paintBorderEnabled(g, width, height); break; case BORDER_ENABLED_FOCUSED: paintBorderFocused(g, width, height); break; case CORNER_ENABLED: paintCornerEnabled(g, width, height); break; } } protected final PaintContext getPaintContext() { return ctx; } private void paintBorderEnabled(Graphics2D g, int width, int height) { g.setPaint(borderColor); g.drawLine(3, 2, width - 4, 2); g.drawLine(2, 2, 2, height - 3); g.drawLine(width - 3, 2, width - 3, height - 3); g.drawLine(3, height - 3, width - 4, height - 3); } private void paintBorderFocused(Graphics2D g, int width, int height) { paintBorderEnabled(g, width, height); Shape s = decodeFocusPath(width, height); g.setPaint(focusColor); g.fill(s); } private void paintCornerEnabled(Graphics2D g, int width, int height) { Shape s = decodeCornerBorder(width, height); g.setPaint(cornerBorder); g.fill(s); s = decodeCornerInside(width, height); g.setPaint(decodeCornerGradient(s)); g.fill(s); } private Shape decodeFocusPath(int width, int height) { float left = 2; float top = 2; float right = width - 2; float bottom = height - 2; path.reset(); path.moveTo(left, top); path.lineTo(left, bottom); path.lineTo(right, bottom); path.lineTo(right, top); float left2 = 0.6f; float top2 = 0.6f; float right2 = width - 0.6f; float bottom2 = height - 0.6f; // TODO These two lines were curveTo in Nimbus. Perhaps we should // revisit this? path.lineTo(right2, top); path.lineTo(right2, bottom2); path.lineTo(left2, bottom2); path.lineTo(left2, top2); path.lineTo(right2, top2); path.lineTo(right2, top); path.closePath(); return path; } private Shape decodeCornerBorder(int width, int height) { rect.setRect(0, 0, width, height); return rect; } private Shape decodeCornerInside(int width, int height) { rect.setRect(1, 1, width - 2, height - 2); return rect; } private Paint decodeCornerGradient(Shape s) { Rectangle2D bounds = s.getBounds2D(); float w = (float) bounds.getWidth(); float h = (float) bounds.getHeight(); return decodeGradient(1, 1, w - 2, h - 2, new float[] { 0f, 1f }, new Color[] { cornerColor1, cornerColor2 }); } }
src/main/java/com/seaglasslookandfeel/painter/ScrollPanePainter.java
/* * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr. * * This file is part of the SeaGlass Pluggable Look and Feel. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ */ package com.seaglasslookandfeel.painter; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Shape; import java.awt.geom.Path2D; import javax.swing.JComponent; import com.seaglasslookandfeel.painter.AbstractRegionPainter.PaintContext.CacheMode; /** * Nimbus's ScrollPanePainter. */ public final class ScrollPanePainter extends AbstractRegionPainter { public static enum Which { BACKGROUND_ENABLED, BORDER_ENABLED, BORDER_ENABLED_FOCUSED } private static final Insets insets = new Insets(5, 5, 5, 5); private static final Dimension dimension = new Dimension(122, 24); private static final CacheMode cacheMode = CacheMode.FIXED_SIZES; private static final Double maxH = Double.POSITIVE_INFINITY; private static final Double maxV = Double.POSITIVE_INFINITY; private Which state; private PaintContext ctx; private Path2D path = new Path2D.Float(); private Color borderColor = decodeColor("nimbusBorder", 0.0f, 0.0f, 0.0f, 0); private Color focusColor = decodeColor("nimbusFocus", 0.0f, 0.0f, 0.0f, 0); public ScrollPanePainter(Which state) { super(); this.state = state; this.ctx = new PaintContext(insets, dimension, false, cacheMode, maxH, maxV); } protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) { switch (state) { case BORDER_ENABLED: paintBorderEnabled(g, width, height); break; case BORDER_ENABLED_FOCUSED: paintBorderFocused(g, width, height); break; } } protected final PaintContext getPaintContext() { return ctx; } private void paintBorderEnabled(Graphics2D g, int width, int height) { g.setPaint(borderColor); g.drawLine(3, 2, width - 4, 2); g.drawLine(2, 2, 2, height - 3); g.drawLine(width - 3, 2, width - 3, height - 3); g.drawLine(3, height - 3, width - 4, height - 3); } private void paintBorderFocused(Graphics2D g, int width, int height) { paintBorderEnabled(g, width, height); Shape s = decodeFocusPath(width, height); g.setPaint(focusColor); g.fill(s); } private Shape decodeFocusPath(int width, int height) { float left = 2; float top = 2; float right = width - 2; float bottom = height - 2; path.reset(); path.moveTo(left, top); path.lineTo(left, bottom); path.lineTo(right, bottom); path.lineTo(right, top); float left2 = 0.6f; float top2 = 0.6f; float right2 = width - 0.6f; float bottom2 = height - 0.6f; // TODO These two lines were curveTo in Nimbus. Perhaps we should revisit this? path.lineTo(right2, top); path.lineTo(right2, bottom2); path.lineTo(left2, bottom2); path.lineTo(left2, top2); path.lineTo(right2, top2); path.lineTo(right2, top); path.closePath(); return path; } }
Added painter state for painting the scrollpane corner when there are two scrollbars.
src/main/java/com/seaglasslookandfeel/painter/ScrollPanePainter.java
Added painter state for painting the scrollpane corner when there are two scrollbars.
<ide><path>rc/main/java/com/seaglasslookandfeel/painter/ScrollPanePainter.java <ide> import java.awt.Dimension; <ide> import java.awt.Graphics2D; <ide> import java.awt.Insets; <add>import java.awt.Paint; <ide> import java.awt.Shape; <ide> import java.awt.geom.Path2D; <add>import java.awt.geom.Rectangle2D; <ide> <ide> import javax.swing.JComponent; <ide> <ide> */ <ide> public final class ScrollPanePainter extends AbstractRegionPainter { <ide> public static enum Which { <del> BACKGROUND_ENABLED, BORDER_ENABLED, BORDER_ENABLED_FOCUSED <add> BACKGROUND_ENABLED, BORDER_ENABLED, BORDER_ENABLED_FOCUSED, CORNER_ENABLED, <ide> } <ide> <del> private static final Insets insets = new Insets(5, 5, 5, 5); <del> private static final Dimension dimension = new Dimension(122, 24); <del> private static final CacheMode cacheMode = CacheMode.FIXED_SIZES; <del> private static final Double maxH = Double.POSITIVE_INFINITY; <del> private static final Double maxV = Double.POSITIVE_INFINITY; <add> private static final Insets insets = new Insets(5, 5, 5, 5); <add> private static final Dimension dimension = new Dimension(122, 24); <add> private static final CacheMode cacheMode = CacheMode.FIXED_SIZES; <add> private static final Double maxH = Double.POSITIVE_INFINITY; <add> private static final Double maxV = Double.POSITIVE_INFINITY; <ide> <ide> private Which state; <ide> private PaintContext ctx; <ide> <del> private Path2D path = new Path2D.Float(); <add> private Rectangle2D rect = new Rectangle2D.Double(); <add> private Path2D path = new Path2D.Float(); <ide> <del> private Color borderColor = decodeColor("nimbusBorder", 0.0f, 0.0f, 0.0f, 0); <del> private Color focusColor = decodeColor("nimbusFocus", 0.0f, 0.0f, 0.0f, 0); <add> private Color borderColor = decodeColor("nimbusBorder", 0.0f, 0.0f, 0.0f, 0); <add> private Color focusColor = decodeColor("nimbusFocus", 0.0f, 0.0f, 0.0f, 0); <add> <add> private Color cornerBorder = new Color(192, 192, 192); <add> private Color cornerColor1 = new Color(240, 240, 240); <add> private Color cornerColor2 = new Color(212, 212, 212); <ide> <ide> public ScrollPanePainter(Which state) { <ide> super(); <ide> break; <ide> case BORDER_ENABLED_FOCUSED: <ide> paintBorderFocused(g, width, height); <add> break; <add> case CORNER_ENABLED: <add> paintCornerEnabled(g, width, height); <ide> break; <ide> } <ide> } <ide> g.fill(s); <ide> } <ide> <add> private void paintCornerEnabled(Graphics2D g, int width, int height) { <add> Shape s = decodeCornerBorder(width, height); <add> g.setPaint(cornerBorder); <add> g.fill(s); <add> s = decodeCornerInside(width, height); <add> g.setPaint(decodeCornerGradient(s)); <add> g.fill(s); <add> } <add> <ide> private Shape decodeFocusPath(int width, int height) { <ide> float left = 2; <ide> float top = 2; <ide> float right2 = width - 0.6f; <ide> float bottom2 = height - 0.6f; <ide> <del> // TODO These two lines were curveTo in Nimbus. Perhaps we should revisit this? <add> // TODO These two lines were curveTo in Nimbus. Perhaps we should <add> // revisit this? <ide> path.lineTo(right2, top); <ide> path.lineTo(right2, bottom2); <ide> path.lineTo(left2, bottom2); <ide> <ide> return path; <ide> } <add> <add> private Shape decodeCornerBorder(int width, int height) { <add> rect.setRect(0, 0, width, height); <add> return rect; <add> } <add> <add> private Shape decodeCornerInside(int width, int height) { <add> rect.setRect(1, 1, width - 2, height - 2); <add> return rect; <add> } <add> <add> private Paint decodeCornerGradient(Shape s) { <add> Rectangle2D bounds = s.getBounds2D(); <add> float w = (float) bounds.getWidth(); <add> float h = (float) bounds.getHeight(); <add> return decodeGradient(1, 1, w - 2, h - 2, new float[] { 0f, 1f }, new Color[] { cornerColor1, cornerColor2 }); <add> } <ide> }
Java
apache-2.0
1afa9d222712c49fcc43d65bb991eef3641a8e15
0
ronsigal/xerces,RackerWilliams/xercesj,ronsigal/xerces,jimma/xerces,ronsigal/xerces,jimma/xerces,RackerWilliams/xercesj,jimma/xerces,RackerWilliams/xercesj
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001-2003 The Apache Software Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2002, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.parsers; import java.io.IOException; import java.util.Hashtable; import java.util.Locale; import java.util.Vector; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.XML11DTDScannerImpl; import org.apache.xerces.impl.XML11DocumentScannerImpl; import org.apache.xerces.impl.XML11NSDocumentScannerImpl; import org.apache.xerces.impl.XMLDTDScannerImpl; import org.apache.xerces.impl.XMLDocumentScannerImpl; import org.apache.xerces.impl.XMLEntityHandler; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.XMLNSDocumentScannerImpl; import org.apache.xerces.impl.XMLVersionDetector; import org.apache.xerces.impl.dtd.XML11DTDProcessor; import org.apache.xerces.impl.dtd.XML11DTDValidator; import org.apache.xerces.impl.dtd.XML11NSDTDValidator; import org.apache.xerces.impl.dtd.XMLDTDProcessor; import org.apache.xerces.impl.dtd.XMLDTDValidator; import org.apache.xerces.impl.dtd.XMLNSDTDValidator; import org.apache.xerces.impl.dv.DTDDVFactory; import org.apache.xerces.impl.msg.XMLMessageFormatter; import org.apache.xerces.impl.validation.ValidationManager; import org.apache.xerces.impl.xs.XMLSchemaValidator; import org.apache.xerces.impl.xs.XSMessageFormatter; import org.apache.xerces.util.ParserConfigurationSettings; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.xni.XMLDTDContentModelHandler; import org.apache.xerces.xni.XMLDTDHandler; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDTDScanner; import org.apache.xerces.xni.parser.XMLDocumentScanner; import org.apache.xerces.xni.parser.XMLDocumentSource; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLErrorHandler; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.parser.XMLPullParserConfiguration; /** * This class is the configuration used to parse XML 1.0 and XML 1.1 documents. * This is the default Xerces configuration. * * @author Elena Litani, IBM * @author Neil Graham, IBM * @author Michael Glavassevich, IBM * * @version $Id$ */ public class XML11Configuration extends ParserConfigurationSettings implements XMLPullParserConfiguration { // // Constants // protected final static String XML11_DATATYPE_VALIDATOR_FACTORY = "org.apache.xerces.impl.dv.dtd.XML11DTDDVFactoryImpl"; // feature identifiers /** Feature identifier: warn on duplicate attribute definition. */ protected static final String WARN_ON_DUPLICATE_ATTDEF = Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ATTDEF_FEATURE; /** Feature identifier: warn on duplicate entity definition. */ protected static final String WARN_ON_DUPLICATE_ENTITYDEF = Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ENTITYDEF_FEATURE; /** Feature identifier: warn on undeclared element definition. */ protected static final String WARN_ON_UNDECLARED_ELEMDEF = Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_UNDECLARED_ELEMDEF_FEATURE; /** Feature identifier: allow Java encodings. */ protected static final String ALLOW_JAVA_ENCODINGS = Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE; /** Feature identifier: continue after fatal error. */ protected static final String CONTINUE_AFTER_FATAL_ERROR = Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE; /** Feature identifier: load external DTD. */ protected static final String LOAD_EXTERNAL_DTD = Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE; /** Feature identifier: notify built-in refereces. */ protected static final String NOTIFY_BUILTIN_REFS = Constants.XERCES_FEATURE_PREFIX + Constants.NOTIFY_BUILTIN_REFS_FEATURE; /** Feature identifier: notify character refereces. */ protected static final String NOTIFY_CHAR_REFS = Constants.XERCES_FEATURE_PREFIX + Constants.NOTIFY_CHAR_REFS_FEATURE; /** Feature identifier: expose schema normalized value */ protected static final String NORMALIZE_DATA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE; /** Feature identifier: send element default value via characters() */ protected static final String SCHEMA_ELEMENT_DEFAULT = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT; /** Feature identifier: augment PSVI */ protected static final String SCHEMA_AUGMENT_PSVI = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_AUGMENT_PSVI; /** feature identifier: XML Schema validation */ protected static final String XMLSCHEMA_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** feature identifier: XML Schema validation -- full checking */ protected static final String XMLSCHEMA_FULL_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING; // feature identifiers /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE; /** Feature identifier: namespaces. */ protected static final String NAMESPACES = Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE; /** Feature identifier: external general entities. */ protected static final String EXTERNAL_GENERAL_ENTITIES = Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE; /** Feature identifier: external parameter entities. */ protected static final String EXTERNAL_PARAMETER_ENTITIES = Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE; // property identifiers /** Property identifier: xml string. */ protected static final String XML_STRING = Constants.SAX_PROPERTY_PREFIX + Constants.XML_STRING_PROPERTY; /** Property identifier: symbol table. */ protected static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error handler. */ protected static final String ERROR_HANDLER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; /** Property identifier: entity resolver. */ protected static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** Property identifier: XML Schema validator. */ protected static final String SCHEMA_VALIDATOR = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY; /** Property identifier: schema location. */ protected static final String SCHEMA_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION; /** Property identifier: no namespace schema location. */ protected static final String SCHEMA_NONS_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION; // property identifiers /** Property identifier: error reporter. */ protected static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: entity manager. */ protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; /** Property identifier document scanner: */ protected static final String DOCUMENT_SCANNER = Constants.XERCES_PROPERTY_PREFIX + Constants.DOCUMENT_SCANNER_PROPERTY; /** Property identifier: DTD scanner. */ protected static final String DTD_SCANNER = Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_SCANNER_PROPERTY; /** Property identifier: grammar pool. */ protected static final String XMLGRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; /** Property identifier: DTD loader. */ protected static final String DTD_PROCESSOR = Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_PROCESSOR_PROPERTY; /** Property identifier: DTD validator. */ protected static final String DTD_VALIDATOR = Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_VALIDATOR_PROPERTY; /** Property identifier: namespace binder. */ protected static final String NAMESPACE_BINDER = Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_BINDER_PROPERTY; /** Property identifier: datatype validator factory. */ protected static final String DATATYPE_VALIDATOR_FACTORY = Constants.XERCES_PROPERTY_PREFIX + Constants.DATATYPE_VALIDATOR_FACTORY_PROPERTY; protected static final String VALIDATION_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; /** Property identifier: JAXP schema language / DOM schema-type. */ protected static final String JAXP_SCHEMA_LANGUAGE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE; /** Property identifier: JAXP schema source/ DOM schema-location. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; // debugging /** Set to true and recompile to print exception stack trace. */ protected static final boolean PRINT_EXCEPTION_STACK_TRACE = false; // // Data // protected SymbolTable fSymbolTable; protected XMLInputSource fInputSource; protected ValidationManager fValidationManager; protected XMLVersionDetector fVersionDetector; protected XMLLocator fLocator; protected Locale fLocale; /** XML 1.0 Components. */ protected Vector fComponents; /** XML 1.1. Components. */ protected Vector fXML11Components = null; /** Common components: XMLEntityManager, XMLErrorReporter, XMLSchemaValidator */ protected Vector fCommonComponents = null; /** The document handler. */ protected XMLDocumentHandler fDocumentHandler; /** The DTD handler. */ protected XMLDTDHandler fDTDHandler; /** The DTD content model handler. */ protected XMLDTDContentModelHandler fDTDContentModelHandler; /** Last component in the document pipeline */ protected XMLDocumentSource fLastComponent; /** * True if a parse is in progress. This state is needed because * some features/properties cannot be set while parsing (e.g. * validation and namespaces). */ protected boolean fParseInProgress = false; /** fConfigUpdated is set to true if there has been any change to the configuration settings, * i.e a feature or a property was changed. */ protected boolean fConfigUpdated = false; // // XML 1.0 components // /** The XML 1.0 Datatype validator factory. */ protected DTDDVFactory fDatatypeValidatorFactory; /** The XML 1.0 Document scanner that does namespace binding. */ protected XMLNSDocumentScannerImpl fNamespaceScanner; /** The XML 1.0 Non-namespace implementation of scanner */ protected XMLDocumentScannerImpl fNonNSScanner; /** The XML 1.0 DTD Validator: binds namespaces */ protected XMLDTDValidator fDTDValidator; /** The XML 1.0 DTD Validator that does not bind namespaces */ protected XMLDTDValidator fNonNSDTDValidator; /** The XML 1.0 DTD scanner. */ protected XMLDTDScanner fDTDScanner; /** The XML 1.0 DTD Processor . */ protected XMLDTDProcessor fDTDProcessor; // // XML 1.1 components // /** The XML 1.1 datatype factory. **/ protected DTDDVFactory fXML11DatatypeFactory = null; /** The XML 1.1 document scanner that does namespace binding. **/ protected XML11NSDocumentScannerImpl fXML11NSDocScanner = null; /** The XML 1.1 document scanner that does not do namespace binding. **/ protected XML11DocumentScannerImpl fXML11DocScanner = null; /** The XML 1.1 DTD validator that does namespace binding. **/ protected XML11NSDTDValidator fXML11NSDTDValidator = null; /** The XML 1.1 DTD validator that does not do namespace binding. **/ protected XML11DTDValidator fXML11DTDValidator = null; /** The XML 1.1 DTD scanner. **/ protected XML11DTDScannerImpl fXML11DTDScanner = null; /** The XML 1.1 DTD processor. **/ protected XML11DTDProcessor fXML11DTDProcessor = null; // // Common components // /** Grammar pool. */ protected XMLGrammarPool fGrammarPool; /** Error reporter. */ protected XMLErrorReporter fErrorReporter; /** Entity manager. */ protected XMLEntityManager fEntityManager; /** XML Schema Validator. */ protected XMLSchemaValidator fSchemaValidator; /** Current scanner */ protected XMLDocumentScanner fCurrentScanner; /** Current Datatype validator factory. */ protected DTDDVFactory fCurrentDVFactory; /** Current DTD scanner. */ protected XMLDTDScanner fCurrentDTDScanner; private boolean fInitalized = false; // // Constructors // /** Default constructor. */ public XML11Configuration() { this(null, null, null); } // <init>() /** * Constructs a parser configuration using the specified symbol table. * * @param symbolTable The symbol table to use. */ public XML11Configuration(SymbolTable symbolTable) { this(symbolTable, null, null); } // <init>(SymbolTable) /** * Constructs a parser configuration using the specified symbol table and * grammar pool. * <p> * <strong>REVISIT:</strong> * Grammar pool will be updated when the new validation engine is * implemented. * * @param symbolTable The symbol table to use. * @param grammarPool The grammar pool to use. */ public XML11Configuration(SymbolTable symbolTable, XMLGrammarPool grammarPool) { this(symbolTable, grammarPool, null); } // <init>(SymbolTable,XMLGrammarPool) /** * Constructs a parser configuration using the specified symbol table, * grammar pool, and parent settings. * <p> * <strong>REVISIT:</strong> * Grammar pool will be updated when the new validation engine is * implemented. * * @param symbolTable The symbol table to use. * @param grammarPool The grammar pool to use. * @param parentSettings The parent settings. */ public XML11Configuration( SymbolTable symbolTable, XMLGrammarPool grammarPool, XMLComponentManager parentSettings) { super(parentSettings); // create a vector to hold all the components in use // XML 1.0 specialized components fComponents = new Vector(); // XML 1.1 specialized components fXML11Components = new Vector(); // Common components for XML 1.1. and XML 1.0 fCommonComponents = new Vector(); // create storage for recognized features and properties fRecognizedFeatures = new Vector(); fRecognizedProperties = new Vector(); // create table for features and properties fFeatures = new Hashtable(); fProperties = new Hashtable(); // add default recognized features final String[] recognizedFeatures = { CONTINUE_AFTER_FATAL_ERROR, LOAD_EXTERNAL_DTD, // from XMLDTDScannerImpl VALIDATION, NAMESPACES, NORMALIZE_DATA, SCHEMA_ELEMENT_DEFAULT, SCHEMA_AUGMENT_PSVI, // NOTE: These shouldn't really be here but since the XML Schema // validator is constructed dynamically, its recognized // features might not have been set and it would cause a // not-recognized exception to be thrown. -Ac XMLSCHEMA_VALIDATION, XMLSCHEMA_FULL_CHECKING, EXTERNAL_GENERAL_ENTITIES, EXTERNAL_PARAMETER_ENTITIES, PARSER_SETTINGS }; addRecognizedFeatures(recognizedFeatures); // set state for default features fFeatures.put(VALIDATION, Boolean.FALSE); fFeatures.put(NAMESPACES, Boolean.TRUE); fFeatures.put(EXTERNAL_GENERAL_ENTITIES, Boolean.TRUE); fFeatures.put(EXTERNAL_PARAMETER_ENTITIES, Boolean.TRUE); fFeatures.put(CONTINUE_AFTER_FATAL_ERROR, Boolean.FALSE); fFeatures.put(LOAD_EXTERNAL_DTD, Boolean.TRUE); fFeatures.put(SCHEMA_ELEMENT_DEFAULT, Boolean.TRUE); fFeatures.put(NORMALIZE_DATA, Boolean.TRUE); fFeatures.put(SCHEMA_AUGMENT_PSVI, Boolean.TRUE); fFeatures.put(PARSER_SETTINGS, Boolean.TRUE); // add default recognized properties final String[] recognizedProperties = { SYMBOL_TABLE, ERROR_HANDLER, ENTITY_RESOLVER, ERROR_REPORTER, ENTITY_MANAGER, DOCUMENT_SCANNER, DTD_SCANNER, DTD_PROCESSOR, DTD_VALIDATOR, DATATYPE_VALIDATOR_FACTORY, VALIDATION_MANAGER, SCHEMA_VALIDATOR, XML_STRING, XMLGRAMMAR_POOL, JAXP_SCHEMA_SOURCE, JAXP_SCHEMA_LANGUAGE, // NOTE: These shouldn't really be here but since the XML Schema // validator is constructed dynamically, its recognized // properties might not have been set and it would cause a // not-recognized exception to be thrown. -Ac SCHEMA_LOCATION, SCHEMA_NONS_LOCATION, }; addRecognizedProperties(recognizedProperties); if (symbolTable == null) { symbolTable = new SymbolTable(); } fSymbolTable = symbolTable; fProperties.put(SYMBOL_TABLE, fSymbolTable); fGrammarPool = grammarPool; if (fGrammarPool != null) { fProperties.put(XMLGRAMMAR_POOL, fGrammarPool); } fEntityManager = new XMLEntityManager(); fProperties.put(ENTITY_MANAGER, fEntityManager); addCommonComponent(fEntityManager); fErrorReporter = new XMLErrorReporter(); fErrorReporter.setDocumentLocator(fEntityManager.getEntityScanner()); fProperties.put(ERROR_REPORTER, fErrorReporter); addCommonComponent(fErrorReporter); fNamespaceScanner = new XMLNSDocumentScannerImpl(); fProperties.put(DOCUMENT_SCANNER, fNamespaceScanner); addComponent((XMLComponent) fNamespaceScanner); fDTDScanner = new XMLDTDScannerImpl(); fProperties.put(DTD_SCANNER, fDTDScanner); addComponent((XMLComponent) fDTDScanner); fDTDProcessor = new XMLDTDProcessor(); fProperties.put(DTD_PROCESSOR, fDTDProcessor); addComponent((XMLComponent) fDTDProcessor); fDTDValidator = new XMLNSDTDValidator(); fProperties.put(DTD_VALIDATOR, fDTDValidator); addComponent(fDTDValidator); fDatatypeValidatorFactory = DTDDVFactory.getInstance(); fProperties.put(DATATYPE_VALIDATOR_FACTORY, fDatatypeValidatorFactory); fValidationManager = new ValidationManager(); fProperties.put(VALIDATION_MANAGER, fValidationManager); fVersionDetector = new XMLVersionDetector(); // add message formatters if (fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN) == null) { XMLMessageFormatter xmft = new XMLMessageFormatter(); fErrorReporter.putMessageFormatter(XMLMessageFormatter.XML_DOMAIN, xmft); fErrorReporter.putMessageFormatter(XMLMessageFormatter.XMLNS_DOMAIN, xmft); } // set locale try { setLocale(Locale.getDefault()); } catch (XNIException e) { // do nothing // REVISIT: What is the right thing to do? -Ac } fConfigUpdated = false; } // <init>(SymbolTable,XMLGrammarPool) // // Public methods // /** * Sets the input source for the document to parse. * * @param inputSource The document's input source. * * @exception XMLConfigurationException Thrown if there is a * configuration error when initializing the * parser. * @exception IOException Thrown on I/O error. * * @see #parse(boolean) */ public void setInputSource(XMLInputSource inputSource) throws XMLConfigurationException, IOException { // REVISIT: this method used to reset all the components and // construct the pipeline. Now reset() is called // in parse (boolean) just before we parse the document // Should this method still throw exceptions..? fInputSource = inputSource; } // setInputSource(XMLInputSource) /** * Set the locale to use for messages. * * @param locale The locale object to use for localization of messages. * * @exception XNIException Thrown if the parser does not support the * specified locale. */ public void setLocale(Locale locale) throws XNIException { fLocale = locale; fErrorReporter.setLocale(locale); } // setLocale(Locale) /** * Sets the document handler on the last component in the pipeline * to receive information about the document. * * @param documentHandler The document handler. */ public void setDocumentHandler(XMLDocumentHandler documentHandler) { fDocumentHandler = documentHandler; if (fLastComponent != null) { fLastComponent.setDocumentHandler(fDocumentHandler); if (fDocumentHandler !=null){ fDocumentHandler.setDocumentSource(fLastComponent); } } } // setDocumentHandler(XMLDocumentHandler) /** Returns the registered document handler. */ public XMLDocumentHandler getDocumentHandler() { return fDocumentHandler; } // getDocumentHandler():XMLDocumentHandler /** * Sets the DTD handler. * * @param dtdHandler The DTD handler. */ public void setDTDHandler(XMLDTDHandler dtdHandler) { fDTDHandler = dtdHandler; } // setDTDHandler(XMLDTDHandler) /** Returns the registered DTD handler. */ public XMLDTDHandler getDTDHandler() { return fDTDHandler; } // getDTDHandler():XMLDTDHandler /** * Sets the DTD content model handler. * * @param handler The DTD content model handler. */ public void setDTDContentModelHandler(XMLDTDContentModelHandler handler) { fDTDContentModelHandler = handler; } // setDTDContentModelHandler(XMLDTDContentModelHandler) /** Returns the registered DTD content model handler. */ public XMLDTDContentModelHandler getDTDContentModelHandler() { return fDTDContentModelHandler; } // getDTDContentModelHandler():XMLDTDContentModelHandler /** * Sets the resolver used to resolve external entities. The EntityResolver * interface supports resolution of public and system identifiers. * * @param resolver The new entity resolver. Passing a null value will * uninstall the currently installed resolver. */ public void setEntityResolver(XMLEntityResolver resolver) { fProperties.put(ENTITY_RESOLVER, resolver); } // setEntityResolver(XMLEntityResolver) /** * Return the current entity resolver. * * @return The current entity resolver, or null if none * has been registered. * @see #setEntityResolver */ public XMLEntityResolver getEntityResolver() { return (XMLEntityResolver)fProperties.get(ENTITY_RESOLVER); } // getEntityResolver():XMLEntityResolver /** * Allow an application to register an error event handler. * * <p>If the application does not register an error handler, all * error events reported by the SAX parser will be silently * ignored; however, normal processing may not continue. It is * highly recommended that all SAX applications implement an * error handler to avoid unexpected bugs.</p> * * <p>Applications may register a new or different handler in the * middle of a parse, and the SAX parser must begin using the new * handler immediately.</p> * * @param errorHandler The error handler. * @exception java.lang.NullPointerException If the handler * argument is null. * @see #getErrorHandler */ public void setErrorHandler(XMLErrorHandler errorHandler) { fProperties.put(ERROR_HANDLER, errorHandler); } // setErrorHandler(XMLErrorHandler) /** * Return the current error handler. * * @return The current error handler, or null if none * has been registered. * @see #setErrorHandler */ public XMLErrorHandler getErrorHandler() { // REVISIT: Should this be a property? return (XMLErrorHandler)fProperties.get(ERROR_HANDLER); } // getErrorHandler():XMLErrorHandler /** * If the application decides to terminate parsing before the xml document * is fully parsed, the application should call this method to free any * resource allocated during parsing. For example, close all opened streams. */ public void cleanup() { fEntityManager.closeReaders(); } /** * Parses the specified input source. * * @param source The input source. * * @exception XNIException Throws exception on XNI error. * @exception java.io.IOException Throws exception on i/o error. */ public void parse(XMLInputSource source) throws XNIException, IOException { if (fParseInProgress) { // REVISIT - need to add new error message throw new XNIException("FWK005 parse may not be called while parsing."); } fParseInProgress = true; try { setInputSource(source); parse(true); } catch (XNIException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (IOException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (RuntimeException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (Exception ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw new XNIException(ex); } finally { fParseInProgress = false; // close all streams opened by xerces this.cleanup(); } } // parse(InputSource) public boolean parse(boolean complete) throws XNIException, IOException { // // reset and configure pipeline and set InputSource. if (fInputSource != null) { try { fValidationManager.reset(); fVersionDetector.reset(this); resetCommon(); short version = fVersionDetector.determineDocVersion(fInputSource); if (version == Constants.XML_VERSION_1_1) { initXML11Components(); configureXML11Pipeline(); resetXML11(); } else { configurePipeline(); reset(); } // mark configuration as fixed fConfigUpdated = false; // resets and sets the pipeline. fVersionDetector.startDocumentParsing((XMLEntityHandler) fCurrentScanner, version); fInputSource = null; } catch (XNIException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (IOException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (RuntimeException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (Exception ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw new XNIException(ex); } } try { return fCurrentScanner.scanDocument(complete); } catch (XNIException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (IOException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (RuntimeException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (Exception ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw new XNIException(ex); } } // parse(boolean):boolean /** * Returns the state of a feature. * * @param featureId The feature identifier. * @return true if the feature is supported * * @throws XMLConfigurationException Thrown for configuration error. * In general, components should * only throw this exception if * it is <strong>really</strong> * a critical error. */ public boolean getFeature(String featureId) throws XMLConfigurationException { // make this feature special if (featureId.equals(PARSER_SETTINGS)){ return fConfigUpdated; } return super.getFeature(featureId); } // getFeature(String):boolean /** * Set the state of a feature. * * Set the state of any feature in a SAX2 parser. The parser * might not recognize the feature, and if it does recognize * it, it might not be able to fulfill the request. * * @param featureId The unique identifier (URI) of the feature. * @param state The requested state of the feature (true or false). * * @exception org.apache.xerces.xni.parser.XMLConfigurationException If the * requested feature is not known. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { fConfigUpdated = true; // forward to every XML 1.0 component int count = fComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fComponents.elementAt(i); c.setFeature(featureId, state); } // forward it to common components count = fCommonComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fCommonComponents.elementAt(i); c.setFeature(featureId, state); } // forward to every XML 1.1 component count = fXML11Components.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fXML11Components.elementAt(i); try{ c.setFeature(featureId, state); } catch (Exception e){ // no op } } // save state if noone "objects" super.setFeature(featureId, state); } // setFeature(String,boolean) /** * setProperty * * @param propertyId * @param value */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { fConfigUpdated = true; // forward to every XML 1.0 component int count = fComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fComponents.elementAt(i); c.setProperty(propertyId, value); } // forward it to every common Component count = fCommonComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fCommonComponents.elementAt(i); c.setProperty(propertyId, value); } // forward it to every XML 1.1 component count = fXML11Components.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fXML11Components.elementAt(i); try{ c.setProperty(propertyId, value); } catch (Exception e){ // ignore it } } // store value if noone "objects" super.setProperty(propertyId, value); } // setProperty(String,Object) /** Returns the locale. */ public Locale getLocale() { return fLocale; } // getLocale():Locale /** * reset all XML 1.0 components before parsing and namespace context */ protected void reset() throws XNIException { int count = fComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fComponents.elementAt(i); c.reset(this); } } // reset() /** * reset all common components before parsing */ protected void resetCommon() throws XNIException { // reset common components int count = fCommonComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fCommonComponents.elementAt(i); c.reset(this); } } // resetCommon() /** * reset all components before parsing and namespace context */ protected void resetXML11() throws XNIException { // reset every component int count = fXML11Components.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fXML11Components.elementAt(i); c.reset(this); } } // resetXML11() /** * Configures the XML 1.1 pipeline. * Note: this method also resets the new XML11 components. */ protected void configureXML11Pipeline() { if (fCurrentDVFactory != fXML11DatatypeFactory) { fCurrentDVFactory = fXML11DatatypeFactory; setProperty(DATATYPE_VALIDATOR_FACTORY, fCurrentDVFactory); } if (fCurrentDTDScanner != fXML11DTDScanner) { fCurrentDTDScanner = fXML11DTDScanner; setProperty(DTD_SCANNER, fCurrentDTDScanner); setProperty(DTD_PROCESSOR, fXML11DTDProcessor); } fXML11DTDScanner.setDTDHandler(fXML11DTDProcessor); fXML11DTDProcessor.setDTDSource(fXML11DTDScanner); fXML11DTDProcessor.setDTDHandler(fDTDHandler); if (fDTDHandler != null) { fDTDHandler.setDTDSource(fXML11DTDProcessor); } fXML11DTDScanner.setDTDContentModelHandler(fXML11DTDProcessor); fXML11DTDProcessor.setDTDContentModelSource(fXML11DTDScanner); fXML11DTDProcessor.setDTDContentModelHandler(fDTDContentModelHandler); if (fDTDContentModelHandler != null) { fDTDContentModelHandler.setDTDContentModelSource(fXML11DTDProcessor); } // setup XML 1.1 document pipeline if (fFeatures.get(NAMESPACES) == Boolean.TRUE) { if (fCurrentScanner != fXML11NSDocScanner) { fCurrentScanner = fXML11NSDocScanner; setProperty(DOCUMENT_SCANNER, fXML11NSDocScanner); setProperty(DTD_VALIDATOR, fXML11NSDTDValidator); } fXML11NSDocScanner.setDTDValidator(fXML11NSDTDValidator); fXML11NSDocScanner.setDocumentHandler(fXML11NSDTDValidator); fXML11NSDTDValidator.setDocumentSource(fXML11NSDocScanner); fXML11NSDTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fXML11NSDTDValidator); } fLastComponent = fXML11NSDTDValidator; } else { // create components if (fXML11DocScanner == null) { // non namespace document pipeline fXML11DocScanner = new XML11DocumentScannerImpl(); addXML11Component(fXML11DocScanner); fXML11DTDValidator = new XML11DTDValidator(); addXML11Component(fXML11DTDValidator); } if (fCurrentScanner != fXML11DocScanner) { fCurrentScanner = fXML11DocScanner; setProperty(DOCUMENT_SCANNER, fXML11DocScanner); setProperty(DTD_VALIDATOR, fXML11DTDValidator); } fXML11DocScanner.setDocumentHandler(fXML11DTDValidator); fXML11DTDValidator.setDocumentSource(fXML11DocScanner); fXML11DTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fXML11DTDValidator); } fLastComponent = fXML11DTDValidator; } // setup document pipeline if (fFeatures.get(XMLSCHEMA_VALIDATION) == Boolean.TRUE) { // If schema validator was not in the pipeline insert it. if (fSchemaValidator == null) { fSchemaValidator = new XMLSchemaValidator(); // add schema component setProperty(SCHEMA_VALIDATOR, fSchemaValidator); addCommonComponent(fSchemaValidator); fSchemaValidator.reset(this); // add schema message formatter if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) { XSMessageFormatter xmft = new XSMessageFormatter(); fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, xmft); } } fLastComponent.setDocumentHandler(fSchemaValidator); fSchemaValidator.setDocumentSource(fLastComponent); fSchemaValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fSchemaValidator); } fLastComponent = fSchemaValidator; } } // configureXML11Pipeline() /** Configures the pipeline. */ protected void configurePipeline() { if (fCurrentDVFactory != fDatatypeValidatorFactory) { fCurrentDVFactory = fDatatypeValidatorFactory; // use XML 1.0 datatype library setProperty(DATATYPE_VALIDATOR_FACTORY, fCurrentDVFactory); } // setup DTD pipeline if (fCurrentDTDScanner != fDTDScanner) { fCurrentDTDScanner = fDTDScanner; setProperty(DTD_SCANNER, fCurrentDTDScanner); setProperty(DTD_PROCESSOR, fDTDProcessor); } fDTDScanner.setDTDHandler(fDTDProcessor); fDTDProcessor.setDTDSource(fDTDScanner); fDTDProcessor.setDTDHandler(fDTDHandler); if (fDTDHandler != null) { fDTDHandler.setDTDSource(fDTDProcessor); } fDTDScanner.setDTDContentModelHandler(fDTDProcessor); fDTDProcessor.setDTDContentModelSource(fDTDScanner); fDTDProcessor.setDTDContentModelHandler(fDTDContentModelHandler); if (fDTDContentModelHandler != null) { fDTDContentModelHandler.setDTDContentModelSource(fDTDProcessor); } // setup document pipeline if (fFeatures.get(NAMESPACES) == Boolean.TRUE) { if (fCurrentScanner != fNamespaceScanner) { fCurrentScanner = fNamespaceScanner; setProperty(DOCUMENT_SCANNER, fNamespaceScanner); setProperty(DTD_VALIDATOR, fDTDValidator); } fNamespaceScanner.setDTDValidator(fDTDValidator); fNamespaceScanner.setDocumentHandler(fDTDValidator); fDTDValidator.setDocumentSource(fNamespaceScanner); fDTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fDTDValidator); } fLastComponent = fDTDValidator; } else { // create components if (fNonNSScanner == null) { fNonNSScanner = new XMLDocumentScannerImpl(); fNonNSDTDValidator = new XMLDTDValidator(); // add components addComponent((XMLComponent) fNonNSScanner); addComponent((XMLComponent) fNonNSDTDValidator); } if (fCurrentScanner != fNonNSScanner) { fCurrentScanner = fNonNSScanner; setProperty(DOCUMENT_SCANNER, fNonNSScanner); setProperty(DTD_VALIDATOR, fNonNSDTDValidator); } fNonNSScanner.setDocumentHandler(fNonNSDTDValidator); fNonNSDTDValidator.setDocumentSource(fNonNSScanner); fNonNSDTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fNonNSDTDValidator); } fLastComponent = fNonNSDTDValidator; } // add XML Schema validator if needed if (fFeatures.get(XMLSCHEMA_VALIDATION) == Boolean.TRUE) { // If schema validator was not in the pipeline insert it. if (fSchemaValidator == null) { fSchemaValidator = new XMLSchemaValidator(); // add schema component setProperty(SCHEMA_VALIDATOR, fSchemaValidator); addCommonComponent(fSchemaValidator); fSchemaValidator.reset(this); // add schema message formatter if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) { XSMessageFormatter xmft = new XSMessageFormatter(); fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, xmft); } } fLastComponent.setDocumentHandler(fSchemaValidator); fSchemaValidator.setDocumentSource(fLastComponent); fSchemaValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fSchemaValidator); } fLastComponent = fSchemaValidator; } } // configurePipeline() // features and properties /** * Check a feature. If feature is know and supported, this method simply * returns. Otherwise, the appropriate exception is thrown. * * @param featureId The unique identifier (URI) of the feature. * * @throws XMLConfigurationException Thrown for configuration error. * In general, components should * only throw this exception if * it is <strong>really</strong> * a critical error. */ protected void checkFeature(String featureId) throws XMLConfigurationException { // // Xerces Features // if (featureId.startsWith(Constants.XERCES_FEATURE_PREFIX)) { String feature = featureId.substring(Constants.XERCES_FEATURE_PREFIX.length()); // // http://apache.org/xml/features/validation/dynamic // Allows the parser to validate a document only when it // contains a grammar. Validation is turned on/off based // on each document instance, automatically. // if (feature.equals(Constants.DYNAMIC_VALIDATION_FEATURE)) { return; } // // http://apache.org/xml/features/validation/default-attribute-values // if (feature.equals(Constants.DEFAULT_ATTRIBUTE_VALUES_FEATURE)) { // REVISIT short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, featureId); } // // http://apache.org/xml/features/validation/default-attribute-values // if (feature.equals(Constants.VALIDATE_CONTENT_MODELS_FEATURE)) { // REVISIT short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, featureId); } // // http://apache.org/xml/features/validation/nonvalidating/load-dtd-grammar // if (feature.equals(Constants.LOAD_DTD_GRAMMAR_FEATURE)) { return; } // // http://apache.org/xml/features/validation/nonvalidating/load-external-dtd // if (feature.equals(Constants.LOAD_EXTERNAL_DTD_FEATURE)) { return; } // // http://apache.org/xml/features/validation/default-attribute-values // if (feature.equals(Constants.VALIDATE_DATATYPES_FEATURE)) { short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, featureId); } // // http://apache.org/xml/features/validation/schema // Lets the user turn Schema validation support on/off. // if (feature.equals(Constants.SCHEMA_VALIDATION_FEATURE)) { return; } // activate full schema checking if (feature.equals(Constants.SCHEMA_FULL_CHECKING)) { return; } // Feature identifier: expose schema normalized value // http://apache.org/xml/features/validation/schema/normalized-value if(feature.equals(Constants.SCHEMA_NORMALIZED_VALUE)) { return; } // Feature identifier: send element default value via characters() // http://apache.org/xml/features/validation/schema/element-default if(feature.equals(Constants.SCHEMA_ELEMENT_DEFAULT)) { return; } // special performance feature: only component manager is allowed to set it. if (feature.equals(Constants.PARSER_SETTINGS)) { short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, featureId); } } // // Not recognized // super.checkFeature(featureId); } // checkFeature(String) /** * Check a property. If the property is know and supported, this method * simply returns. Otherwise, the appropriate exception is thrown. * * @param propertyId The unique identifier (URI) of the property * being set. * * @throws XMLConfigurationException Thrown for configuration error. * In general, components should * only throw this exception if * it is <strong>really</strong> * a critical error. */ protected void checkProperty(String propertyId) throws XMLConfigurationException { // // Xerces Properties // if (propertyId.startsWith(Constants.XERCES_PROPERTY_PREFIX)) { String property = propertyId.substring(Constants.XERCES_PROPERTY_PREFIX.length()); if (property.equals(Constants.DTD_SCANNER_PROPERTY)) { return; } if (property.equals(Constants.SCHEMA_LOCATION)) { return; } if (property.equals(Constants.SCHEMA_NONS_LOCATION)) { return; } } if (propertyId.startsWith(Constants.JAXP_PROPERTY_PREFIX)) { String property = propertyId.substring(Constants.JAXP_PROPERTY_PREFIX.length()); if (property.equals(Constants.SCHEMA_SOURCE)) { return; } } // special cases if (propertyId.startsWith(Constants.SAX_PROPERTY_PREFIX)) { String property = propertyId.substring(Constants.SAX_PROPERTY_PREFIX.length()); // // http://xml.org/sax/properties/xml-string // Value type: String // Access: read-only // Get the literal string of characters associated with the // current event. If the parser recognises and supports this // property but is not currently parsing text, it should return // null (this is a good way to check for availability before the // parse begins). // if (property.equals(Constants.XML_STRING_PROPERTY)) { // REVISIT - we should probably ask xml-dev for a precise // definition of what this is actually supposed to return, and // in exactly which circumstances. short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, propertyId); } } // // Not recognized // super.checkProperty(propertyId); } // checkProperty(String) /** * Adds a component to the parser configuration. This method will * also add all of the component's recognized features and properties * to the list of default recognized features and properties. * * @param component The component to add. */ protected void addComponent(XMLComponent component) { // don't add a component more than once if (fComponents.contains(component)) { return; } fComponents.addElement(component); // register component's recognized features String[] recognizedFeatures = component.getRecognizedFeatures(); addRecognizedFeatures(recognizedFeatures); // register component's recognized properties String[] recognizedProperties = component.getRecognizedProperties(); addRecognizedProperties(recognizedProperties); // set default values if (recognizedFeatures != null) { for (int i = 0; i < recognizedFeatures.length; i++) { String featureId = recognizedFeatures[i]; Boolean state = component.getFeatureDefault(featureId); if (state != null) { super.setFeature(featureId, state.booleanValue()); } } } if (recognizedProperties != null) { for (int i = 0; i < recognizedProperties.length; i++) { String propertyId = recognizedProperties[i]; Object value = component.getPropertyDefault(propertyId); if (value != null) { super.setProperty(propertyId, value); } } } } // addComponent(XMLComponent) /** * Adds common component to the parser configuration. This method will * also add all of the component's recognized features and properties * to the list of default recognized features and properties. * * @param component The component to add. */ protected void addCommonComponent(XMLComponent component) { // don't add a component more than once if (fCommonComponents.contains(component)) { return; } fCommonComponents.addElement(component); // register component's recognized features String[] recognizedFeatures = component.getRecognizedFeatures(); addRecognizedFeatures(recognizedFeatures); // register component's recognized properties String[] recognizedProperties = component.getRecognizedProperties(); addRecognizedProperties(recognizedProperties); // set default values if (recognizedFeatures != null) { for (int i = 0; i < recognizedFeatures.length; i++) { String featureId = recognizedFeatures[i]; Boolean state = component.getFeatureDefault(featureId); if (state != null) { super.setFeature(featureId, state.booleanValue()); } } } if (recognizedProperties != null) { for (int i = 0; i < recognizedProperties.length; i++) { String propertyId = recognizedProperties[i]; Object value = component.getPropertyDefault(propertyId); if (value != null) { super.setProperty(propertyId, value); } } } } // addCommonComponent(XMLComponent) /** * Adds an XML 1.1 component to the parser configuration. This method will * also add all of the component's recognized features and properties * to the list of default recognized features and properties. * * @param component The component to add. */ protected void addXML11Component(XMLComponent component) { // don't add a component more than once if (fXML11Components.contains(component)) { return; } fXML11Components.addElement(component); // register component's recognized features String[] recognizedFeatures = component.getRecognizedFeatures(); addRecognizedFeatures(recognizedFeatures); // register component's recognized properties String[] recognizedProperties = component.getRecognizedProperties(); addRecognizedProperties(recognizedProperties); // set default values if (recognizedFeatures != null) { for (int i = 0; i < recognizedFeatures.length; i++) { String featureId = recognizedFeatures[i]; Boolean state = component.getFeatureDefault(featureId); if (state != null) { checkFeature(featureId); fFeatures.put(featureId, state); } } } if (recognizedProperties != null) { for (int i = 0; i < recognizedProperties.length; i++) { String propertyId = recognizedProperties[i]; Object value = component.getPropertyDefault(propertyId); if (value != null) { checkProperty(propertyId); fProperties.put(propertyId, value); } } } } // addXML11Component(XMLComponent) private void initXML11Components() { if (!fInitalized) { // create datatype factory fXML11DatatypeFactory = DTDDVFactory.getInstance(XML11_DATATYPE_VALIDATOR_FACTORY); // setup XML 1.1 DTD pipeline fXML11DTDScanner = new XML11DTDScannerImpl(); addXML11Component(fXML11DTDScanner); fXML11DTDProcessor = new XML11DTDProcessor(); addXML11Component(fXML11DTDProcessor); // setup XML 1.1. document pipeline - namespace aware fXML11NSDocScanner = new XML11NSDocumentScannerImpl(); addXML11Component(fXML11NSDocScanner); fXML11NSDTDValidator = new XML11NSDTDValidator(); addXML11Component(fXML11NSDTDValidator); if (fSchemaValidator != null) addXML11Component(fSchemaValidator); } } } // class XML11Configuration
src/org/apache/xerces/parsers/XML11Configuration.java
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001-2003 The Apache Software Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2002, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.parsers; import java.io.IOException; import java.util.Hashtable; import java.util.Locale; import java.util.Vector; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.XML11DTDScannerImpl; import org.apache.xerces.impl.XML11DocumentScannerImpl; import org.apache.xerces.impl.XML11NSDocumentScannerImpl; import org.apache.xerces.impl.XMLDTDScannerImpl; import org.apache.xerces.impl.XMLDocumentScannerImpl; import org.apache.xerces.impl.XMLEntityHandler; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.XMLNSDocumentScannerImpl; import org.apache.xerces.impl.XMLVersionDetector; import org.apache.xerces.impl.dtd.XML11DTDProcessor; import org.apache.xerces.impl.dtd.XML11DTDValidator; import org.apache.xerces.impl.dtd.XML11NSDTDValidator; import org.apache.xerces.impl.dtd.XMLDTDProcessor; import org.apache.xerces.impl.dtd.XMLDTDValidator; import org.apache.xerces.impl.dtd.XMLNSDTDValidator; import org.apache.xerces.impl.dv.DTDDVFactory; import org.apache.xerces.impl.msg.XMLMessageFormatter; import org.apache.xerces.impl.validation.ValidationManager; import org.apache.xerces.impl.xs.XMLSchemaValidator; import org.apache.xerces.impl.xs.XSMessageFormatter; import org.apache.xerces.util.ParserConfigurationSettings; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.xni.XMLDTDContentModelHandler; import org.apache.xerces.xni.XMLDTDHandler; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDTDScanner; import org.apache.xerces.xni.parser.XMLDocumentScanner; import org.apache.xerces.xni.parser.XMLDocumentSource; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLErrorHandler; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.parser.XMLPullParserConfiguration; /** * This class is the configuration used to parse XML 1.0 and XML 1.1 documents. * This is the default Xerces configuration. * * @author Elena Litani, IBM * @author Neil Graham, IBM * @author Michael Glavassevich, IBM * * @version $Id$ */ public class XML11Configuration extends ParserConfigurationSettings implements XMLPullParserConfiguration { // // Constants // protected final static String XML11_DATATYPE_VALIDATOR_FACTORY = "org.apache.xerces.impl.dv.dtd.XML11DTDDVFactoryImpl"; // feature identifiers /** Feature identifier: warn on duplicate attribute definition. */ protected static final String WARN_ON_DUPLICATE_ATTDEF = Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ATTDEF_FEATURE; /** Feature identifier: warn on duplicate entity definition. */ protected static final String WARN_ON_DUPLICATE_ENTITYDEF = Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ENTITYDEF_FEATURE; /** Feature identifier: warn on undeclared element definition. */ protected static final String WARN_ON_UNDECLARED_ELEMDEF = Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_UNDECLARED_ELEMDEF_FEATURE; /** Feature identifier: allow Java encodings. */ protected static final String ALLOW_JAVA_ENCODINGS = Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE; /** Feature identifier: continue after fatal error. */ protected static final String CONTINUE_AFTER_FATAL_ERROR = Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE; /** Feature identifier: load external DTD. */ protected static final String LOAD_EXTERNAL_DTD = Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE; /** Feature identifier: notify built-in refereces. */ protected static final String NOTIFY_BUILTIN_REFS = Constants.XERCES_FEATURE_PREFIX + Constants.NOTIFY_BUILTIN_REFS_FEATURE; /** Feature identifier: notify character refereces. */ protected static final String NOTIFY_CHAR_REFS = Constants.XERCES_FEATURE_PREFIX + Constants.NOTIFY_CHAR_REFS_FEATURE; /** Feature identifier: expose schema normalized value */ protected static final String NORMALIZE_DATA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE; /** Feature identifier: send element default value via characters() */ protected static final String SCHEMA_ELEMENT_DEFAULT = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT; /** Feature identifier: augment PSVI */ protected static final String SCHEMA_AUGMENT_PSVI = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_AUGMENT_PSVI; /** feature identifier: XML Schema validation */ protected static final String XMLSCHEMA_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** feature identifier: XML Schema validation -- full checking */ protected static final String XMLSCHEMA_FULL_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING; // feature identifiers /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE; /** Feature identifier: namespaces. */ protected static final String NAMESPACES = Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE; /** Feature identifier: external general entities. */ protected static final String EXTERNAL_GENERAL_ENTITIES = Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_GENERAL_ENTITIES_FEATURE; /** Feature identifier: external parameter entities. */ protected static final String EXTERNAL_PARAMETER_ENTITIES = Constants.SAX_FEATURE_PREFIX + Constants.EXTERNAL_PARAMETER_ENTITIES_FEATURE; // property identifiers /** Property identifier: xml string. */ protected static final String XML_STRING = Constants.SAX_PROPERTY_PREFIX + Constants.XML_STRING_PROPERTY; /** Property identifier: symbol table. */ protected static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error handler. */ protected static final String ERROR_HANDLER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; /** Property identifier: entity resolver. */ protected static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** Property identifier: XML Schema validator. */ protected static final String SCHEMA_VALIDATOR = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY; /** Property identifier: schema location. */ protected static final String SCHEMA_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION; /** Property identifier: no namespace schema location. */ protected static final String SCHEMA_NONS_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION; // property identifiers /** Property identifier: error reporter. */ protected static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: entity manager. */ protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; /** Property identifier document scanner: */ protected static final String DOCUMENT_SCANNER = Constants.XERCES_PROPERTY_PREFIX + Constants.DOCUMENT_SCANNER_PROPERTY; /** Property identifier: DTD scanner. */ protected static final String DTD_SCANNER = Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_SCANNER_PROPERTY; /** Property identifier: grammar pool. */ protected static final String XMLGRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; /** Property identifier: DTD loader. */ protected static final String DTD_PROCESSOR = Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_PROCESSOR_PROPERTY; /** Property identifier: DTD validator. */ protected static final String DTD_VALIDATOR = Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_VALIDATOR_PROPERTY; /** Property identifier: namespace binder. */ protected static final String NAMESPACE_BINDER = Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_BINDER_PROPERTY; /** Property identifier: datatype validator factory. */ protected static final String DATATYPE_VALIDATOR_FACTORY = Constants.XERCES_PROPERTY_PREFIX + Constants.DATATYPE_VALIDATOR_FACTORY_PROPERTY; protected static final String VALIDATION_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; /** Property identifier: JAXP schema language / DOM schema-type. */ protected static final String JAXP_SCHEMA_LANGUAGE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE; /** Property identifier: JAXP schema source/ DOM schema-location. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; // debugging /** Set to true and recompile to print exception stack trace. */ protected static final boolean PRINT_EXCEPTION_STACK_TRACE = false; // // Data // protected SymbolTable fSymbolTable; protected XMLInputSource fInputSource; protected ValidationManager fValidationManager; protected XMLVersionDetector fVersionDetector; protected XMLLocator fLocator; protected Locale fLocale; /** XML 1.0 Components. */ protected Vector fComponents; /** XML 1.1. Components. */ protected Vector fXML11Components = null; /** Common components: XMLEntityManager, XMLErrorReporter, XMLSchemaValidator */ protected Vector fCommonComponents = null; /** The document handler. */ protected XMLDocumentHandler fDocumentHandler; /** The DTD handler. */ protected XMLDTDHandler fDTDHandler; /** The DTD content model handler. */ protected XMLDTDContentModelHandler fDTDContentModelHandler; /** Last component in the document pipeline */ protected XMLDocumentSource fLastComponent; /** * True if a parse is in progress. This state is needed because * some features/properties cannot be set while parsing (e.g. * validation and namespaces). */ protected boolean fParseInProgress = false; /** fConfigUpdated is set to true if there has been any change to the configuration settings, * i.e a feature or a property was changed. */ protected boolean fConfigUpdated = false; // // XML 1.0 components // /** The XML 1.0 Datatype validator factory. */ protected DTDDVFactory fDatatypeValidatorFactory; /** The XML 1.0 Document scanner that does namespace binding. */ protected XMLNSDocumentScannerImpl fNamespaceScanner; /** The XML 1.0 Non-namespace implementation of scanner */ protected XMLDocumentScannerImpl fNonNSScanner; /** The XML 1.0 DTD Validator: binds namespaces */ protected XMLDTDValidator fDTDValidator; /** The XML 1.0 DTD Validator that does not bind namespaces */ protected XMLDTDValidator fNonNSDTDValidator; /** The XML 1.0 DTD scanner. */ protected XMLDTDScanner fDTDScanner; /** The XML 1.0 DTD Processor . */ protected XMLDTDProcessor fDTDProcessor; // // XML 1.1 components // /** The XML 1.1 datatype factory. **/ protected DTDDVFactory fXML11DatatypeFactory = null; /** The XML 1.1 document scanner that does namespace binding. **/ protected XML11NSDocumentScannerImpl fXML11NSDocScanner = null; /** The XML 1.1 document scanner that does not do namespace binding. **/ protected XML11DocumentScannerImpl fXML11DocScanner = null; /** The XML 1.1 DTD validator that does namespace binding. **/ protected XML11NSDTDValidator fXML11NSDTDValidator = null; /** The XML 1.1 DTD validator that does not do namespace binding. **/ protected XML11DTDValidator fXML11DTDValidator = null; /** The XML 1.1 DTD scanner. **/ protected XML11DTDScannerImpl fXML11DTDScanner = null; /** The XML 1.1 DTD processor. **/ protected XML11DTDProcessor fXML11DTDProcessor = null; // // Common components // /** Grammar pool. */ protected XMLGrammarPool fGrammarPool; /** Error reporter. */ protected XMLErrorReporter fErrorReporter; /** Entity manager. */ protected XMLEntityManager fEntityManager; /** XML Schema Validator. */ protected XMLSchemaValidator fSchemaValidator; /** Current scanner */ protected XMLDocumentScanner fCurrentScanner; /** Current Datatype validator factory. */ protected DTDDVFactory fCurrentDVFactory; /** Current DTD scanner. */ protected XMLDTDScanner fCurrentDTDScanner; private boolean fInitalized = false; // // Constructors // /** Default constructor. */ public XML11Configuration() { this(null, null, null); } // <init>() /** * Constructs a parser configuration using the specified symbol table. * * @param symbolTable The symbol table to use. */ public XML11Configuration(SymbolTable symbolTable) { this(symbolTable, null, null); } // <init>(SymbolTable) /** * Constructs a parser configuration using the specified symbol table and * grammar pool. * <p> * <strong>REVISIT:</strong> * Grammar pool will be updated when the new validation engine is * implemented. * * @param symbolTable The symbol table to use. * @param grammarPool The grammar pool to use. */ public XML11Configuration(SymbolTable symbolTable, XMLGrammarPool grammarPool) { this(symbolTable, grammarPool, null); } // <init>(SymbolTable,XMLGrammarPool) /** * Constructs a parser configuration using the specified symbol table, * grammar pool, and parent settings. * <p> * <strong>REVISIT:</strong> * Grammar pool will be updated when the new validation engine is * implemented. * * @param symbolTable The symbol table to use. * @param grammarPool The grammar pool to use. * @param parentSettings The parent settings. */ public XML11Configuration( SymbolTable symbolTable, XMLGrammarPool grammarPool, XMLComponentManager parentSettings) { super(parentSettings); // create a vector to hold all the components in use // XML 1.0 specialized components fComponents = new Vector(); // XML 1.1 specialized components fXML11Components = new Vector(); // Common components for XML 1.1. and XML 1.0 fCommonComponents = new Vector(); // create storage for recognized features and properties fRecognizedFeatures = new Vector(); fRecognizedProperties = new Vector(); // create table for features and properties fFeatures = new Hashtable(); fProperties = new Hashtable(); // add default recognized features final String[] recognizedFeatures = { CONTINUE_AFTER_FATAL_ERROR, LOAD_EXTERNAL_DTD, // from XMLDTDScannerImpl VALIDATION, NAMESPACES, NORMALIZE_DATA, SCHEMA_ELEMENT_DEFAULT, SCHEMA_AUGMENT_PSVI, // NOTE: These shouldn't really be here but since the XML Schema // validator is constructed dynamically, its recognized // features might not have been set and it would cause a // not-recognized exception to be thrown. -Ac XMLSCHEMA_VALIDATION, XMLSCHEMA_FULL_CHECKING, EXTERNAL_GENERAL_ENTITIES, EXTERNAL_PARAMETER_ENTITIES, PARSER_SETTINGS }; addRecognizedFeatures(recognizedFeatures); // set state for default features fFeatures.put(VALIDATION, Boolean.FALSE); fFeatures.put(NAMESPACES, Boolean.TRUE); fFeatures.put(EXTERNAL_GENERAL_ENTITIES, Boolean.TRUE); fFeatures.put(EXTERNAL_PARAMETER_ENTITIES, Boolean.TRUE); fFeatures.put(CONTINUE_AFTER_FATAL_ERROR, Boolean.FALSE); fFeatures.put(LOAD_EXTERNAL_DTD, Boolean.TRUE); fFeatures.put(SCHEMA_ELEMENT_DEFAULT, Boolean.TRUE); fFeatures.put(NORMALIZE_DATA, Boolean.TRUE); fFeatures.put(SCHEMA_AUGMENT_PSVI, Boolean.TRUE); fFeatures.put(PARSER_SETTINGS, Boolean.TRUE); // add default recognized properties final String[] recognizedProperties = { SYMBOL_TABLE, ERROR_HANDLER, ENTITY_RESOLVER, ERROR_REPORTER, ENTITY_MANAGER, DOCUMENT_SCANNER, DTD_SCANNER, DTD_PROCESSOR, DTD_VALIDATOR, DATATYPE_VALIDATOR_FACTORY, VALIDATION_MANAGER, SCHEMA_VALIDATOR, XML_STRING, XMLGRAMMAR_POOL, JAXP_SCHEMA_SOURCE, JAXP_SCHEMA_LANGUAGE, // NOTE: These shouldn't really be here but since the XML Schema // validator is constructed dynamically, its recognized // properties might not have been set and it would cause a // not-recognized exception to be thrown. -Ac SCHEMA_LOCATION, SCHEMA_NONS_LOCATION, }; addRecognizedProperties(recognizedProperties); if (symbolTable == null) { symbolTable = new SymbolTable(); } fSymbolTable = symbolTable; fProperties.put(SYMBOL_TABLE, fSymbolTable); fGrammarPool = grammarPool; if (fGrammarPool != null) { fProperties.put(XMLGRAMMAR_POOL, fGrammarPool); } fEntityManager = new XMLEntityManager(); fProperties.put(ENTITY_MANAGER, fEntityManager); addCommonComponent(fEntityManager); fErrorReporter = new XMLErrorReporter(); fErrorReporter.setDocumentLocator(fEntityManager.getEntityScanner()); fProperties.put(ERROR_REPORTER, fErrorReporter); addCommonComponent(fErrorReporter); fNamespaceScanner = new XMLNSDocumentScannerImpl(); fProperties.put(DOCUMENT_SCANNER, fNamespaceScanner); addComponent((XMLComponent) fNamespaceScanner); fDTDScanner = new XMLDTDScannerImpl(); fProperties.put(DTD_SCANNER, fDTDScanner); addComponent((XMLComponent) fDTDScanner); fDTDProcessor = new XMLDTDProcessor(); fProperties.put(DTD_PROCESSOR, fDTDProcessor); addComponent((XMLComponent) fDTDProcessor); fDTDValidator = new XMLNSDTDValidator(); fProperties.put(DTD_VALIDATOR, fDTDValidator); addComponent(fDTDValidator); fDatatypeValidatorFactory = DTDDVFactory.getInstance(); fProperties.put(DATATYPE_VALIDATOR_FACTORY, fDatatypeValidatorFactory); fValidationManager = new ValidationManager(); fProperties.put(VALIDATION_MANAGER, fValidationManager); fVersionDetector = new XMLVersionDetector(); // add message formatters if (fErrorReporter.getMessageFormatter(XMLMessageFormatter.XML_DOMAIN) == null) { XMLMessageFormatter xmft = new XMLMessageFormatter(); fErrorReporter.putMessageFormatter(XMLMessageFormatter.XML_DOMAIN, xmft); fErrorReporter.putMessageFormatter(XMLMessageFormatter.XMLNS_DOMAIN, xmft); } // set locale try { setLocale(Locale.getDefault()); } catch (XNIException e) { // do nothing // REVISIT: What is the right thing to do? -Ac } fConfigUpdated = false; } // <init>(SymbolTable,XMLGrammarPool) // // Public methods // /** * Sets the input source for the document to parse. * * @param inputSource The document's input source. * * @exception XMLConfigurationException Thrown if there is a * configuration error when initializing the * parser. * @exception IOException Thrown on I/O error. * * @see #parse(boolean) */ public void setInputSource(XMLInputSource inputSource) throws XMLConfigurationException, IOException { // REVISIT: this method used to reset all the components and // construct the pipeline. Now reset() is called // in parse (boolean) just before we parse the document // Should this method still throw exceptions..? fInputSource = inputSource; } // setInputSource(XMLInputSource) /** * Set the locale to use for messages. * * @param locale The locale object to use for localization of messages. * * @exception XNIException Thrown if the parser does not support the * specified locale. */ public void setLocale(Locale locale) throws XNIException { fLocale = locale; fErrorReporter.setLocale(locale); } // setLocale(Locale) /** * Sets the document handler on the last component in the pipeline * to receive information about the document. * * @param documentHandler The document handler. */ public void setDocumentHandler(XMLDocumentHandler documentHandler) { fDocumentHandler = documentHandler; if (fLastComponent != null) { fLastComponent.setDocumentHandler(fDocumentHandler); if (fDocumentHandler !=null){ fDocumentHandler.setDocumentSource(fLastComponent); } } } // setDocumentHandler(XMLDocumentHandler) /** Returns the registered document handler. */ public XMLDocumentHandler getDocumentHandler() { return fDocumentHandler; } // getDocumentHandler():XMLDocumentHandler /** * Sets the DTD handler. * * @param dtdHandler The DTD handler. */ public void setDTDHandler(XMLDTDHandler dtdHandler) { fDTDHandler = dtdHandler; } // setDTDHandler(XMLDTDHandler) /** Returns the registered DTD handler. */ public XMLDTDHandler getDTDHandler() { return fDTDHandler; } // getDTDHandler():XMLDTDHandler /** * Sets the DTD content model handler. * * @param handler The DTD content model handler. */ public void setDTDContentModelHandler(XMLDTDContentModelHandler handler) { fDTDContentModelHandler = handler; } // setDTDContentModelHandler(XMLDTDContentModelHandler) /** Returns the registered DTD content model handler. */ public XMLDTDContentModelHandler getDTDContentModelHandler() { return fDTDContentModelHandler; } // getDTDContentModelHandler():XMLDTDContentModelHandler /** * Sets the resolver used to resolve external entities. The EntityResolver * interface supports resolution of public and system identifiers. * * @param resolver The new entity resolver. Passing a null value will * uninstall the currently installed resolver. */ public void setEntityResolver(XMLEntityResolver resolver) { fProperties.put(ENTITY_RESOLVER, resolver); } // setEntityResolver(XMLEntityResolver) /** * Return the current entity resolver. * * @return The current entity resolver, or null if none * has been registered. * @see #setEntityResolver */ public XMLEntityResolver getEntityResolver() { return (XMLEntityResolver)fProperties.get(ENTITY_RESOLVER); } // getEntityResolver():XMLEntityResolver /** * Allow an application to register an error event handler. * * <p>If the application does not register an error handler, all * error events reported by the SAX parser will be silently * ignored; however, normal processing may not continue. It is * highly recommended that all SAX applications implement an * error handler to avoid unexpected bugs.</p> * * <p>Applications may register a new or different handler in the * middle of a parse, and the SAX parser must begin using the new * handler immediately.</p> * * @param errorHandler The error handler. * @exception java.lang.NullPointerException If the handler * argument is null. * @see #getErrorHandler */ public void setErrorHandler(XMLErrorHandler errorHandler) { fProperties.put(ERROR_HANDLER, errorHandler); } // setErrorHandler(XMLErrorHandler) /** * Return the current error handler. * * @return The current error handler, or null if none * has been registered. * @see #setErrorHandler */ public XMLErrorHandler getErrorHandler() { // REVISIT: Should this be a property? return (XMLErrorHandler)fProperties.get(ERROR_HANDLER); } // getErrorHandler():XMLErrorHandler /** * If the application decides to terminate parsing before the xml document * is fully parsed, the application should call this method to free any * resource allocated during parsing. For example, close all opened streams. */ public void cleanup() { fEntityManager.closeReaders(); } /** * Parses the specified input source. * * @param source The input source. * * @exception XNIException Throws exception on XNI error. * @exception java.io.IOException Throws exception on i/o error. */ public void parse(XMLInputSource source) throws XNIException, IOException { if (fParseInProgress) { // REVISIT - need to add new error message throw new XNIException("FWK005 parse may not be called while parsing."); } fParseInProgress = true; try { setInputSource(source); parse(true); } catch (XNIException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (IOException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (RuntimeException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (Exception ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw new XNIException(ex); } finally { fParseInProgress = false; // close all streams opened by xerces this.cleanup(); } } // parse(InputSource) public boolean parse(boolean complete) throws XNIException, IOException { // // reset and configure pipeline and set InputSource. if (fInputSource != null) { try { fValidationManager.reset(); fVersionDetector.reset(this); resetCommon(); short version = fVersionDetector.determineDocVersion(fInputSource); if (version == Constants.XML_VERSION_1_1) { initXML11Components(); configureXML11Pipeline(); resetXML11(); } else { configurePipeline(); reset(); } // mark configuration as fixed fConfigUpdated = false; // resets and sets the pipeline. fVersionDetector.startDocumentParsing((XMLEntityHandler) fCurrentScanner, version); fInputSource = null; } catch (XNIException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (IOException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (RuntimeException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (Exception ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw new XNIException(ex); } } try { return fCurrentScanner.scanDocument(complete); } catch (XNIException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (IOException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (RuntimeException ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw ex; } catch (Exception ex) { if (PRINT_EXCEPTION_STACK_TRACE) ex.printStackTrace(); throw new XNIException(ex); } } // parse(boolean):boolean /** * Returns the state of a feature. * * @param featureId The feature identifier. * @return true if the feature is supported * * @throws XMLConfigurationException Thrown for configuration error. * In general, components should * only throw this exception if * it is <strong>really</strong> * a critical error. */ public boolean getFeature(String featureId) throws XMLConfigurationException { // make this feature special if (featureId.equals(PARSER_SETTINGS)){ return fConfigUpdated; } return super.getFeature(featureId); } // getFeature(String):boolean /** * Set the state of a feature. * * Set the state of any feature in a SAX2 parser. The parser * might not recognize the feature, and if it does recognize * it, it might not be able to fulfill the request. * * @param featureId The unique identifier (URI) of the feature. * @param state The requested state of the feature (true or false). * * @exception org.apache.xerces.xni.parser.XMLConfigurationException If the * requested feature is not known. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { fConfigUpdated = true; // forward to every XML 1.0 component int count = fComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fComponents.elementAt(i); c.setFeature(featureId, state); } // forward it to common components count = fCommonComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fCommonComponents.elementAt(i); c.setFeature(featureId, state); } // forward to every XML 1.1 component count = fXML11Components.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fXML11Components.elementAt(i); try{ c.setFeature(featureId, state); } catch (Exception e){ // no op } } // save state if noone "objects" super.setFeature(featureId, state); } // setFeature(String,boolean) /** * setProperty * * @param propertyId * @param value */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { fConfigUpdated = true; // forward to every XML 1.0 component int count = fComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fComponents.elementAt(i); c.setProperty(propertyId, value); } // forward it to every common Component count = fCommonComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fCommonComponents.elementAt(i); c.setProperty(propertyId, value); } // forward it to every XML 1.1 component count = fXML11Components.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fXML11Components.elementAt(i); try{ c.setProperty(propertyId, value); } catch (Exception e){ // ignore it } } // store value if noone "objects" super.setProperty(propertyId, value); } // setProperty(String,Object) /** Returns the locale. */ public Locale getLocale() { return fLocale; } // getLocale():Locale /** * reset all XML 1.0 components before parsing and namespace context */ protected void reset() throws XNIException { int count = fComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fComponents.elementAt(i); c.reset(this); } } // reset() /** * reset all common components before parsing */ protected void resetCommon() throws XNIException { // reset common components int count = fCommonComponents.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fCommonComponents.elementAt(i); c.reset(this); } } // resetCommon() /** * reset all components before parsing and namespace context */ protected void resetXML11() throws XNIException { // reset every component int count = fXML11Components.size(); for (int i = 0; i < count; i++) { XMLComponent c = (XMLComponent) fXML11Components.elementAt(i); c.reset(this); } } // resetXML11() /** * Configures the XML 1.1 pipeline. * Note: this method also resets the new XML11 components. */ protected void configureXML11Pipeline() { if (fCurrentDVFactory != fXML11DatatypeFactory) { fCurrentDVFactory = fXML11DatatypeFactory; setProperty(DATATYPE_VALIDATOR_FACTORY, fCurrentDVFactory); } if (fCurrentDTDScanner != fXML11DTDScanner) { fCurrentDTDScanner = fXML11DTDScanner; setProperty(DTD_SCANNER, fCurrentDTDScanner); setProperty(DTD_PROCESSOR, fXML11DTDProcessor); } fXML11DTDScanner.setDTDHandler(fXML11DTDProcessor); fXML11DTDProcessor.setDTDSource(fXML11DTDScanner); fXML11DTDProcessor.setDTDHandler(fDTDHandler); if (fDTDHandler != null) { fDTDHandler.setDTDSource(fXML11DTDProcessor); } fXML11DTDScanner.setDTDContentModelHandler(fXML11DTDProcessor); fXML11DTDProcessor.setDTDContentModelSource(fXML11DTDScanner); fXML11DTDProcessor.setDTDContentModelHandler(fDTDContentModelHandler); if (fDTDContentModelHandler != null) { fDTDContentModelHandler.setDTDContentModelSource(fXML11DTDProcessor); } // setup XML 1.1 document pipeline if (fFeatures.get(NAMESPACES) == Boolean.TRUE) { if (fCurrentScanner != fXML11NSDocScanner) { fCurrentScanner = fXML11NSDocScanner; setProperty(DOCUMENT_SCANNER, fXML11NSDocScanner); setProperty(DTD_VALIDATOR, fXML11NSDTDValidator); } fXML11NSDocScanner.setDTDValidator(fXML11NSDTDValidator); fXML11NSDocScanner.setDocumentHandler(fXML11NSDTDValidator); fXML11NSDTDValidator.setDocumentSource(fXML11NSDocScanner); fXML11NSDTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fXML11NSDTDValidator); } fLastComponent = fXML11NSDTDValidator; } else { // create components if (fXML11DocScanner == null) { // non namespace document pipeline fXML11DocScanner = new XML11DocumentScannerImpl(); addXML11Component(fXML11DocScanner); fXML11DTDValidator = new XML11DTDValidator(); addXML11Component(fXML11DTDValidator); } if (fCurrentScanner != fXML11DocScanner) { fCurrentScanner = fXML11DocScanner; setProperty(DOCUMENT_SCANNER, fXML11DocScanner); setProperty(DTD_VALIDATOR, fXML11DTDValidator); } fXML11DocScanner.setDocumentHandler(fXML11DTDValidator); fXML11DTDValidator.setDocumentSource(fXML11DocScanner); fXML11DTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fXML11DTDValidator); } fLastComponent = fXML11DTDValidator; } // setup document pipeline if (fFeatures.get(XMLSCHEMA_VALIDATION) == Boolean.TRUE) { // If schema validator was not in the pipeline insert it. if (fSchemaValidator == null) { fSchemaValidator = new XMLSchemaValidator(); // add schema component setProperty(SCHEMA_VALIDATOR, fSchemaValidator); addCommonComponent(fSchemaValidator); fSchemaValidator.reset(this); // add schema message formatter if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) { XSMessageFormatter xmft = new XSMessageFormatter(); fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, xmft); } } fLastComponent.setDocumentHandler(fSchemaValidator); fSchemaValidator.setDocumentSource(fLastComponent); fSchemaValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fSchemaValidator); } fLastComponent = fSchemaValidator; } } // configureXML11Pipeline() /** Configures the pipeline. */ protected void configurePipeline() { if (fCurrentDVFactory != fDatatypeValidatorFactory) { fCurrentDVFactory = fDatatypeValidatorFactory; // use XML 1.0 datatype library setProperty(DATATYPE_VALIDATOR_FACTORY, fCurrentDVFactory); } // setup DTD pipeline if (fCurrentDTDScanner != fDTDScanner) { fCurrentDTDScanner = fDTDScanner; setProperty(DTD_SCANNER, fCurrentDTDScanner); setProperty(DTD_PROCESSOR, fDTDProcessor); fDTDScanner.setDTDHandler(fDTDProcessor); fDTDProcessor.setDTDSource(fDTDScanner); fDTDProcessor.setDTDHandler(fDTDHandler); if (fDTDHandler != null) { fDTDHandler.setDTDSource(fDTDProcessor); } fDTDScanner.setDTDContentModelHandler(fDTDProcessor); fDTDProcessor.setDTDContentModelSource(fDTDScanner); fDTDProcessor.setDTDContentModelHandler(fDTDContentModelHandler); if (fDTDContentModelHandler != null) { fDTDContentModelHandler.setDTDContentModelSource(fDTDProcessor); } } // setup document pipeline if (fFeatures.get(NAMESPACES) == Boolean.TRUE) { if (fCurrentScanner != fNamespaceScanner) { fCurrentScanner = fNamespaceScanner; setProperty(DOCUMENT_SCANNER, fNamespaceScanner); setProperty(DTD_VALIDATOR, fDTDValidator); } fNamespaceScanner.setDTDValidator(fDTDValidator); fNamespaceScanner.setDocumentHandler(fDTDValidator); fDTDValidator.setDocumentSource(fNamespaceScanner); fDTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fDTDValidator); } fLastComponent = fDTDValidator; } else { // create components if (fNonNSScanner == null) { fNonNSScanner = new XMLDocumentScannerImpl(); fNonNSDTDValidator = new XMLDTDValidator(); // add components addComponent((XMLComponent) fNonNSScanner); addComponent((XMLComponent) fNonNSDTDValidator); } if (fCurrentScanner != fNonNSScanner) { fCurrentScanner = fNonNSScanner; setProperty(DOCUMENT_SCANNER, fNonNSScanner); setProperty(DTD_VALIDATOR, fNonNSDTDValidator); } fNonNSScanner.setDocumentHandler(fNonNSDTDValidator); fNonNSDTDValidator.setDocumentSource(fNonNSScanner); fNonNSDTDValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fNonNSDTDValidator); } fLastComponent = fNonNSDTDValidator; } // add XML Schema validator if needed if (fFeatures.get(XMLSCHEMA_VALIDATION) == Boolean.TRUE) { // If schema validator was not in the pipeline insert it. if (fSchemaValidator == null) { fSchemaValidator = new XMLSchemaValidator(); // add schema component setProperty(SCHEMA_VALIDATOR, fSchemaValidator); addCommonComponent(fSchemaValidator); fSchemaValidator.reset(this); // add schema message formatter if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) { XSMessageFormatter xmft = new XSMessageFormatter(); fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, xmft); } } fLastComponent.setDocumentHandler(fSchemaValidator); fSchemaValidator.setDocumentSource(fLastComponent); fSchemaValidator.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) { fDocumentHandler.setDocumentSource(fSchemaValidator); } fLastComponent = fSchemaValidator; } } // configurePipeline() // features and properties /** * Check a feature. If feature is know and supported, this method simply * returns. Otherwise, the appropriate exception is thrown. * * @param featureId The unique identifier (URI) of the feature. * * @throws XMLConfigurationException Thrown for configuration error. * In general, components should * only throw this exception if * it is <strong>really</strong> * a critical error. */ protected void checkFeature(String featureId) throws XMLConfigurationException { // // Xerces Features // if (featureId.startsWith(Constants.XERCES_FEATURE_PREFIX)) { String feature = featureId.substring(Constants.XERCES_FEATURE_PREFIX.length()); // // http://apache.org/xml/features/validation/dynamic // Allows the parser to validate a document only when it // contains a grammar. Validation is turned on/off based // on each document instance, automatically. // if (feature.equals(Constants.DYNAMIC_VALIDATION_FEATURE)) { return; } // // http://apache.org/xml/features/validation/default-attribute-values // if (feature.equals(Constants.DEFAULT_ATTRIBUTE_VALUES_FEATURE)) { // REVISIT short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, featureId); } // // http://apache.org/xml/features/validation/default-attribute-values // if (feature.equals(Constants.VALIDATE_CONTENT_MODELS_FEATURE)) { // REVISIT short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, featureId); } // // http://apache.org/xml/features/validation/nonvalidating/load-dtd-grammar // if (feature.equals(Constants.LOAD_DTD_GRAMMAR_FEATURE)) { return; } // // http://apache.org/xml/features/validation/nonvalidating/load-external-dtd // if (feature.equals(Constants.LOAD_EXTERNAL_DTD_FEATURE)) { return; } // // http://apache.org/xml/features/validation/default-attribute-values // if (feature.equals(Constants.VALIDATE_DATATYPES_FEATURE)) { short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, featureId); } // // http://apache.org/xml/features/validation/schema // Lets the user turn Schema validation support on/off. // if (feature.equals(Constants.SCHEMA_VALIDATION_FEATURE)) { return; } // activate full schema checking if (feature.equals(Constants.SCHEMA_FULL_CHECKING)) { return; } // Feature identifier: expose schema normalized value // http://apache.org/xml/features/validation/schema/normalized-value if(feature.equals(Constants.SCHEMA_NORMALIZED_VALUE)) { return; } // Feature identifier: send element default value via characters() // http://apache.org/xml/features/validation/schema/element-default if(feature.equals(Constants.SCHEMA_ELEMENT_DEFAULT)) { return; } // special performance feature: only component manager is allowed to set it. if (feature.equals(Constants.PARSER_SETTINGS)) { short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, featureId); } } // // Not recognized // super.checkFeature(featureId); } // checkFeature(String) /** * Check a property. If the property is know and supported, this method * simply returns. Otherwise, the appropriate exception is thrown. * * @param propertyId The unique identifier (URI) of the property * being set. * * @throws XMLConfigurationException Thrown for configuration error. * In general, components should * only throw this exception if * it is <strong>really</strong> * a critical error. */ protected void checkProperty(String propertyId) throws XMLConfigurationException { // // Xerces Properties // if (propertyId.startsWith(Constants.XERCES_PROPERTY_PREFIX)) { String property = propertyId.substring(Constants.XERCES_PROPERTY_PREFIX.length()); if (property.equals(Constants.DTD_SCANNER_PROPERTY)) { return; } if (property.equals(Constants.SCHEMA_LOCATION)) { return; } if (property.equals(Constants.SCHEMA_NONS_LOCATION)) { return; } } if (propertyId.startsWith(Constants.JAXP_PROPERTY_PREFIX)) { String property = propertyId.substring(Constants.JAXP_PROPERTY_PREFIX.length()); if (property.equals(Constants.SCHEMA_SOURCE)) { return; } } // special cases if (propertyId.startsWith(Constants.SAX_PROPERTY_PREFIX)) { String property = propertyId.substring(Constants.SAX_PROPERTY_PREFIX.length()); // // http://xml.org/sax/properties/xml-string // Value type: String // Access: read-only // Get the literal string of characters associated with the // current event. If the parser recognises and supports this // property but is not currently parsing text, it should return // null (this is a good way to check for availability before the // parse begins). // if (property.equals(Constants.XML_STRING_PROPERTY)) { // REVISIT - we should probably ask xml-dev for a precise // definition of what this is actually supposed to return, and // in exactly which circumstances. short type = XMLConfigurationException.NOT_SUPPORTED; throw new XMLConfigurationException(type, propertyId); } } // // Not recognized // super.checkProperty(propertyId); } // checkProperty(String) /** * Adds a component to the parser configuration. This method will * also add all of the component's recognized features and properties * to the list of default recognized features and properties. * * @param component The component to add. */ protected void addComponent(XMLComponent component) { //System.out.println("==>Adding XML 1.0: "+component); // don't add a component more than once if (fComponents.contains(component)) { return; } fComponents.addElement(component); // register component's recognized features String[] recognizedFeatures = component.getRecognizedFeatures(); addRecognizedFeatures(recognizedFeatures); // register component's recognized properties String[] recognizedProperties = component.getRecognizedProperties(); addRecognizedProperties(recognizedProperties); // set default values if (recognizedFeatures != null) { for (int i = 0; i < recognizedFeatures.length; i++) { String featureId = recognizedFeatures[i]; Boolean state = component.getFeatureDefault(featureId); if (state != null) { super.setFeature(featureId, state.booleanValue()); } } } if (recognizedProperties != null) { for (int i = 0; i < recognizedProperties.length; i++) { String propertyId = recognizedProperties[i]; Object value = component.getPropertyDefault(propertyId); if (value != null) { super.setProperty(propertyId, value); } } } } // addComponent(XMLComponent) /** * Adds common component to the parser configuration. This method will * also add all of the component's recognized features and properties * to the list of default recognized features and properties. * * @param component The component to add. */ protected void addCommonComponent(XMLComponent component) { // don't add a component more than once if (fCommonComponents.contains(component)) { return; } fCommonComponents.addElement(component); // register component's recognized features String[] recognizedFeatures = component.getRecognizedFeatures(); addRecognizedFeatures(recognizedFeatures); // register component's recognized properties String[] recognizedProperties = component.getRecognizedProperties(); addRecognizedProperties(recognizedProperties); // set default values if (recognizedFeatures != null) { for (int i = 0; i < recognizedFeatures.length; i++) { String featureId = recognizedFeatures[i]; Boolean state = component.getFeatureDefault(featureId); if (state != null) { super.setFeature(featureId, state.booleanValue()); } } } if (recognizedProperties != null) { for (int i = 0; i < recognizedProperties.length; i++) { String propertyId = recognizedProperties[i]; Object value = component.getPropertyDefault(propertyId); if (value != null) { super.setProperty(propertyId, value); } } } } // addCommonComponent(XMLComponent) /** * Adds an XML 1.1 component to the parser configuration. This method will * also add all of the component's recognized features and properties * to the list of default recognized features and properties. * * @param component The component to add. */ protected void addXML11Component(XMLComponent component) { //System.out.println("Adding XML 1.1: " + component); // don't add a component more than once if (fXML11Components.contains(component)) { return; } fXML11Components.addElement(component); // register component's recognized features String[] recognizedFeatures = component.getRecognizedFeatures(); addRecognizedFeatures(recognizedFeatures); // register component's recognized properties String[] recognizedProperties = component.getRecognizedProperties(); addRecognizedProperties(recognizedProperties); // set default values if (recognizedFeatures != null) { for (int i = 0; i < recognizedFeatures.length; i++) { String featureId = recognizedFeatures[i]; Boolean state = component.getFeatureDefault(featureId); if (state != null) { checkFeature(featureId); fFeatures.put(featureId, state); } } } if (recognizedProperties != null) { for (int i = 0; i < recognizedProperties.length; i++) { String propertyId = recognizedProperties[i]; Object value = component.getPropertyDefault(propertyId); if (value != null) { checkProperty(propertyId); fProperties.put(propertyId, value); } } } } // addXML11Component(XMLComponent) private void initXML11Components() { if (!fInitalized) { // create datatype factory fXML11DatatypeFactory = DTDDVFactory.getInstance(XML11_DATATYPE_VALIDATOR_FACTORY); // setup XML 1.1 DTD pipeline fXML11DTDScanner = new XML11DTDScannerImpl(); addXML11Component(fXML11DTDScanner); fXML11DTDProcessor = new XML11DTDProcessor(); addXML11Component(fXML11DTDProcessor); // setup XML 1.1. document pipeline - namespace aware fXML11NSDocScanner = new XML11NSDocumentScannerImpl(); addXML11Component(fXML11NSDocScanner); fXML11NSDTDValidator = new XML11NSDTDValidator(); addXML11Component(fXML11NSDTDValidator); if (fSchemaValidator != null) addXML11Component(fSchemaValidator); } } } // class XML11Configuration
Fixing a bug in XML10 configurePipeline: we should always setup DTD pipeline (was only setup if scanner has not been changed) git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@319532 13f79535-47bb-0310-9956-ffa450edef68
src/org/apache/xerces/parsers/XML11Configuration.java
Fixing a bug in XML10 configurePipeline: we should always setup DTD pipeline (was only setup if scanner has not been changed)
<ide><path>rc/org/apache/xerces/parsers/XML11Configuration.java <ide> <ide> // setup DTD pipeline <ide> if (fCurrentDTDScanner != fDTDScanner) { <del> fCurrentDTDScanner = fDTDScanner; <add> fCurrentDTDScanner = fDTDScanner; <ide> setProperty(DTD_SCANNER, fCurrentDTDScanner); <ide> setProperty(DTD_PROCESSOR, fDTDProcessor); <del> fDTDScanner.setDTDHandler(fDTDProcessor); <del> fDTDProcessor.setDTDSource(fDTDScanner); <del> fDTDProcessor.setDTDHandler(fDTDHandler); <del> if (fDTDHandler != null) { <del> fDTDHandler.setDTDSource(fDTDProcessor); <del> } <del> <del> fDTDScanner.setDTDContentModelHandler(fDTDProcessor); <del> fDTDProcessor.setDTDContentModelSource(fDTDScanner); <del> fDTDProcessor.setDTDContentModelHandler(fDTDContentModelHandler); <del> if (fDTDContentModelHandler != null) { <del> fDTDContentModelHandler.setDTDContentModelSource(fDTDProcessor); <del> } <add> } <add> fDTDScanner.setDTDHandler(fDTDProcessor); <add> fDTDProcessor.setDTDSource(fDTDScanner); <add> fDTDProcessor.setDTDHandler(fDTDHandler); <add> if (fDTDHandler != null) { <add> fDTDHandler.setDTDSource(fDTDProcessor); <add> } <add> <add> fDTDScanner.setDTDContentModelHandler(fDTDProcessor); <add> fDTDProcessor.setDTDContentModelSource(fDTDScanner); <add> fDTDProcessor.setDTDContentModelHandler(fDTDContentModelHandler); <add> if (fDTDContentModelHandler != null) { <add> fDTDContentModelHandler.setDTDContentModelSource(fDTDProcessor); <ide> } <ide> <ide> // setup document pipeline <ide> // add schema component <ide> setProperty(SCHEMA_VALIDATOR, fSchemaValidator); <ide> addCommonComponent(fSchemaValidator); <del> fSchemaValidator.reset(this); <add> fSchemaValidator.reset(this); <ide> // add schema message formatter <ide> if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) { <ide> XSMessageFormatter xmft = new XSMessageFormatter(); <ide> * @param component The component to add. <ide> */ <ide> protected void addComponent(XMLComponent component) { <del> //System.out.println("==>Adding XML 1.0: "+component); <ide> // don't add a component more than once <ide> if (fComponents.contains(component)) { <ide> return; <ide> * @param component The component to add. <ide> */ <ide> protected void addXML11Component(XMLComponent component) { <del> //System.out.println("Adding XML 1.1: " + component); <ide> // don't add a component more than once <ide> if (fXML11Components.contains(component)) { <ide> return;
Java
bsd-3-clause
8d7798b3250fb531a9165cca55eec415caec8988
0
anildahiya/sdl_android,jthrun/sdl_android,jthrun/sdl_android,smartdevicelink/sdl_android
package com.smartdevicelink.api.lockscreen; import android.content.Context; import android.test.AndroidTestCase; import android.test.mock.MockContext; import com.smartdevicelink.proxy.interfaces.ISdl; import com.smartdevicelink.proxy.rpc.enums.LockScreenStatus; import com.smartdevicelink.test.Test; import static org.mockito.Mockito.mock; /** * This is a unit test class for the SmartDeviceLink library manager class : * {@link com.smartdevicelink.api.lockscreen.LockScreenManager} */ public class LockScreenManagerTests extends AndroidTestCase { private LockScreenManager lockScreenManager; @Override public void setUp() throws Exception{ super.setUp(); ISdl internalInterface = mock(ISdl.class); Context context = new MockContext(); // create config LockScreenConfig lockScreenConfig = new LockScreenConfig(); lockScreenConfig.setCustomView(Test.GENERAL_INT); lockScreenConfig.setAppIcon(Test.GENERAL_INT); lockScreenConfig.setBackgroundColor(Test.GENERAL_INT); lockScreenConfig.showDeviceLogo(true); lockScreenConfig.setEnabled(true); lockScreenManager = new LockScreenManager(lockScreenConfig, context, internalInterface); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testVariables() { assertEquals(Test.GENERAL_INT, lockScreenManager.customView); assertEquals(Test.GENERAL_INT, lockScreenManager.lockScreenIcon); assertEquals(Test.GENERAL_INT, lockScreenManager.lockScreenColor); assertEquals(true, lockScreenManager.deviceLogoEnabled); assertEquals(true, lockScreenManager.lockScreenEnabled); assertNull(lockScreenManager.deviceLogo); } public void testGetLockScreenStatus(){ assertEquals(LockScreenStatus.OFF, lockScreenManager.getLockScreenStatus()); } }
sdl_android/src/androidTest/java/com/smartdevicelink/api/lockscreen/LockScreenManagerTests.java
package com.smartdevicelink.api.lockscreen; import android.content.Context; import android.test.AndroidTestCase; import android.test.mock.MockContext; import com.smartdevicelink.proxy.interfaces.ISdl; import com.smartdevicelink.proxy.rpc.enums.LockScreenStatus; import com.smartdevicelink.test.Test; import static org.mockito.Mockito.mock; /** * This is a unit test class for the SmartDeviceLink library manager class : * {@link com.smartdevicelink.api.SdlManager} */ public class LockScreenManagerTests extends AndroidTestCase { private LockScreenManager lockScreenManager; @Override public void setUp() throws Exception{ super.setUp(); ISdl internalInterface = mock(ISdl.class); Context context = new MockContext(); // create config LockScreenConfig lockScreenConfig = new LockScreenConfig(); lockScreenConfig.setCustomView(Test.GENERAL_INT); lockScreenConfig.setAppIcon(Test.GENERAL_INT); lockScreenConfig.setBackgroundColor(Test.GENERAL_INT); lockScreenConfig.showDeviceLogo(true); lockScreenConfig.setEnabled(true); lockScreenManager = new LockScreenManager(lockScreenConfig, context, internalInterface); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testVariables() { assertEquals(Test.GENERAL_INT, lockScreenManager.customView); assertEquals(Test.GENERAL_INT, lockScreenManager.lockScreenIcon); assertEquals(Test.GENERAL_INT, lockScreenManager.lockScreenColor); assertEquals(true, lockScreenManager.deviceLogoEnabled); assertEquals(true, lockScreenManager.lockScreenEnabled); assertNull(lockScreenManager.deviceLogo); } public void testGetLockScreenStatus(){ assertEquals(LockScreenStatus.OFF, lockScreenManager.getLockScreenStatus()); } }
fixed invalid javadoc link
sdl_android/src/androidTest/java/com/smartdevicelink/api/lockscreen/LockScreenManagerTests.java
fixed invalid javadoc link
<ide><path>dl_android/src/androidTest/java/com/smartdevicelink/api/lockscreen/LockScreenManagerTests.java <ide> <ide> /** <ide> * This is a unit test class for the SmartDeviceLink library manager class : <del> * {@link com.smartdevicelink.api.SdlManager} <add> * {@link com.smartdevicelink.api.lockscreen.LockScreenManager} <ide> */ <ide> public class LockScreenManagerTests extends AndroidTestCase { <ide>
Java
epl-1.0
cc91713f068bedc9ff605ad4273bcf944e2dc47b
0
voltnor/gp438,voltnor/gp438,voltnor/gp438
import java.awt.*; import java.awt.event.*; import java.io.File; import java.util.ArrayList; import javax.swing.*; import edu.mines.jtk.awt.*; import edu.mines.jtk.dsp.*; import edu.mines.jtk.util.Cdouble; import edu.mines.jtk.mosaic.*; import static edu.mines.jtk.util.ArrayMath.*; public class PlotTest{ public static void main(String[] args){ SwingUtilities.invokeLater(new Runnable() { public void run() { new PlotTest(); } }); } // Location and size of overlay plot. private static final int M_X = 100; private static final int M_Y = 0; private static final int M_WIDTH = 520; private static final int M_HEIGHT = 550; // Location and size of response plot. private static final int RP_X = M_X+M_WIDTH; private static final int RP_Y = 0; private static final int RP_WIDTH = 520; private static final int RP_HEIGHT = 550; // Plot of source/receivers // private ArrayList<MPoint> _shots; private ArrayList<MPoint> _recs; private ArrayList<MPoint> _gps; private BasePlot _bp; private ResponsePlot _rp; private PlotTest(){ // _shots = new ArrayList<MPoint>(0); _recs = new ArrayList<MPoint>(0); _bp = new BasePlot(); _rp = new ResponsePlot(); } private void addMPoint(MPoint p) { _recs.add(p); _bp.updateBPView(); } /////////////////////////////////////////////////////////////////////////// private class BasePlot { private PlotFrame _plotFrame; private PlotPanel _plotPanel; private PointsView _baseView; private BasePlot() { // The plot panel. _plotPanel = new PlotPanel(); _plotPanel.setTitle("Base Plot Test"); _plotPanel.setHLabel("Easting (UTM)"); _plotPanel.setVLabel("Northing (UTM)"); _plotPanel.setHLimits(100,200); //TODO: plot displays E+06 for large ints _plotPanel.setVLimits(100,200); //TODO: plot displays E+06 for large ints // A grid view for horizontal and vertical lines (axes). _plotPanel.addGrid("H0-V0-"); // A plot frame has a mode for zooming in tiles or tile axes. _plotFrame = new PlotFrame(_plotPanel); TileZoomMode tzm = _plotFrame.getTileZoomMode(); // We add two more modes for editing poles and zeros. ModeManager mm = _plotFrame.getModeManager(); AddMode am = new AddMode(mm); // for test points // PoleZeroMode zm = new PoleZeroMode(mm,false); // for zeros // The menu bar includes a mode menu for selecting a mode. JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); fileMenu.add(new SaveAsPngAction(_plotFrame)).setMnemonic('a'); fileMenu.add(new ExitAction()).setMnemonic('x'); JMenu modeMenu = new JMenu("Mode"); modeMenu.setMnemonic('M'); modeMenu.add(new ModeMenuItem(tzm)); modeMenu.add(new ModeMenuItem(am)); JMenu toolMenu = new JMenu("Tools"); toolMenu.setMnemonic('T'); toolMenu.add(new GetFlagsFromHH()).setMnemonic('f'); toolMenu.add(new GetDEM(_plotPanel)).setMnemonic('g'); JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); menuBar.add(modeMenu); menuBar.add(toolMenu); _plotFrame.setJMenuBar(menuBar); // The tool bar includes toggle buttons for selecting a mode. JToolBar toolBar = new JToolBar(SwingConstants.VERTICAL); toolBar.setRollover(true); toolBar.add(new ModeToggleButton(tzm)); toolBar.add(new ModeToggleButton(am)); _plotFrame.add(toolBar,BorderLayout.WEST); // Initially, enable editing of poles. // pm.setActive(true); // Make the plot frame visible. _plotFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); _plotFrame.setLocation(M_X,M_Y); _plotFrame.setSize(M_WIDTH,M_HEIGHT); _plotFrame.setFontSizeForPrint(8,240); _plotFrame.setVisible(true); } // Makes poles view consistent with the list of poles. private void updateBPView() { int np = _recs.size(); float[] xp = new float[np]; float[] yp = new float[np]; boolean[] sel = new boolean[np]; for (int ip=0; ip<np; ++ip) { MPoint p = _recs.get(ip); xp[ip] = (float)p.x; yp[ip] = (float)p.y; System.out.println("xp[ip]: " + xp[ip] + " yp[ip]: " + yp[ip]); sel[ip] = p.selected; } if (_baseView==null) { _baseView = _plotPanel.addPoints(xp,yp); _baseView.setMarkStyle(PointsView.Mark.CROSS); _baseView.setLineStyle(PointsView.Line.NONE); } else { _baseView.set(xp,yp); } } } /////////////////////////////////////////////////////////////////////////// private class ResponsePlot { private PlotPanel _plotPanelH; private PlotFrame _plotFrame; private SequenceView _hView; private PointsView _pView; // The amplitude response can be in decibels (db). private ResponsePlot() { // One plot panel for the impulse response. _plotPanelH = new PlotPanel(); _plotPanelH.setHLabel("Easting (UTM)"); _plotPanelH.setVLabel("Time (s)"); _plotPanelH.setTitle("Title"); // This first update constructs a sequence view for the impulse // response, and a points view for amplitude and phase responses. // updateViews(); _plotFrame = new PlotFrame(_plotPanelH); // The menu bar. JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); fileMenu.add(new SaveAsPngAction(_plotFrame)).setMnemonic('a'); fileMenu.add(new ExitAction()).setMnemonic('x'); JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); _plotFrame.setJMenuBar(menuBar); // Make the plot frame visible. _plotFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); _plotFrame.setLocation(RP_X,RP_Y); _plotFrame.setSize(RP_WIDTH,RP_HEIGHT); _plotFrame.setFontSizeForPrint(8,240); _plotFrame.setVisible(true); } } /////////////////////////////////////////////////////////////////////////// private class AddMode extends Mode { public AddMode(ModeManager modeManager) { super(modeManager); setName("Add Receivers"); // setIcon(loadIcon(PolesAndZerosDemo.class,"Poles16.png")); setMnemonicKey(KeyEvent.VK_X); setAcceleratorKey(KeyStroke.getKeyStroke(KeyEvent.VK_X,0)); setShortDescription("Add (Shift)"); } // When this mode is activated (or deactivated) for a tile, it simply // adds (or removes) its mouse listener to (or from) that tile. protected void setActive(Component component, boolean active) { if (component instanceof Tile) { if (active) { component.addMouseListener(_ml); } else { component.removeMouseListener(_ml); } } } } private boolean _editing; // true, if currently editing private Tile _tile; // tile in which editing began // Handles mouse pressed and released events. private MouseListener _ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isShiftDown()) { add(e); } else { if (beginEdit(e)) { _editing = true; _tile.addMouseMotionListener(_mml); } } } public void mouseReleased(MouseEvent e) { if (_editing) { _tile.removeMouseMotionListener(_mml); endEdit(e); _editing = false; } } }; // Handles mouse dragged events. private MouseMotionListener _mml = new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (_editing) duringEdit(e); } }; // Adds a pole or zero at mouse coordinates (x,y). // TODO: Convert pixels to actual private void add(MouseEvent e) { _tile = (Tile)e.getSource(); double x = e.getX(); double y = e.getY(); MPoint p = new MPoint(x,y); System.out.println("p.x: " + p.x + " p.y: " + p.y); addMPoint(p); } // Begins editing of an existing pole or zero, if close enough. // Returns true, if close enough so that we have begun editing; // false, otherwise. private boolean beginEdit(MouseEvent e) { _tile = (Tile)e.getSource(); int x = e.getX(); int y = e.getY(); return false; } private void duringEdit(MouseEvent e) { int x = e.getX(); int y = e.getY(); // Cdouble z = pointToComplex(x,y); // if (_poles) { // movePole(_zedit,z); // } else { // moveZero(_zedit,z); // } // _zedit = z; } // Called when done editing a pole or zero. private void endEdit(MouseEvent e) { duringEdit(e); _editing = false; } /////////////////////////////////////////////////////////////////////////// // Actions common to both plot frames. private class ExitAction extends AbstractAction { private ExitAction() { super("Exit"); } public void actionPerformed(ActionEvent event) { System.exit(0); } } private class SaveAsPngAction extends AbstractAction { private PlotFrame _plotFrame; private SaveAsPngAction(PlotFrame plotFrame) { super("Save as PNG"); _plotFrame = plotFrame; } public void actionPerformed(ActionEvent event) { JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.showSaveDialog(_plotFrame); File file = fc.getSelectedFile(); if (file!=null) { String filename = file.getAbsolutePath(); _plotFrame.paintToPng(300,6,filename); } } } private class GetDEM extends AbstractAction { private GetDEM(PlotPanel plotPanel){ super("Get USGS Elevation"); } public void actionPerformed(ActionEvent event){ //TODO } } private class GetFlagsFromHH extends AbstractAction { private GetFlagsFromHH(){ super("Get HandHeld GPS"); } public void actionPerformed(ActionEvent event){ //TODO JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.showOpenDialog(null); File f = fc.getSelectedFile(); } } /////////////////////////////////////////////////////////////////////////// public class MPoint { // from xyz coord MPoint(double x, double y, double z){ this.x = x; this.y = y; this.z = z; } // from xy coord MPoint(double x, double y){ this.x = x; this.y = y; } public double x, y, z; public boolean selected; } }
PlotTest/PlotTest.java
import java.awt.*; import java.awt.event.*; import java.io.File; import java.util.ArrayList; import javax.swing.*; import edu.mines.jtk.awt.*; import edu.mines.jtk.dsp.*; import edu.mines.jtk.util.Cdouble; import edu.mines.jtk.mosaic.*; import static edu.mines.jtk.util.ArrayMath.*; public class PlotTest{ public static void main(String[] args){ SwingUtilities.invokeLater(new Runnable() { public void run() { new PlotTest(); } }); } // Location and size of overlay plot. private static final int M_X = 100; private static final int M_Y = 0; private static final int M_WIDTH = 520; private static final int M_HEIGHT = 550; // Location and size of response plot. private static final int RP_X = M_X+M_WIDTH; private static final int RP_Y = 0; private static final int RP_WIDTH = 520; private static final int RP_HEIGHT = 550; // Plot of source/receivers // private ArrayList<MPoint> _shots; private ArrayList<MPoint> _recs; private ArrayList<MPoint> _gps; private BasePlot _bp; private ResponsePlot _rp; private PlotTest(){ // _shots = new ArrayList<MPoint>(0); _recs = new ArrayList<MPoint>(0); _bp = new BasePlot(); _rp = new ResponsePlot(); } private void addMPoint(MPoint p) { _recs.add(p); _bp.updateBPView(); } /////////////////////////////////////////////////////////////////////////// private class BasePlot { private PlotFrame _plotFrame; private PlotPanel _plotPanel; private PointsView _baseView; private BasePlot() { // The plot panel. _plotPanel = new PlotPanel(); _plotPanel.setTitle("Base Plot Test"); _plotPanel.setHLabel("Easting (UTM)"); _plotPanel.setVLabel("Northing (UTM)"); _plotPanel.setHLimits(100,200); //TODO: plot displays E+06 for large ints _plotPanel.setVLimits(100,200); //TODO: plot displays E+06 for large ints // A grid view for horizontal and vertical lines (axes). _plotPanel.addGrid("H0-V0-"); // A plot frame has a mode for zooming in tiles or tile axes. _plotFrame = new PlotFrame(_plotPanel); TileZoomMode tzm = _plotFrame.getTileZoomMode(); // We add two more modes for editing poles and zeros. ModeManager mm = _plotFrame.getModeManager(); AddMode am = new AddMode(mm); // for test points // PoleZeroMode zm = new PoleZeroMode(mm,false); // for zeros // The menu bar includes a mode menu for selecting a mode. JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); fileMenu.add(new SaveAsPngAction(_plotFrame)).setMnemonic('a'); fileMenu.add(new ExitAction()).setMnemonic('x'); JMenu modeMenu = new JMenu("Mode"); modeMenu.setMnemonic('M'); modeMenu.add(new ModeMenuItem(tzm)); modeMenu.add(new ModeMenuItem(am)); JMenu toolMenu = new JMenu("Tools"); toolMenu.setMnemonic('T'); toolMenu.add(new GetFlagsFromHH()).setMnemonic('f'); toolMenu.add(new GetDEM(_plotPanel)).setMnemonic('g'); JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); menuBar.add(modeMenu); menuBar.add(toolMenu); _plotFrame.setJMenuBar(menuBar); // The tool bar includes toggle buttons for selecting a mode. JToolBar toolBar = new JToolBar(SwingConstants.VERTICAL); toolBar.setRollover(true); toolBar.add(new ModeToggleButton(tzm)); toolBar.add(new ModeToggleButton(am)); _plotFrame.add(toolBar,BorderLayout.WEST); // Initially, enable editing of poles. // pm.setActive(true); // Make the plot frame visible. _plotFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); _plotFrame.setLocation(M_X,M_Y); _plotFrame.setSize(M_WIDTH,M_HEIGHT); _plotFrame.setFontSizeForPrint(8,240); _plotFrame.setVisible(true); } // Makes poles view consistent with the list of poles. private void updateBPView() { int np = _recs.size(); float[] xp = new float[np]; float[] yp = new float[np]; boolean[] sel = new boolean[np]; for (int ip=0; ip<np; ++ip) { MPoint p = _recs.get(ip); xp[ip] = (float)p.px; yp[ip] = (float)p.py; System.out.println("xp[ip]: " + xp[ip] + " yp[ip]: " + yp[ip]); sel[ip] = p.selected; } if (_baseView==null) { _baseView = _plotPanel.addPoints(xp,yp); _baseView.setMarkStyle(PointsView.Mark.CROSS); _baseView.setLineStyle(PointsView.Line.NONE); } else { _baseView.set(xp,yp); } } } /////////////////////////////////////////////////////////////////////////// private class ResponsePlot { private PlotPanel _plotPanelH; private PlotFrame _plotFrame; private SequenceView _hView; private PointsView _pView; // The amplitude response can be in decibels (db). private ResponsePlot() { // One plot panel for the impulse response. _plotPanelH = new PlotPanel(); _plotPanelH.setHLabel("Easting (UTM)"); _plotPanelH.setVLabel("Time (s)"); _plotPanelH.setTitle("Title"); // This first update constructs a sequence view for the impulse // response, and a points view for amplitude and phase responses. // updateViews(); _plotFrame = new PlotFrame(_plotPanelH); // The menu bar. JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); fileMenu.add(new SaveAsPngAction(_plotFrame)).setMnemonic('a'); fileMenu.add(new ExitAction()).setMnemonic('x'); JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); _plotFrame.setJMenuBar(menuBar); // Make the plot frame visible. _plotFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); _plotFrame.setLocation(RP_X,RP_Y); _plotFrame.setSize(RP_WIDTH,RP_HEIGHT); _plotFrame.setFontSizeForPrint(8,240); _plotFrame.setVisible(true); } } /////////////////////////////////////////////////////////////////////////// private class AddMode extends Mode { public AddMode(ModeManager modeManager) { super(modeManager); setName("Add Receivers"); // setIcon(loadIcon(PolesAndZerosDemo.class,"Poles16.png")); setMnemonicKey(KeyEvent.VK_X); setAcceleratorKey(KeyStroke.getKeyStroke(KeyEvent.VK_X,0)); setShortDescription("Add (Shift)"); } // When this mode is activated (or deactivated) for a tile, it simply // adds (or removes) its mouse listener to (or from) that tile. protected void setActive(Component component, boolean active) { if (component instanceof Tile) { if (active) { component.addMouseListener(_ml); } else { component.removeMouseListener(_ml); } } } } private boolean _editing; // true, if currently editing private Tile _tile; // tile in which editing began // Handles mouse pressed and released events. private MouseListener _ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isShiftDown()) { add(e); } else { if (beginEdit(e)) { _editing = true; _tile.addMouseMotionListener(_mml); } } } public void mouseReleased(MouseEvent e) { if (_editing) { _tile.removeMouseMotionListener(_mml); endEdit(e); _editing = false; } } }; // Handles mouse dragged events. private MouseMotionListener _mml = new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (_editing) duringEdit(e); } }; // Adds a pole or zero at mouse coordinates (x,y). // TODO: Convert pixels to actual private void add(MouseEvent e) { _tile = (Tile)e.getSource(); double x = e.getX(); double y = e.getY(); MPoint p = new MPoint((int)x,(int)y, false); System.out.println("p.px: " + p.px + " p.py: " + p.py); addMPoint(p); } // Begins editing of an existing pole or zero, if close enough. // Returns true, if close enough so that we have begun editing; // false, otherwise. private boolean beginEdit(MouseEvent e) { _tile = (Tile)e.getSource(); int x = e.getX(); int y = e.getY(); return false; } private void duringEdit(MouseEvent e) { int x = e.getX(); int y = e.getY(); // Cdouble z = pointToComplex(x,y); // if (_poles) { // movePole(_zedit,z); // } else { // moveZero(_zedit,z); // } // _zedit = z; } // Called when done editing a pole or zero. private void endEdit(MouseEvent e) { duringEdit(e); _editing = false; } /////////////////////////////////////////////////////////////////////////// // Actions common to both plot frames. private class ExitAction extends AbstractAction { private ExitAction() { super("Exit"); } public void actionPerformed(ActionEvent event) { System.exit(0); } } private class SaveAsPngAction extends AbstractAction { private PlotFrame _plotFrame; private SaveAsPngAction(PlotFrame plotFrame) { super("Save as PNG"); _plotFrame = plotFrame; } public void actionPerformed(ActionEvent event) { JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); fc.showSaveDialog(_plotFrame); File file = fc.getSelectedFile(); if (file!=null) { String filename = file.getAbsolutePath(); _plotFrame.paintToPng(300,6,filename); } } } private class GetDEM extends AbstractAction { private GetDEM(PlotPanel plotPanel){ super("Get USGS Elevation"); } public void actionPerformed(ActionEvent event){ //TODO } } private class GetFlagsFromHH extends AbstractAction { private GetFlagsFromHH(){ super("Get HandHeld GPS"); } public void actionPerformed(ActionEvent event){ //TODO } } /////////////////////////////////////////////////////////////////////////// public class MPoint { // from gps coord MPoint(double x, double y){ this.x = x; this.y = y; calcPixFromGPS(); } // from pixel MPoint(int px, int py, boolean mode){ this.px = px; this.py = py; calcGPSFromPix(); } private void calcPixFromGPS(){ } private void calcGPSFromPix(){ } public double x, y, elev; public int px, py; public boolean selected; } }
updated gps read
PlotTest/PlotTest.java
updated gps read
<ide><path>lotTest/PlotTest.java <ide> boolean[] sel = new boolean[np]; <ide> for (int ip=0; ip<np; ++ip) { <ide> MPoint p = _recs.get(ip); <del> xp[ip] = (float)p.px; <del> yp[ip] = (float)p.py; <add> xp[ip] = (float)p.x; <add> yp[ip] = (float)p.y; <ide> System.out.println("xp[ip]: " + xp[ip] + " yp[ip]: " + yp[ip]); <ide> sel[ip] = p.selected; <ide> } <ide> _tile = (Tile)e.getSource(); <ide> double x = e.getX(); <ide> double y = e.getY(); <del> MPoint p = new MPoint((int)x,(int)y, false); <del> System.out.println("p.px: " + p.px + " p.py: " + p.py); <add> MPoint p = new MPoint(x,y); <add> System.out.println("p.x: " + p.x + " p.y: " + p.y); <ide> addMPoint(p); <ide> } <ide> <ide> private class GetFlagsFromHH extends AbstractAction { <ide> private GetFlagsFromHH(){ <ide> super("Get HandHeld GPS"); <add> <ide> } <ide> public void actionPerformed(ActionEvent event){ <ide> //TODO <add> JFileChooser fc = new JFileChooser(System.getProperty("user.dir")); <add> fc.showOpenDialog(null); <add> File f = fc.getSelectedFile(); <add> <ide> } <ide> <ide> } <ide> <ide> <ide> public class MPoint { <del> // from gps coord <add> // from xyz coord <add> MPoint(double x, double y, double z){ <add> this.x = x; <add> this.y = y; <add> this.z = z; <add> } <add> <add> // from xy coord <ide> MPoint(double x, double y){ <ide> this.x = x; <ide> this.y = y; <del> calcPixFromGPS(); <del> } <del> // from pixel <del> MPoint(int px, int py, boolean mode){ <del> this.px = px; <del> this.py = py; <del> calcGPSFromPix(); <del> } <del> <del> private void calcPixFromGPS(){ <del> <del> } <del> <del> private void calcGPSFromPix(){ <del> <del> } <del> <del> public double x, y, elev; <del> public int px, py; <add> } <add> <add> <add> public double x, y, z; <ide> public boolean selected; <ide> } <ide>
Java
mit
68959ef26855960c006bf200627845336d9e9222
0
HackMyChurch/aelf-dailyreadings,HackMyChurch/aelf-dailyreadings,HackMyChurch/aelf-dailyreadings,HackMyChurch/aelf-dailyreadings,HackMyChurch/aelf-dailyreadings
package co.epitre.aelf_lectures; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; // WebView dependencies import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import static co.epitre.aelf_lectures.SyncPrefActivity.KEY_BIBLE_LAST_PAGE; /** * Created by jean-tiare on 12/03/18. */ public class SectionBibleFragment extends SectionFragmentBase { public static final String TAG = "SectionBibleFragment"; public static final String BASE_RES_URL = "file:///android_asset/www/"; public SectionBibleFragment(){ // Required empty public constructor } /** * Global managers / resources */ SharedPreferences settings = null; WebView mWebView; int activityRequestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); // Load settings settings = PreferenceManager.getDefaultSharedPreferences(getContext()); // Set Section title (Can be anywhere in the class !) actionBar.setTitle("Bible"); // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_section_bible, container, false); mWebView = view.findViewById(R.id.webView); // Get webview settings settings final WebSettings webSettings = mWebView.getSettings(); // Zoom support mWebView.setOnTouchListener(new PinchToZoomListener(getContext()) { public int onZoomStart() { return super.onZoomStart(); } public void onZoomEnd(int zoomLevel) { super.onZoomEnd(zoomLevel); webSettings.setTextZoom(zoomLevel); } public void onZoom(int zoomLevel) { super.onZoom(zoomLevel); webSettings.setTextZoom(zoomLevel); } }); // Dark theme support final boolean nightMode = settings.getBoolean(SyncPrefActivity.KEY_PREF_DISP_NIGHT_MODE, false); // Force links and redirects to open in the WebView instead of in a browser mWebView.setWebViewClient(new WebViewClient() { @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (url.equals("file:///android_asset/www/virtual/application.css")) { // Load the CSS file corresponding to the selected theme String themeName = nightMode ? "dark":"light"; try { InputStream styleStream = getActivity().getAssets().open("www/assets/application_"+themeName+".css"); return new WebResourceResponse("text/css", "UTF-8", styleStream); } catch (IOException e) { Log.e(TAG, "Failed to load "+themeName+" theme", e); return null; } } return super.shouldInterceptRequest(view, url); } }); // Clear the cache on theme change so that we can inject our own CSS mWebView.clearCache(true); // Enable Javascript webSettings.setJavaScriptEnabled(true); // Enable Dom Storage https://stackoverflow.com/questions/33079762/android-webview-uncaught-typeerror-cannot-read-property-getitem-of-null webSettings.setDomStorageEnabled(true); // Get intent link, if any Uri uri = activity.getIntent().getData(); // Load webview if (uri != null) { // Parse link and open linked page onLink(uri); } else if (savedInstanceState != null) { // Restore state mWebView.restoreState(savedInstanceState); } else { // Load default page SharedPreferences settings = getActivity().getPreferences(Context.MODE_PRIVATE); Log.d(TAG,"Loading webview, KEY_BIBLE_LAST_PAGE is " + settings.getString(KEY_BIBLE_LAST_PAGE,"null")); mWebView.loadUrl(settings.getString(KEY_BIBLE_LAST_PAGE,(BASE_RES_URL + "index.html"))); } //Save last URL // onPageFinished infos found on https://stackoverflow.com/a/6720004 mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(mWebView, url); String last_url = mWebView.getUrl(); Log.d(TAG, "last_url is " + last_url); SharedPreferences settings = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(KEY_BIBLE_LAST_PAGE, last_url); editor.apply(); Log.d(TAG,"onPageFinished, KEY_BIBLE_LAST_PAGE is " + settings.getString(KEY_BIBLE_LAST_PAGE,"null")); } }); //TODO: Create the following two methods somewhere ; getLastUrl() returning String ; setLastUrl(String last_url) //TODO: Save scroll position and restore it. return view; } /** * Back pressed send from activity. * * @return if event is consumed, it will return true. * https://www.skoumal.net/en/android-handle-back-press-in-fragment/ */ @Override public boolean onBackPressed() { if (mWebView.canGoBack()) { mWebView.goBack(); return true; } else { return false; } } @Override public void onLink(Uri uri) { String path = uri.getPath(); String host = uri.getHost(); String parsedUrl = "index.html"; if (host.equals("www.aelf.org")) { // AELF Website String[] chunks = path.split("/"); if (chunks.length >= 2 && chunks[1].equals("bible")) { if (chunks.length == 2) { // Bible home page parsedUrl = "index.html"; } else { parsedUrl = TextUtils.join("/", Arrays.copyOfRange(chunks, 1, chunks.length)); parsedUrl += ".html"; } } } // Load requested page mWebView.loadUrl(BASE_RES_URL + parsedUrl); } // // Option menu // @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); // Inflate the menu; this adds items to the action bar inflater.inflate(R.menu.toolbar_bible, menu); // Make the share image white Drawable normalDrawable = ContextCompat.getDrawable(activity, R.drawable.ic_share_black_24dp); Drawable wrapDrawable = DrawableCompat.wrap(normalDrawable); DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(activity, R.color.white)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_share: return onShare(); } return super.onOptionsItemSelected(item); } // // Events // public boolean onShare() { if (mWebView == null) { return false; } // Get current webview URL String webviewUrl = mWebView.getUrl(); webviewUrl = webviewUrl.substring(BASE_RES_URL.length() - 1, webviewUrl.length()- ".html".length()); if (webviewUrl.equals("/index")) { webviewUrl = "/bible"; } // Get current webview title String webviewTitle = mWebView.getTitle(); // Build share message String websiteUrl = "https://www.aelf.org" + webviewUrl; String message = webviewTitle + ": " + websiteUrl; String subject = webviewTitle; // Create the intent Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, message); intent.putExtra(Intent.EXTRA_SUBJECT, subject); startActivity(Intent.createChooser(intent, getString(R.string.action_share))); // All done ! return true; } // // Lifecycle // @Override public void onResume() { super.onResume(); FragmentActivity activity = getActivity(); if (activity == null) { return; } // Get current requested orientation, so that we can restore it activityRequestedOrientation = activity.getRequestedOrientation(); // Disable landscape view, this is currently broken activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } @Override public void onPause() { super.onPause(); FragmentActivity activity = getActivity(); if (activity == null) { return; } activity.setRequestedOrientation(activityRequestedOrientation); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mWebView != null) { mWebView.saveState(outState); } } // TODO : Fix shadow on "Autres Livres" dropdown menu not showing on real phone // TODO : Test Bible on tablet ! // TODO : Link daily readings from mass and offices to Bible // TODO : Add search in Bible function... // TODO (later): support landscape orientation }
app/src/main/java/co/epitre/aelf_lectures/SectionBibleFragment.java
package co.epitre.aelf_lectures; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; // WebView dependencies import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import static co.epitre.aelf_lectures.SyncPrefActivity.KEY_BIBLE_LAST_PAGE; /** * Created by jean-tiare on 12/03/18. */ public class SectionBibleFragment extends SectionFragmentBase { public static final String TAG = "SectionBibleFragment"; public static final String BASE_RES_URL = "file:///android_asset/www/"; public SectionBibleFragment(){ // Required empty public constructor } /** * Global managers / resources */ SharedPreferences settings = null; WebView mWebView; int activityRequestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); // Load settings settings = PreferenceManager.getDefaultSharedPreferences(getContext()); // Set Section title (Can be anywhere in the class !) actionBar.setTitle("Bible"); // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_section_bible, container, false); mWebView = view.findViewById(R.id.webView); // Get webview settings settings final WebSettings webSettings = mWebView.getSettings(); // Zoom support mWebView.setOnTouchListener(new PinchToZoomListener(getContext()) { public int onZoomStart() { return super.onZoomStart(); } public void onZoomEnd(int zoomLevel) { super.onZoomEnd(zoomLevel); webSettings.setTextZoom(zoomLevel); } public void onZoom(int zoomLevel) { super.onZoom(zoomLevel); webSettings.setTextZoom(zoomLevel); } }); // Dark theme support final boolean nightMode = settings.getBoolean(SyncPrefActivity.KEY_PREF_DISP_NIGHT_MODE, false); // Force links and redirects to open in the WebView instead of in a browser mWebView.setWebViewClient(new WebViewClient() { @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (url.equals("file:///android_asset/www/virtual/application.css")) { // Load the CSS file corresponding to the selected theme String themeName = nightMode ? "dark":"light"; try { InputStream styleStream = getActivity().getAssets().open("www/assets/application_"+themeName+".css"); return new WebResourceResponse("text/css", "UTF-8", styleStream); } catch (IOException e) { Log.e(TAG, "Failed to load "+themeName+" theme", e); return null; } } return super.shouldInterceptRequest(view, url); } }); // Clear the cache on theme change so that we can inject our own CSS mWebView.clearCache(true); // Enable Javascript webSettings.setJavaScriptEnabled(true); // Enable Dom Storage https://stackoverflow.com/questions/33079762/android-webview-uncaught-typeerror-cannot-read-property-getitem-of-null webSettings.setDomStorageEnabled(true); // Get intent link, if any Uri uri = activity.getIntent().getData(); // Load webview if (uri != null) { // Parse link and open linked page onLink(uri); } else if (savedInstanceState != null) { // Restore state mWebView.restoreState(savedInstanceState); } else { // Load default page Log.d(TAG,"Loading webview, KEY_BIBLE_LAST_PAGE is " + settings.getString(KEY_BIBLE_LAST_PAGE,"null")); mWebView.loadUrl(settings.getString(KEY_BIBLE_LAST_PAGE,(BASE_RES_URL + "index.html"))); } //Save last URL // onPageFinished infos found on https://stackoverflow.com/a/6720004 mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(mWebView, url); String last_url = mWebView.getUrl(); Log.d(TAG, "last_url is " + last_url); //TODO: Save the value in a persistent storage, maybe sharedpreferences and use it when the webview is re-created. SharedPreferences settings = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putString(KEY_BIBLE_LAST_PAGE, last_url); editor.apply(); Log.d(TAG,"onPageFinished, KEY_BIBLE_LAST_PAGE is " + settings.getString(KEY_BIBLE_LAST_PAGE,"null")); } }); //TODO: Save scroll position and restore it. return view; } /** * Back pressed send from activity. * * @return if event is consumed, it will return true. * https://www.skoumal.net/en/android-handle-back-press-in-fragment/ */ @Override public boolean onBackPressed() { if (mWebView.canGoBack()) { mWebView.goBack(); return true; } else { return false; } } @Override public void onLink(Uri uri) { String path = uri.getPath(); String host = uri.getHost(); String parsedUrl = "index.html"; if (host.equals("www.aelf.org")) { // AELF Website String[] chunks = path.split("/"); if (chunks.length >= 2 && chunks[1].equals("bible")) { if (chunks.length == 2) { // Bible home page parsedUrl = "index.html"; } else { parsedUrl = TextUtils.join("/", Arrays.copyOfRange(chunks, 1, chunks.length)); parsedUrl += ".html"; } } } // Load requested page mWebView.loadUrl(BASE_RES_URL + parsedUrl); } // // Option menu // @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); // Inflate the menu; this adds items to the action bar inflater.inflate(R.menu.toolbar_bible, menu); // Make the share image white Drawable normalDrawable = ContextCompat.getDrawable(activity, R.drawable.ic_share_black_24dp); Drawable wrapDrawable = DrawableCompat.wrap(normalDrawable); DrawableCompat.setTint(wrapDrawable, ContextCompat.getColor(activity, R.color.white)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_share: return onShare(); } return super.onOptionsItemSelected(item); } // // Events // public boolean onShare() { if (mWebView == null) { return false; } // Get current webview URL String webviewUrl = mWebView.getUrl(); webviewUrl = webviewUrl.substring(BASE_RES_URL.length() - 1, webviewUrl.length()- ".html".length()); if (webviewUrl.equals("/index")) { webviewUrl = "/bible"; } // Get current webview title String webviewTitle = mWebView.getTitle(); // Build share message String websiteUrl = "https://www.aelf.org" + webviewUrl; String message = webviewTitle + ": " + websiteUrl; String subject = webviewTitle; // Create the intent Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, message); intent.putExtra(Intent.EXTRA_SUBJECT, subject); startActivity(Intent.createChooser(intent, getString(R.string.action_share))); // All done ! return true; } // // Lifecycle // @Override public void onResume() { super.onResume(); FragmentActivity activity = getActivity(); if (activity == null) { return; } // Get current requested orientation, so that we can restore it activityRequestedOrientation = activity.getRequestedOrientation(); // Disable landscape view, this is currently broken activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } @Override public void onPause() { super.onPause(); FragmentActivity activity = getActivity(); if (activity == null) { return; } activity.setRequestedOrientation(activityRequestedOrientation); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mWebView != null) { mWebView.saveState(outState); } } // TODO : Fix shadow on "Autres Livres" dropdown menu not showing on real phone // TODO : Test Bible on tablet ! // TODO : Link daily readings from mass and offices to Bible // TODO : Add search in Bible function... // TODO (later): support landscape orientation }
bible: Restore last page view, 4/4 This commit fixes the problem
app/src/main/java/co/epitre/aelf_lectures/SectionBibleFragment.java
bible: Restore last page view, 4/4 This commit fixes the problem
<ide><path>pp/src/main/java/co/epitre/aelf_lectures/SectionBibleFragment.java <ide> mWebView.restoreState(savedInstanceState); <ide> } else { <ide> // Load default page <add> SharedPreferences settings = getActivity().getPreferences(Context.MODE_PRIVATE); <ide> Log.d(TAG,"Loading webview, KEY_BIBLE_LAST_PAGE is " + settings.getString(KEY_BIBLE_LAST_PAGE,"null")); <ide> mWebView.loadUrl(settings.getString(KEY_BIBLE_LAST_PAGE,(BASE_RES_URL + "index.html"))); <ide> } <ide> super.onPageFinished(mWebView, url); <ide> String last_url = mWebView.getUrl(); <ide> Log.d(TAG, "last_url is " + last_url); <del> //TODO: Save the value in a persistent storage, maybe sharedpreferences and use it when the webview is re-created. <ide> SharedPreferences settings = getActivity().getPreferences(Context.MODE_PRIVATE); <ide> SharedPreferences.Editor editor = settings.edit(); <ide> editor.putString(KEY_BIBLE_LAST_PAGE, last_url); <ide> <ide> } <ide> }); <del> <add> //TODO: Create the following two methods somewhere ; getLastUrl() returning String ; setLastUrl(String last_url) <ide> //TODO: Save scroll position and restore it. <ide> <ide> return view;
Java
apache-2.0
3bb4a5a69fd7c247434b22e04b8d76b32016d29f
0
robinverduijn/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle,robinverduijn/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,gstevey/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gstevey/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,gstevey/gradle,gstevey/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,lsmaira/gradle,gstevey/gradle,robinverduijn/gradle,blindpirate/gradle
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.resolve; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import org.gradle.api.UnknownProjectException; import org.gradle.api.artifacts.component.ComponentIdentifier; import org.gradle.api.artifacts.component.LibraryBinaryIdentifier; import org.gradle.api.artifacts.component.LibraryComponentSelector; import org.gradle.api.internal.component.ArtifactType; import org.gradle.internal.component.local.model.LocalComponentMetaData; import org.gradle.internal.component.local.model.PublishArtifactLocalArtifactMetaData; import org.gradle.internal.component.model.*; import org.gradle.internal.resolve.ArtifactResolveException; import org.gradle.internal.resolve.ModuleVersionResolveException; import org.gradle.internal.resolve.resolver.ArtifactResolver; import org.gradle.internal.resolve.resolver.ComponentMetaDataResolver; import org.gradle.internal.resolve.resolver.DependencyToComponentIdResolver; import org.gradle.internal.resolve.result.BuildableArtifactResolveResult; import org.gradle.internal.resolve.result.BuildableArtifactSetResolveResult; import org.gradle.internal.resolve.result.BuildableComponentIdResolveResult; import org.gradle.internal.resolve.result.BuildableComponentResolveResult; import org.gradle.language.base.internal.model.VariantAxisCompatibilityFactory; import org.gradle.language.base.internal.model.VariantsMetaData; import org.gradle.language.base.internal.resolve.LibraryResolveException; import org.gradle.model.ModelMap; import org.gradle.model.internal.manage.schema.ModelSchemaStore; import org.gradle.model.internal.registry.ModelRegistry; import org.gradle.model.internal.type.ModelType; import org.gradle.platform.base.BinarySpec; import org.gradle.platform.base.ComponentSpec; import org.gradle.platform.base.internal.BinarySpecInternal; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; public class LocalLibraryDependencyResolver<T extends BinarySpec> implements DependencyToComponentIdResolver, ComponentMetaDataResolver, ArtifactResolver { private final ProjectModelResolver projectModelResolver; private final VariantsMetaData variantsMetaData; private final VariantsMatcher matcher; private final LibraryResolutionErrorMessageBuilder errorMessageBuilder; private final LocalLibraryMetaDataAdapter libraryMetaDataAdapter; private final Class<? extends BinarySpec> binaryType; private final Predicate<ComponentSpec> binarySpecPredicate; public LocalLibraryDependencyResolver( Class<T> binarySpecType, ProjectModelResolver projectModelResolver, List<VariantAxisCompatibilityFactory> selectorFactories, VariantsMetaData variantsMetaData, ModelSchemaStore schemaStore, LocalLibraryMetaDataAdapter libraryMetaDataAdapter, LibraryResolutionErrorMessageBuilder errorMessageBuilder) { this.projectModelResolver = projectModelResolver; this.libraryMetaDataAdapter = libraryMetaDataAdapter; this.matcher = new VariantsMatcher(selectorFactories, binarySpecType, schemaStore); this.errorMessageBuilder = errorMessageBuilder; this.variantsMetaData = variantsMetaData; this.binaryType = binarySpecType; this.binarySpecPredicate = new Predicate<ComponentSpec>() { @Override public boolean apply(ComponentSpec input) { return !input.getBinaries().withType(binaryType).isEmpty(); } }; } @Override public void resolve(DependencyMetaData dependency, final BuildableComponentIdResolveResult result) { if (dependency.getSelector() instanceof LibraryComponentSelector) { LibraryComponentSelector selector = (LibraryComponentSelector) dependency.getSelector(); resolveLibraryAndChooseBinary(result, selector); } } private void resolveLibraryAndChooseBinary(BuildableComponentIdResolveResult result, LibraryComponentSelector selector) { final String selectorProjectPath = selector.getProjectPath(); final String libraryName = selector.getLibraryName(); final String variant = selector.getVariant(); LibraryResolutionErrorMessageBuilder.LibraryResolutionResult resolutionResult = doResolve(selectorProjectPath, libraryName); ComponentSpec selectedLibrary = resolutionResult.getSelectedLibrary(); if (selectedLibrary != null) { if (variant == null) { selectMatchingVariant(result, selectedLibrary, selector, selectorProjectPath, libraryName); } else { selectExplicitlyProvidedVariant(result, selectedLibrary, selectorProjectPath, variant); } } if (!result.hasResult()) { String message = resolutionResult.toResolutionErrorMessage(binaryType, selector); ModuleVersionResolveException failure = new ModuleVersionResolveException(selector, new LibraryResolveException(message)); result.failed(failure); } } private void selectExplicitlyProvidedVariant(BuildableComponentIdResolveResult result, ComponentSpec selectedLibrary, String selectorProjectPath, String variant) { Collection<BinarySpec> allBinaries = selectedLibrary.getBinaries().values(); for (BinarySpec binarySpec : allBinaries) { BinarySpecInternal binary = (BinarySpecInternal) binarySpec; LibraryBinaryIdentifier id = binary.getId(); if (Objects.equal(variant, id.getVariant())) { // TODO:Cedric This is not quite right. We assume that if we are asking for a specific binary, then we resolve to the assembly instead // of the jar, but it should be somehow parametrized LocalComponentMetaData metaData = libraryMetaDataAdapter.createLocalComponentMetaData(binary, selectorProjectPath, true); result.resolved(metaData); } } } private void selectMatchingVariant(BuildableComponentIdResolveResult result, ComponentSpec selectedLibrary, LibraryComponentSelector selector, String selectorProjectPath, String libraryName) { Collection<BinarySpec> allBinaries = selectedLibrary.getBinaries().values(); Collection<? extends BinarySpec> compatibleBinaries = matcher.filterBinaries(variantsMetaData, allBinaries); if (!allBinaries.isEmpty() && compatibleBinaries.isEmpty()) { // no compatible variant found result.failed(new ModuleVersionResolveException(selector, errorMessageBuilder.noCompatibleVariantErrorMessage(libraryName, allBinaries))); } else if (compatibleBinaries.size() > 1) { result.failed(new ModuleVersionResolveException(selector, errorMessageBuilder.multipleCompatibleVariantsErrorMessage(libraryName, compatibleBinaries))); } else { BinarySpec selectedBinary = compatibleBinaries.iterator().next(); LocalComponentMetaData metaData = libraryMetaDataAdapter.createLocalComponentMetaData(selectedBinary, selectorProjectPath, false); result.resolved(metaData); } } private LibraryResolutionErrorMessageBuilder.LibraryResolutionResult doResolve(String projectPath, String libraryName) { try { ModelRegistry projectModel = projectModelResolver.resolveProjectModel(projectPath); LibraryResolutionErrorMessageBuilder.LibraryResolutionResult libraries = findLocalComponent(libraryName, projectModel); if (libraries != null) { return libraries; } return LibraryResolutionErrorMessageBuilder.LibraryResolutionResult.emptyResolutionResult(); } catch (UnknownProjectException e) { return LibraryResolutionErrorMessageBuilder.LibraryResolutionResult.projectNotFound(); } } private LibraryResolutionErrorMessageBuilder.LibraryResolutionResult findLocalComponent(String componentName, ModelRegistry projectModel) { List<ComponentSpec> librarySpecs = Lists.newArrayList(); collectLocalComponents(projectModel, "components", librarySpecs); collectLocalComponents(projectModel, "testSuites", librarySpecs); if (librarySpecs.isEmpty()) { return null; } return LibraryResolutionErrorMessageBuilder.LibraryResolutionResult.of(librarySpecs, componentName, binarySpecPredicate); } private void collectLocalComponents(ModelRegistry projectModel, String container, List<ComponentSpec> librarySpecs) { ModelMap<ComponentSpec> components = projectModel.find(container, new ModelType<ModelMap<ComponentSpec>>() { }); if (components != null) { ModelMap<? extends ComponentSpec> libraries = components.withType(ComponentSpec.class); librarySpecs.addAll(libraries.values()); } } @Override public void resolve(ComponentIdentifier identifier, ComponentOverrideMetadata componentOverrideMetadata, BuildableComponentResolveResult result) { if (isLibrary(identifier)) { throw new RuntimeException("Not yet implemented"); } } private boolean isLibrary(ComponentIdentifier identifier) { return identifier instanceof LibraryBinaryIdentifier; } @Override public void resolveModuleArtifacts(ComponentResolveMetaData component, ComponentUsage usage, BuildableArtifactSetResolveResult result) { ComponentIdentifier componentId = component.getComponentId(); if (isLibrary(componentId)) { ConfigurationMetaData configuration = component.getConfiguration(usage.getConfigurationName()); if (configuration != null) { Set<ComponentArtifactMetaData> artifacts = configuration.getArtifacts(); result.resolved(artifacts); } if (!result.hasResult()) { result.failed(new ArtifactResolveException(String.format("Unable to resolve artifact for %s", componentId))); } } } @Override public void resolveModuleArtifacts(ComponentResolveMetaData component, ArtifactType artifactType, BuildableArtifactSetResolveResult result) { if (isLibrary(component.getComponentId())) { result.resolved(Collections.<ComponentArtifactMetaData>emptyList()); } } @Override public void resolveArtifact(ComponentArtifactMetaData artifact, ModuleSource moduleSource, BuildableArtifactResolveResult result) { if (isLibrary(artifact.getComponentId())) { if (artifact instanceof PublishArtifactLocalArtifactMetaData) { result.resolved(((PublishArtifactLocalArtifactMetaData) artifact).getFile()); } else { result.failed(new ArtifactResolveException("Unsupported artifact metadata type: " + artifact)); } } } }
subprojects/platform-base/src/main/java/org/gradle/api/internal/resolve/LocalLibraryDependencyResolver.java
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.resolve; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.collect.Lists; import org.gradle.api.UnknownProjectException; import org.gradle.api.artifacts.component.ComponentIdentifier; import org.gradle.api.artifacts.component.LibraryBinaryIdentifier; import org.gradle.api.artifacts.component.LibraryComponentSelector; import org.gradle.api.internal.component.ArtifactType; import org.gradle.internal.component.local.model.LocalComponentMetaData; import org.gradle.internal.component.local.model.PublishArtifactLocalArtifactMetaData; import org.gradle.internal.component.model.*; import org.gradle.internal.resolve.ArtifactResolveException; import org.gradle.internal.resolve.ModuleVersionResolveException; import org.gradle.internal.resolve.resolver.ArtifactResolver; import org.gradle.internal.resolve.resolver.ComponentMetaDataResolver; import org.gradle.internal.resolve.resolver.DependencyToComponentIdResolver; import org.gradle.internal.resolve.result.BuildableArtifactResolveResult; import org.gradle.internal.resolve.result.BuildableArtifactSetResolveResult; import org.gradle.internal.resolve.result.BuildableComponentIdResolveResult; import org.gradle.internal.resolve.result.BuildableComponentResolveResult; import org.gradle.language.base.internal.model.VariantAxisCompatibilityFactory; import org.gradle.language.base.internal.model.VariantsMetaData; import org.gradle.language.base.internal.resolve.LibraryResolveException; import org.gradle.model.ModelMap; import org.gradle.model.internal.manage.schema.ModelSchemaStore; import org.gradle.model.internal.registry.ModelRegistry; import org.gradle.model.internal.type.ModelType; import org.gradle.platform.base.BinarySpec; import org.gradle.platform.base.ComponentSpec; import org.gradle.platform.base.internal.BinarySpecInternal; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; public class LocalLibraryDependencyResolver<T extends BinarySpec> implements DependencyToComponentIdResolver, ComponentMetaDataResolver, ArtifactResolver { private final ProjectModelResolver projectModelResolver; private final VariantsMetaData variantsMetaData; private final VariantsMatcher matcher; private final LibraryResolutionErrorMessageBuilder errorMessageBuilder; private final LocalLibraryMetaDataAdapter libraryMetaDataAdapter; private final Class<? extends BinarySpec> binaryType; private final Predicate<ComponentSpec> binarySpecPredicate; public LocalLibraryDependencyResolver( Class<T> binarySpecType, ProjectModelResolver projectModelResolver, List<VariantAxisCompatibilityFactory> selectorFactories, VariantsMetaData variantsMetaData, ModelSchemaStore schemaStore, LocalLibraryMetaDataAdapter libraryMetaDataAdapter, LibraryResolutionErrorMessageBuilder errorMessageBuilder) { this.projectModelResolver = projectModelResolver; this.libraryMetaDataAdapter = libraryMetaDataAdapter; this.matcher = new VariantsMatcher(selectorFactories, binarySpecType, schemaStore); this.errorMessageBuilder = errorMessageBuilder; this.variantsMetaData = variantsMetaData; this.binaryType = binarySpecType; this.binarySpecPredicate = new Predicate<ComponentSpec>() { @Override public boolean apply(ComponentSpec input) { return !input.getBinaries().withType(binaryType).isEmpty(); } }; } @Override public void resolve(DependencyMetaData dependency, final BuildableComponentIdResolveResult result) { if (dependency.getSelector() instanceof LibraryComponentSelector) { LibraryComponentSelector selector = (LibraryComponentSelector) dependency.getSelector(); resolveLibraryAndChooseBinary(result, selector); } } private void resolveLibraryAndChooseBinary(BuildableComponentIdResolveResult result, LibraryComponentSelector selector) { final String selectorProjectPath = selector.getProjectPath(); final String libraryName = selector.getLibraryName(); final String variant = selector.getVariant(); LibraryResolutionErrorMessageBuilder.LibraryResolutionResult resolutionResult = doResolve(selectorProjectPath, libraryName); ComponentSpec selectedLibrary = resolutionResult.getSelectedLibrary(); if (selectedLibrary != null) { if (variant == null) { selectBinaryVariant(result, selectedLibrary, selector, selectorProjectPath, libraryName); } else { selectSpecificVariant(result, selectedLibrary, selectorProjectPath, variant); } } if (!result.hasResult()) { String message = resolutionResult.toResolutionErrorMessage(binaryType, selector); ModuleVersionResolveException failure = new ModuleVersionResolveException(selector, new LibraryResolveException(message)); result.failed(failure); } } private void selectSpecificVariant(BuildableComponentIdResolveResult result, ComponentSpec selectedLibrary, String selectorProjectPath, String variant) { Collection<BinarySpec> allBinaries = selectedLibrary.getBinaries().values(); for (BinarySpec binarySpec : allBinaries) { BinarySpecInternal binary = (BinarySpecInternal) binarySpec; LibraryBinaryIdentifier id = binary.getId(); if (Objects.equal(variant, id.getVariant())) { // TODO:Cedric This is not quite right. We assume that if we are asking for a specific binary, then we resolve to the assembly instead // of the jar, but it should be somehow parametrized LocalComponentMetaData metaData = libraryMetaDataAdapter.createLocalComponentMetaData(binary, selectorProjectPath, true); result.resolved(metaData); } } } private void selectBinaryVariant(BuildableComponentIdResolveResult result, ComponentSpec selectedLibrary, LibraryComponentSelector selector, String selectorProjectPath, String libraryName) { Collection<BinarySpec> allBinaries = selectedLibrary.getBinaries().values(); Collection<? extends BinarySpec> compatibleBinaries = matcher.filterBinaries(variantsMetaData, allBinaries); if (!allBinaries.isEmpty() && compatibleBinaries.isEmpty()) { // no compatible variant found result.failed(new ModuleVersionResolveException(selector, errorMessageBuilder.noCompatibleVariantErrorMessage(libraryName, allBinaries))); } else if (compatibleBinaries.size() > 1) { result.failed(new ModuleVersionResolveException(selector, errorMessageBuilder.multipleCompatibleVariantsErrorMessage(libraryName, compatibleBinaries))); } else { BinarySpec selectedBinary = compatibleBinaries.iterator().next(); LocalComponentMetaData metaData = libraryMetaDataAdapter.createLocalComponentMetaData(selectedBinary, selectorProjectPath, false); result.resolved(metaData); } } private LibraryResolutionErrorMessageBuilder.LibraryResolutionResult doResolve(String projectPath, String libraryName) { try { ModelRegistry projectModel = projectModelResolver.resolveProjectModel(projectPath); LibraryResolutionErrorMessageBuilder.LibraryResolutionResult libraries = findLocalComponent(libraryName, projectModel); if (libraries != null) { return libraries; } return LibraryResolutionErrorMessageBuilder.LibraryResolutionResult.emptyResolutionResult(); } catch (UnknownProjectException e) { return LibraryResolutionErrorMessageBuilder.LibraryResolutionResult.projectNotFound(); } } private LibraryResolutionErrorMessageBuilder.LibraryResolutionResult findLocalComponent(String componentName, ModelRegistry projectModel) { List<ComponentSpec> librarySpecs = Lists.newArrayList(); collectLocalComponents(projectModel, "components", librarySpecs); collectLocalComponents(projectModel, "testSuites", librarySpecs); if (librarySpecs.isEmpty()) { return null; } return LibraryResolutionErrorMessageBuilder.LibraryResolutionResult.of(librarySpecs, componentName, binarySpecPredicate); } private void collectLocalComponents(ModelRegistry projectModel, String container, List<ComponentSpec> librarySpecs) { ModelMap<ComponentSpec> components = projectModel.find(container, new ModelType<ModelMap<ComponentSpec>>() { }); if (components != null) { ModelMap<? extends ComponentSpec> libraries = components.withType(ComponentSpec.class); librarySpecs.addAll(libraries.values()); } } @Override public void resolve(ComponentIdentifier identifier, ComponentOverrideMetadata componentOverrideMetadata, BuildableComponentResolveResult result) { if (isLibrary(identifier)) { throw new RuntimeException("Not yet implemented"); } } private boolean isLibrary(ComponentIdentifier identifier) { return identifier instanceof LibraryBinaryIdentifier; } @Override public void resolveModuleArtifacts(ComponentResolveMetaData component, ComponentUsage usage, BuildableArtifactSetResolveResult result) { ComponentIdentifier componentId = component.getComponentId(); if (isLibrary(componentId)) { ConfigurationMetaData configuration = component.getConfiguration(usage.getConfigurationName()); if (configuration != null) { Set<ComponentArtifactMetaData> artifacts = configuration.getArtifacts(); result.resolved(artifacts); } if (!result.hasResult()) { result.failed(new ArtifactResolveException(String.format("Unable to resolve artifact for %s", componentId))); } } } @Override public void resolveModuleArtifacts(ComponentResolveMetaData component, ArtifactType artifactType, BuildableArtifactSetResolveResult result) { if (isLibrary(component.getComponentId())) { result.resolved(Collections.<ComponentArtifactMetaData>emptyList()); } } @Override public void resolveArtifact(ComponentArtifactMetaData artifact, ModuleSource moduleSource, BuildableArtifactResolveResult result) { if (isLibrary(artifact.getComponentId())) { if (artifact instanceof PublishArtifactLocalArtifactMetaData) { result.resolved(((PublishArtifactLocalArtifactMetaData) artifact).getFile()); } else { result.failed(new ArtifactResolveException("Unsupported artifact metadata type: " + artifact)); } } } }
Renamed methods for clarity Story: gradle/langos#113
subprojects/platform-base/src/main/java/org/gradle/api/internal/resolve/LocalLibraryDependencyResolver.java
Renamed methods for clarity
<ide><path>ubprojects/platform-base/src/main/java/org/gradle/api/internal/resolve/LocalLibraryDependencyResolver.java <ide> ComponentSpec selectedLibrary = resolutionResult.getSelectedLibrary(); <ide> if (selectedLibrary != null) { <ide> if (variant == null) { <del> selectBinaryVariant(result, selectedLibrary, selector, selectorProjectPath, libraryName); <add> selectMatchingVariant(result, selectedLibrary, selector, selectorProjectPath, libraryName); <ide> } else { <del> selectSpecificVariant(result, selectedLibrary, selectorProjectPath, variant); <add> selectExplicitlyProvidedVariant(result, selectedLibrary, selectorProjectPath, variant); <ide> } <ide> } <ide> if (!result.hasResult()) { <ide> } <ide> } <ide> <del> private void selectSpecificVariant(BuildableComponentIdResolveResult result, ComponentSpec selectedLibrary, String selectorProjectPath, String variant) { <add> private void selectExplicitlyProvidedVariant(BuildableComponentIdResolveResult result, ComponentSpec selectedLibrary, String selectorProjectPath, String variant) { <ide> Collection<BinarySpec> allBinaries = selectedLibrary.getBinaries().values(); <ide> for (BinarySpec binarySpec : allBinaries) { <ide> BinarySpecInternal binary = (BinarySpecInternal) binarySpec; <ide> } <ide> } <ide> <del> private void selectBinaryVariant(BuildableComponentIdResolveResult result, ComponentSpec selectedLibrary, LibraryComponentSelector selector, String selectorProjectPath, String libraryName) { <add> private void selectMatchingVariant(BuildableComponentIdResolveResult result, ComponentSpec selectedLibrary, LibraryComponentSelector selector, String selectorProjectPath, String libraryName) { <ide> Collection<BinarySpec> allBinaries = selectedLibrary.getBinaries().values(); <ide> Collection<? extends BinarySpec> compatibleBinaries = matcher.filterBinaries(variantsMetaData, allBinaries); <ide> if (!allBinaries.isEmpty() && compatibleBinaries.isEmpty()) {
Java
apache-2.0
036fb50bbe60086e0f9761f3e26375b54d1f75c7
0
cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x
/* * Copyright 2004-2005 the original author or authors. */ package org.springframework.binding.support; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.springframework.binding.MutableAttributeSource; import org.springframework.core.Styler; import org.springframework.core.closure.ProcessTemplate; import org.springframework.core.closure.support.IteratorProcessTemplate; import org.springframework.util.Assert; /** * Support class for attribute setters. TODO - should this implement map? * @author Keith Donald */ public abstract class AttributeSourceSupport implements MutableAttributeSource { /** * Get an attribute value and make sure it is of the required type. * @param attributeName name of the attribute to get * @param requiredType the required type of the attribute value * @return the attribute value, or null if not found * @throws IllegalStateException when the value is not of the required type */ public Object getAttribute(String attributeName, Class requiredType) throws IllegalStateException { Object value = getAttribute(attributeName); if (requiredType != null && value != null) { Assert.isInstanceOf(requiredType, value); } return value; } /** * @param attributeName * @return the attribute * @throws IllegalStateException */ public Object getRequiredAttribute(String attributeName) throws IllegalStateException { Object value = getAttribute(attributeName); if (value == null) { throw new IllegalStateException("Required attribute '" + attributeName + "' is not present in this " + getSourceName() + "; attributes present are = " + Styler.call(getAttributeMap())); } return value; } protected String getSourceName() { return "map"; } /** * @param attributeName * @param clazz * @return the attribute * @throws IllegalStateException */ public Object getRequiredAttribute(String attributeName, Class clazz) throws IllegalStateException { Object value = getRequiredAttribute(attributeName); if (clazz != null) { Assert.isInstanceOf(clazz, value); } return value; } /** * Set the set of attributes. * @param attributes the attributes */ public void setAttributes(Map attributes) { Iterator it = attributes.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); Assert.isInstanceOf(String.class, entry.getKey()); setAttribute((String)entry.getKey(), entry.getValue()); } } /** * Assert the the attribute is present in this source. * @param attributeName the attribute name * @param requiredType the expected type * @throws IllegalStateException if not present */ public void assertAttributePresent(String attributeName, Class requiredType) throws IllegalStateException { getRequiredAttribute(attributeName, requiredType); } /** * Assert the the attribute is present in this source. * @param attributeName the attribute name * @throws IllegalStateException if not present */ public void assertAttributePresent(String attributeName) throws IllegalStateException { getRequiredAttribute(attributeName); } /** * Returns the names of attributes in this source * @return a collection of attribute names */ public Set attributeNames() { return Collections.unmodifiableSet(getAttributeMap().keySet()); } /** * Returns the collection of attribute values * @return a collection of attribute values */ public Collection attributeValues() { return Collections.unmodifiableCollection(getAttributeMap().values()); } /** * Returns a collection of attribute name=value pairs * @return the attribute entries */ public Set attributeEntries() { return Collections.unmodifiableSet(getAttributeMap().entrySet()); } /** * Returns a template for iterating over elements in this source. * @return the template */ public ProcessTemplate iteratorTemplate() { return new IteratorProcessTemplate(attributeEntries().iterator()); } /** * Returns the underlying attribute map * @return the attribute map */ protected abstract Map getAttributeMap(); }
sandbox/src/org/springframework/binding/support/AttributeSourceSupport.java
/* * Copyright 2004-2005 the original author or authors. */ package org.springframework.binding.support; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.springframework.binding.MutableAttributeSource; import org.springframework.core.Styler; import org.springframework.core.closure.ProcessTemplate; import org.springframework.core.closure.support.IteratorProcessTemplate; import org.springframework.util.Assert; /** * Support class for attribute setters. TODO - should this implement map? * @author Keith Donald */ public abstract class AttributeSourceSupport implements MutableAttributeSource, Map { /** * Get an attribute value and make sure it is of the required type. * @param attributeName name of the attribute to get * @param requiredType the required type of the attribute value * @return the attribute value, or null if not found * @throws IllegalStateException when the value is not of the required type */ public Object getAttribute(String attributeName, Class requiredType) throws IllegalStateException { Object value = getAttribute(attributeName); if (requiredType != null && value != null) { Assert.isInstanceOf(requiredType, value); } return value; } /** * @param attributeName * @return the attribute * @throws IllegalStateException */ public Object getRequiredAttribute(String attributeName) throws IllegalStateException { Object value = getAttribute(attributeName); if (value == null) { throw new IllegalStateException("Required attribute '" + attributeName + "' is not present in this " + getSourceName() + "; attributes present are = " + Styler.call(getAttributeMap())); } return value; } protected String getSourceName() { return "map"; } /** * @param attributeName * @param clazz * @return the attribute * @throws IllegalStateException */ public Object getRequiredAttribute(String attributeName, Class clazz) throws IllegalStateException { Object value = getRequiredAttribute(attributeName); if (clazz != null) { Assert.isInstanceOf(clazz, value); } return value; } /** * Set the set of attributes. * @param attributes the attributes */ public void setAttributes(Map attributes) { Iterator it = attributes.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); Assert.isInstanceOf(String.class, entry.getKey()); setAttribute((String)entry.getKey(), entry.getValue()); } } /** * Assert the the attribute is present in this source. * @param attributeName the attribute name * @param requiredType the expected type * @throws IllegalStateException if not present */ public void assertAttributePresent(String attributeName, Class requiredType) throws IllegalStateException { getRequiredAttribute(attributeName, requiredType); } /** * Assert the the attribute is present in this source. * @param attributeName the attribute name * @throws IllegalStateException if not present */ public void assertAttributePresent(String attributeName) throws IllegalStateException { getRequiredAttribute(attributeName); } /** * Returns the names of attributes in this source * @return a collection of attribute names */ public Set attributeNames() { return Collections.unmodifiableSet(getAttributeMap().keySet()); } /** * Returns the collection of attribute values * @return a collection of attribute values */ public Collection attributeValues() { return Collections.unmodifiableCollection(getAttributeMap().values()); } /** * Returns a collection of attribute name=value pairs * @return the attribute entries */ public Set attributeEntries() { return Collections.unmodifiableSet(getAttributeMap().entrySet()); } /** * Returns a template for iterating over elements in this source. * @return the template */ public ProcessTemplate iteratorTemplate() { return new IteratorProcessTemplate(attributeEntries().iterator()); } /** * Returns the underlying attribute map * @return the attribute map */ protected abstract Map getAttributeMap(); // map operations public boolean containsKey(Object key) { return containsAttribute(String.valueOf(key)); } public Set entrySet() { return attributeEntries(); } public Object get(Object key) { return getAttribute(String.valueOf(key)); } public Set keySet() { return attributeNames(); } public Object put(Object key, Object value) { return setAttribute(String.valueOf(key), value); } public void putAll(Map attributes) { setAttributes(attributes); } public Collection values() { return attributeValues(); } }
implement map is stupid git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@6806 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
sandbox/src/org/springframework/binding/support/AttributeSourceSupport.java
implement map is stupid
<ide><path>andbox/src/org/springframework/binding/support/AttributeSourceSupport.java <ide> * Support class for attribute setters. TODO - should this implement map? <ide> * @author Keith Donald <ide> */ <del>public abstract class AttributeSourceSupport implements MutableAttributeSource, Map { <add>public abstract class AttributeSourceSupport implements MutableAttributeSource { <ide> <ide> /** <ide> * Get an attribute value and make sure it is of the required type. <ide> */ <ide> protected abstract Map getAttributeMap(); <ide> <del> // map operations <del> <del> public boolean containsKey(Object key) { <del> return containsAttribute(String.valueOf(key)); <del> } <del> <del> public Set entrySet() { <del> return attributeEntries(); <del> } <del> <del> public Object get(Object key) { <del> return getAttribute(String.valueOf(key)); <del> } <del> <del> public Set keySet() { <del> return attributeNames(); <del> } <del> <del> public Object put(Object key, Object value) { <del> return setAttribute(String.valueOf(key), value); <del> } <del> <del> public void putAll(Map attributes) { <del> setAttributes(attributes); <del> } <del> <del> public Collection values() { <del> return attributeValues(); <del> } <ide> }
Java
apache-2.0
f8e4d6fb216f70beaa67a3f34c7f94232bfce9d7
0
youdonghai/intellij-community,apixandru/intellij-community,blademainer/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,retomerz/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,izonder/intellij-community,signed/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,samthor/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,ibinti/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,amith01994/intellij-community,xfournet/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,supersven/intellij-community,izonder/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,semonte/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,allotria/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fitermay/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,holmes/intellij-community,fnouama/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,slisson/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,ibinti/intellij-community,samthor/intellij-community,dslomov/intellij-community,izonder/intellij-community,kdwink/intellij-community,clumsy/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,da1z/intellij-community,xfournet/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,caot/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,signed/intellij-community,fitermay/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,holmes/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,akosyakov/intellij-community,holmes/intellij-community,apixandru/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,apixandru/intellij-community,caot/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,kool79/intellij-community,samthor/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,dslomov/intellij-community,ryano144/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,ibinti/intellij-community,holmes/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,adedayo/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,kool79/intellij-community,diorcety/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,dslomov/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,amith01994/intellij-community,ryano144/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ibinti/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,xfournet/intellij-community,xfournet/intellij-community,fnouama/intellij-community,holmes/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,retomerz/intellij-community,slisson/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,signed/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,clumsy/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,Lekanich/intellij-community,caot/intellij-community,da1z/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,xfournet/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,FHannes/intellij-community,fnouama/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,adedayo/intellij-community,fitermay/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,diorcety/intellij-community,fitermay/intellij-community,caot/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,ibinti/intellij-community,supersven/intellij-community,ibinti/intellij-community,da1z/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,semonte/intellij-community,da1z/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,robovm/robovm-studio,da1z/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,fnouama/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,petteyg/intellij-community,robovm/robovm-studio,vladmm/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,ibinti/intellij-community,slisson/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,retomerz/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,signed/intellij-community,jagguli/intellij-community,da1z/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,diorcety/intellij-community,FHannes/intellij-community,caot/intellij-community,allotria/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,semonte/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,kool79/intellij-community,ryano144/intellij-community,hurricup/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,diorcety/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,hurricup/intellij-community,semonte/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,semonte/intellij-community,blademainer/intellij-community,apixandru/intellij-community,diorcety/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,kool79/intellij-community,fitermay/intellij-community,slisson/intellij-community,caot/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,petteyg/intellij-community,adedayo/intellij-community,dslomov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,vladmm/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,dslomov/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,jagguli/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,amith01994/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,supersven/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,samthor/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,xfournet/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,apixandru/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,asedunov/intellij-community,kdwink/intellij-community,hurricup/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,FHannes/intellij-community,caot/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,supersven/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,FHannes/intellij-community,signed/intellij-community,robovm/robovm-studio,kool79/intellij-community,TangHao1987/intellij-community,signed/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,slisson/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,holmes/intellij-community,ryano144/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,semonte/intellij-community,clumsy/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,petteyg/intellij-community,signed/intellij-community,kool79/intellij-community,izonder/intellij-community,signed/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,signed/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,signed/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,holmes/intellij-community,da1z/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,samthor/intellij-community,signed/intellij-community,amith01994/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,allotria/intellij-community,kool79/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,allotria/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,clumsy/intellij-community,jagguli/intellij-community,ibinti/intellij-community,fnouama/intellij-community,robovm/robovm-studio,diorcety/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community
package com.jetbrains.python.inspections; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiFile; import com.intellij.util.Processor; import com.jetbrains.python.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.actions.RenameParameterQuickFix; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.impl.PyQualifiedName; import com.jetbrains.python.psi.types.PyClassType; import com.jetbrains.python.psi.types.PyNoneType; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Checks that arguments to property() and @property and friends are ok. * <br/> * User: dcheryasov * Date: Jun 30, 2010 2:53:05 PM */ public class PyPropertyDefinitionInspection extends PyInspection { @Nls @NotNull public String getDisplayName() { return PyBundle.message("INSP.NAME.property.definition"); } private ThreadLocal<LanguageLevel> myLevel = new ThreadLocal<LanguageLevel>(); private ThreadLocal<List<PyClass>> myStringClasses = new ThreadLocal<List<PyClass>>(); private ThreadLocal<PyParameterList> myOneParamList = new ThreadLocal<PyParameterList>(); // arglist with one arg, 'self' private ThreadLocal<PyParameterList> myTwoParamList = new ThreadLocal<PyParameterList>(); // arglist with two args, 'self' and 'value' @Override public void inspectionStarted(LocalInspectionToolSession session) { super.inspectionStarted(session); // save us continuous checks for level, module, stc final PsiFile psifile = session.getFile(); LanguageLevel level = null; if (psifile != null) { VirtualFile vfile = psifile.getVirtualFile(); if (vfile != null) level = LanguageLevel.forFile(vfile); } if (level == null) level = LanguageLevel.getDefault(); myLevel.set(level); // string classes final List<PyClass> string_classes = new ArrayList<PyClass>(2); final PyBuiltinCache builtins = PyBuiltinCache.getInstance(psifile); PyClass cls = builtins.getClass("str"); if (cls != null) string_classes.add(cls); cls = builtins.getClass("unicode"); if (cls != null) string_classes.add(cls); myStringClasses.set(string_classes); // reference signatures PyClass object_class = builtins.getClass("object"); if (object_class != null) { final PyFunction method_repr = object_class.findMethodByName("__repr__", false); if (method_repr != null) myOneParamList.set(method_repr.getParameterList()); final PyFunction method_delattr = object_class.findMethodByName("__delattr__", false); if (method_delattr != null) myTwoParamList.set(method_delattr.getParameterList()); } } private static final List<String> SUFFIXES = new ArrayList<String>(2); static { SUFFIXES.add("setter"); SUFFIXES.add("deleter"); } @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) { return new Visitor(holder); } public class Visitor extends PyInspectionVisitor { public Visitor(final ProblemsHolder holder) { super(holder); } @Override public void visitPyFile(PyFile node) { super.visitPyFile(node); } @Override public void visitPyClass(final PyClass node) { super.visitPyClass(node); // check property() and @property node.scanProperties(new Processor<Property>() { @Override public boolean process(Property property) { PyTargetExpression target = property.getDefinitionSite(); if (target != null) { // target = property(); args may be all funny PyCallExpression call = (PyCallExpression)target.findAssignedValue(); assert call != null : "Property has a null call assigned to it"; final PyArgumentList arglist = call.getArgumentList(); assert arglist != null : "Property call has null arglist"; PyArgumentList.AnalysisResult analysis = arglist.analyzeCall(); // we assume fget, fset, fdel, doc names for (Map.Entry<PyExpression, PyNamedParameter> entry: analysis.getPlainMappedParams().entrySet()) { final String param_name = entry.getValue().getName(); PyExpression argument = PyUtil.peelArgument(entry.getKey()); assert argument != null : "Parameter mapped to null argument"; Callable callable = null; if (argument instanceof PyReferenceExpression) { PsiElement resolved = ((PyReferenceExpression)argument).getReference().resolve(); if (resolved instanceof PyFunction) callable = (PyFunction)resolved; else if (resolved instanceof PyLambdaExpression) callable = (PyLambdaExpression)resolved; else { reportStrangeArg(resolved, argument); continue; } } else if (argument instanceof PyLambdaExpression) callable = (PyLambdaExpression)argument; else if (! "doc".equals(param_name)) { reportStrangeArg(argument, argument); continue; } if ("fget".equals(param_name)) checkGetter(callable, argument); else if ("fset".equals(param_name)) checkSetter(callable, argument); else if ("fdel".equals(param_name)) checkDeleter(callable, argument); else if ("doc".equals(param_name)) { PyType type = argument.getType(TypeEvalContext.fast()); if (! (type instanceof PyClassType && myStringClasses.get().contains(((PyClassType)type).getPyClass()))) { registerProblem(argument, PyBundle.message("INSP.doc.param.should.be.str")); } } } } else { // @property; we only check getter, others are checked by visitPyFunction // getter is always present with this form final PyFunction function = property.getGetter().valueOrNull(); checkGetter(function, getFunctionMarkingElement(function)); } return false; // always want more } }, false); } void reportStrangeArg(PsiElement resolved, PsiElement being_checked) { if (! PyUtil.instanceOf(resolved, PySubscriptionExpression.class, PyNoneLiteralExpression.class)) { registerProblem(being_checked, PyBundle.message("INSP.strange.arg.want.callable")); } } @Override public void visitPyFunction(PyFunction node) { super.visitPyFunction(node); if (myLevel.get().isAtLeast(LanguageLevel.PYTHON26)) { // check @foo.setter and @foo.deleter PyClass cls = node.getContainingClass(); if (cls != null) { final PyDecoratorList decos = node.getDecoratorList(); if (decos != null) { String name = node.getName(); for (PyDecorator deco : decos.getDecorators()) { final PyQualifiedName q_name = deco.getQualifiedName(); if (q_name != null) { List<String> name_parts = q_name.getComponents(); if (name_parts.size() == 2) { final int suffix_index = SUFFIXES.indexOf(name_parts.get(1)); if (suffix_index >= 0) { if (Comparing.equal(name, name_parts.get(0))) { // names are ok, what about signatures? PsiElement markable = getFunctionMarkingElement(node); if (suffix_index == 0) checkSetter(node, markable); else checkDeleter(node, markable); } else { registerProblem(deco, PyBundle.message("INSP.func.property.name.mismatch")); } } } } } } } } } @Nullable private PsiElement getFunctionMarkingElement(PyFunction node) { if (node == null) return null; final ASTNode name_node = node.getNameNode(); PsiElement markable = node; if (name_node != null) markable = name_node.getPsi(); return markable; } private void checkGetter(Callable callable, PsiElement being_checked) { if (callable != null) { checkOneParameter(callable, being_checked, true); checkReturnValueAllowed(callable, being_checked, true, PyBundle.message("INSP.getter.return.smth")); } } private void checkSetter(Callable callable, PsiElement being_checked) { if (callable != null) { // signature: at least two params, more optionals ok; first arg 'self' final PyParameterList param_list = callable.getParameterList(); final PyParameterList two_parameters_list = myTwoParamList.get(); if (two_parameters_list != null && !param_list.isCompatibleTo(two_parameters_list)) { registerProblem(being_checked, PyBundle.message("INSP.setter.signature.advice")); } checkForSelf(param_list); // no explicit return type checkReturnValueAllowed(callable, being_checked, false, PyBundle.message("INSP.setter.should.not.return")); } } private void checkDeleter(Callable callable, PsiElement being_checked) { if (callable != null) { checkOneParameter(callable, being_checked, false); checkReturnValueAllowed(callable, being_checked, false, PyBundle.message("INSP.deleter.should.not.return")); } } private void checkOneParameter(Callable callable, PsiElement being_checked, boolean is_getter) { final PyParameterList param_list = callable.getParameterList(); final PyParameterList one_parameter_list = myOneParamList.get(); if (one_parameter_list != null && ! param_list.isCompatibleTo(one_parameter_list)) { if (is_getter) registerProblem(being_checked, PyBundle.message("INSP.getter.signature.advice")); else registerProblem(being_checked, PyBundle.message("INSP.deleter.signature.advice")); } checkForSelf(param_list); } private void checkForSelf(PyParameterList param_list) { PyParameter[] parameters = param_list.getParameters(); if (parameters.length > 0 && ! PyNames.CANONICAL_SELF.equals(parameters[0].getName())) { registerProblem( parameters[0], PyBundle.message("INSP.accessor.first.param.is.$0", PyNames.CANONICAL_SELF), ProblemHighlightType.INFO, null, new RenameParameterQuickFix(PyNames.CANONICAL_SELF)); } } private void checkReturnValueAllowed(Callable callable, PsiElement being_checked, boolean allowed, String message) { PyType type = callable.getReturnType(); if (!allowed ^ (type instanceof PyNoneType)) { registerProblem(being_checked, message); } } } }
python/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java
package com.jetbrains.python.inspections; import com.intellij.codeInspection.LocalInspectionToolSession; import com.intellij.codeInspection.ProblemHighlightType; import com.intellij.codeInspection.ProblemsHolder; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiFile; import com.intellij.util.Processor; import com.jetbrains.python.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.actions.RenameParameterQuickFix; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.impl.PyQualifiedName; import com.jetbrains.python.psi.types.PyClassType; import com.jetbrains.python.psi.types.PyNoneType; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Checks that arguments to property() and @property and friends are ok. * <br/> * User: dcheryasov * Date: Jun 30, 2010 2:53:05 PM */ public class PyPropertyDefinitionInspection extends PyInspection { @Nls @NotNull public String getDisplayName() { return PyBundle.message("INSP.NAME.property.definition"); } private ThreadLocal<LanguageLevel> myLevel = new ThreadLocal<LanguageLevel>(); private ThreadLocal<List<PyClass>> myStringClasses = new ThreadLocal<List<PyClass>>(); private ThreadLocal<PyParameterList> myOneParamList = new ThreadLocal<PyParameterList>(); // arglist with one arg, 'self' private ThreadLocal<PyParameterList> myTwoParamList = new ThreadLocal<PyParameterList>(); // arglist with two args, 'self' and 'value' @Override public void inspectionStarted(LocalInspectionToolSession session) { super.inspectionStarted(session); // save us continuous checks for level, module, stc final PsiFile psifile = session.getFile(); LanguageLevel level = null; if (psifile != null) { VirtualFile vfile = psifile.getVirtualFile(); if (vfile != null) level = LanguageLevel.forFile(vfile); } if (level == null) level = LanguageLevel.getDefault(); myLevel.set(level); // string classes final List<PyClass> string_classes = new ArrayList<PyClass>(2); final PyBuiltinCache builtins = PyBuiltinCache.getInstance(psifile); PyClass cls = builtins.getClass("str"); if (cls != null) string_classes.add(cls); cls = builtins.getClass("unicode"); if (cls != null) string_classes.add(cls); myStringClasses.set(string_classes); // reference signatures PyClass object_class = builtins.getClass("object"); if (object_class != null) { final PyFunction method_repr = object_class.findMethodByName("__repr__", false); if (method_repr != null) myOneParamList.set(method_repr.getParameterList()); final PyFunction method_delattr = object_class.findMethodByName("__delattr__", false); if (method_delattr != null) myTwoParamList.set(method_delattr.getParameterList()); } } private static final List<String> SUFFIXES = new ArrayList<String>(2); static { SUFFIXES.add("setter"); SUFFIXES.add("deleter"); } @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) { return new Visitor(holder); } public class Visitor extends PyInspectionVisitor { public Visitor(final ProblemsHolder holder) { super(holder); } @Override public void visitPyFile(PyFile node) { super.visitPyFile(node); } @Override public void visitPyClass(final PyClass node) { super.visitPyClass(node); // check property() and @property node.scanProperties(new Processor<Property>() { @Override public boolean process(Property property) { PyTargetExpression target = property.getDefinitionSite(); if (target != null) { // target = property(); args may be all funny PyCallExpression call = (PyCallExpression)target.findAssignedValue(); assert call != null : "Property has a null call assigned to it"; final PyArgumentList arglist = call.getArgumentList(); assert arglist != null : "Property call has null arglist"; PyArgumentList.AnalysisResult analysis = arglist.analyzeCall(); // we assume fget, fset, fdel, doc names for (Map.Entry<PyExpression, PyNamedParameter> entry: analysis.getPlainMappedParams().entrySet()) { final String param_name = entry.getValue().getName(); PyExpression argument = PyUtil.peelArgument(entry.getKey()); assert argument != null : "Parameter mapped to null argument"; Callable callable = null; if (argument instanceof PyReferenceExpression) { PsiElement resolved = ((PyReferenceExpression)argument).getReference().resolve(); if (resolved instanceof PyFunction) callable = (PyFunction)resolved; else if (resolved instanceof PyLambdaExpression) callable = (PyLambdaExpression)resolved; else { reportStrangeArg(resolved, argument); continue; } } else if (argument instanceof PyLambdaExpression) callable = (PyLambdaExpression)argument; else if (! "doc".equals(param_name)) { reportStrangeArg(argument, argument); continue; } if ("fget".equals(param_name)) checkGetter(callable, argument); else if ("fset".equals(param_name)) checkSetter(callable, argument); else if ("fdel".equals(param_name)) checkDeleter(callable, argument); else if ("doc".equals(param_name)) { PyType type = argument.getType(TypeEvalContext.fast()); if (! (type instanceof PyClassType && myStringClasses.get().contains(((PyClassType)type).getPyClass()))) { registerProblem(argument, PyBundle.message("INSP.doc.param.should.be.str")); } } } } else { // @property; we only check getter, others are checked by visitPyFunction // getter is always present with this form final PyFunction function = property.getGetter().valueOrNull(); checkGetter(function, getFunctionMarkingElement(function)); } return false; // always want more } }, false); } void reportStrangeArg(PsiElement resolved, PsiElement being_checked) { if (! PyUtil.instanceOf(resolved, PySubscriptionExpression.class, PyNoneLiteralExpression.class)) { registerProblem(being_checked, PyBundle.message("INSP.strange.arg.want.callable")); } } @Override public void visitPyFunction(PyFunction node) { super.visitPyFunction(node); if (myLevel.get().isAtLeast(LanguageLevel.PYTHON26)) { // check @foo.setter and @foo.deleter PyClass cls = node.getContainingClass(); if (cls != null) { final PyDecoratorList decos = node.getDecoratorList(); if (decos != null) { String name = node.getName(); for (PyDecorator deco : decos.getDecorators()) { final PyQualifiedName q_name = deco.getQualifiedName(); if (q_name != null) { List<String> name_parts = q_name.getComponents(); if (name_parts.size() == 2) { final int suffix_index = SUFFIXES.indexOf(name_parts.get(1)); if (suffix_index >= 0) { if (Comparing.equal(name, name_parts.get(0))) { // names are ok, what about signatures? PsiElement markable = getFunctionMarkingElement(node); if (suffix_index == 0) checkSetter(node, markable); else checkDeleter(node, markable); } else { registerProblem(deco, PyBundle.message("INSP.func.property.name.mismatch")); } } } } } } } } } @Nullable private PsiElement getFunctionMarkingElement(PyFunction node) { if (node == null) return null; final ASTNode name_node = node.getNameNode(); PsiElement markable = node; if (name_node != null) markable = name_node.getPsi(); return markable; } private void checkGetter(Callable callable, PsiElement being_checked) { if (callable != null) { checkOneParameter(callable, being_checked, true); checkReturnValueAllowed(callable, being_checked, true, PyBundle.message("INSP.getter.return.smth")); } } private void checkSetter(Callable callable, PsiElement being_checked) { if (callable != null) { // signature: at least two params, more optionals ok; first arg 'self' final PyParameterList param_list = callable.getParameterList(); if (myTwoParamList != null && ! param_list.isCompatibleTo(myTwoParamList.get())) { registerProblem(being_checked, PyBundle.message("INSP.setter.signature.advice")); } checkForSelf(param_list); // no explicit return type checkReturnValueAllowed(callable, being_checked, false, PyBundle.message("INSP.setter.should.not.return")); } } private void checkDeleter(Callable callable, PsiElement being_checked) { if (callable != null) { checkOneParameter(callable, being_checked, false); checkReturnValueAllowed(callable, being_checked, false, PyBundle.message("INSP.deleter.should.not.return")); } } private void checkOneParameter(Callable callable, PsiElement being_checked, boolean is_getter) { final PyParameterList param_list = callable.getParameterList(); if (myOneParamList != null && ! param_list.isCompatibleTo(myOneParamList.get())) { if (is_getter) registerProblem(being_checked, PyBundle.message("INSP.getter.signature.advice")); else registerProblem(being_checked, PyBundle.message("INSP.deleter.signature.advice")); } checkForSelf(param_list); } private void checkForSelf(PyParameterList param_list) { PyParameter[] parameters = param_list.getParameters(); if (parameters.length > 0 && ! PyNames.CANONICAL_SELF.equals(parameters[0].getName())) { registerProblem( parameters[0], PyBundle.message("INSP.accessor.first.param.is.$0", PyNames.CANONICAL_SELF), ProblemHighlightType.INFO, null, new RenameParameterQuickFix(PyNames.CANONICAL_SELF)); } } private void checkReturnValueAllowed(Callable callable, PsiElement being_checked, boolean allowed, String message) { PyType type = callable.getReturnType(); if (!allowed ^ (type instanceof PyNoneType)) { registerProblem(being_checked, message); } } } }
Fix edge case NPEs.
python/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java
Fix edge case NPEs.
<ide><path>ython/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java <ide> if (callable != null) { <ide> // signature: at least two params, more optionals ok; first arg 'self' <ide> final PyParameterList param_list = callable.getParameterList(); <del> if (myTwoParamList != null && ! param_list.isCompatibleTo(myTwoParamList.get())) { <add> final PyParameterList two_parameters_list = myTwoParamList.get(); <add> if (two_parameters_list != null && !param_list.isCompatibleTo(two_parameters_list)) { <ide> registerProblem(being_checked, PyBundle.message("INSP.setter.signature.advice")); <ide> } <ide> checkForSelf(param_list); <ide> <ide> private void checkOneParameter(Callable callable, PsiElement being_checked, boolean is_getter) { <ide> final PyParameterList param_list = callable.getParameterList(); <del> if (myOneParamList != null && ! param_list.isCompatibleTo(myOneParamList.get())) { <add> final PyParameterList one_parameter_list = myOneParamList.get(); <add> if (one_parameter_list != null && ! param_list.isCompatibleTo(one_parameter_list)) { <ide> if (is_getter) registerProblem(being_checked, PyBundle.message("INSP.getter.signature.advice")); <ide> else registerProblem(being_checked, PyBundle.message("INSP.deleter.signature.advice")); <ide> }
Java
apache-2.0
4461159b6c7415db48d9c5353e29a45c61a07e5b
0
3-Round-Stones/callimachus,edwardsph/callimachus,3-Round-Stones/callimachus,jimmccusker/callimachus,edwardsph/callimachus,jimmccusker/callimachus,jimmccusker/callimachus,3-Round-Stones/callimachus,3-Round-Stones/callimachus,edwardsph/callimachus,Thellmann/callimachus,edwardsph/callimachus,3-Round-Stones/callimachus,jimmccusker/callimachus,Thellmann/callimachus,jimmccusker/callimachus,Thellmann/callimachus,Thellmann/callimachus,edwardsph/callimachus,3-Round-Stones/callimachus,jimmccusker/callimachus,edwardsph/callimachus,Thellmann/callimachus,Thellmann/callimachus
package org.callimachusproject.xml; import info.aduna.net.ParsedURI; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import net.sf.saxon.lib.ModuleURIResolver; import net.sf.saxon.trans.XPathException; import org.apache.http.client.HttpClient; import org.callimachusproject.client.HttpUriClient; import org.callimachusproject.client.HttpUriEntity; import org.callimachusproject.server.exceptions.NotFound; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; public class InputSourceResolver implements EntityResolver, URIResolver, ModuleURIResolver { private static final Pattern CHARSET = Pattern .compile("\\bcharset\\s*=\\s*([\\w-:]+)"); private final HttpUriClient client; private final String accept; public InputSourceResolver(String accept, final HttpClient client) { this.accept = accept; this.client = new HttpUriClient() { protected HttpClient getDelegate() { return client; } }; } @Override public StreamSource resolve(String href, String base) throws TransformerException { try { InputSource input = resolve(resolveURI(href, base)); if (input == null) return null; InputStream in = input.getByteStream(); if (in != null) { if (input.getSystemId() == null) return new StreamSource(in); return new StreamSource(in, input.getSystemId()); } Reader reader = input.getCharacterStream(); if (reader != null) { if (input.getSystemId() == null) return new StreamSource(reader); return new StreamSource(reader, input.getSystemId()); } if (input.getSystemId() == null) return new StreamSource(); return new StreamSource(input.getSystemId()); } catch (IOException e) { throw new TransformerException(e); } } @Override public StreamSource[] resolve(String moduleURI, String baseURI, String[] locations) throws XPathException { List<StreamSource> list = new ArrayList<StreamSource>(); try { if (locations == null || locations.length == 0) { StreamSource resolved = resolve(moduleURI, baseURI); if (resolved == null) { XPathException se = new XPathException( "Cannot locate module for namespace " + moduleURI); se.setErrorCode("XQST0059"); se.setIsStaticError(true); throw se; } list.add(resolved); } else { for (String location : locations) { StreamSource resolved = resolve(location, baseURI); if (resolved == null) { XPathException se = new XPathException( "Could not load module at " + location); se.setErrorCode("XQST0059"); se.setIsStaticError(true); throw se; } list.add(resolved); } } } catch (XPathException e) { throw e; } catch (TransformerException e) { throw new XPathException(e); } return list.toArray(new StreamSource[list.size()]); } @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException { return resolve(systemId); } public InputSource resolve(String systemId) throws IOException { if (systemId.startsWith("http:") || systemId.startsWith("https:")) return resolveHttp(systemId); return resolveURL(systemId); } private String resolveURI(String href, String base) { ParsedURI parsed = null; if (href != null) { parsed = new ParsedURI(href); if (parsed.isAbsolute()) return href; } ParsedURI abs = null; if (base != null) { abs = new ParsedURI(base); } if (parsed != null) { if (abs == null) { abs = parsed; } else { abs = abs.resolve(parsed); } } return abs.toString(); } /** * returns null for 404 resources. */ private InputSource resolveHttp(String systemId) throws IOException { try { HttpUriEntity entity = client.getEntity(systemId, getAcceptHeader()); if (entity == null) return null; InputStream in = entity.getContent(); String type = entity.getContentType().getValue(); systemId = entity.getSystemId(); return create(type, in, systemId); } catch (NotFound e) { return null; } } /** * returns null for 404 resources. */ private InputSource resolveURL(String systemId) throws IOException { URLConnection con = new URL(systemId).openConnection(); con.addRequestProperty("Accept", getAcceptHeader()); con.addRequestProperty("Accept-Encoding", "gzip"); try { String base = con.getURL().toExternalForm(); String type = con.getContentType(); String encoding = con.getHeaderField("Content-Encoding"); InputStream in = con.getInputStream(); if (encoding != null && encoding.contains("gzip")) { in = new GZIPInputStream(in); } return create(type, in, base); } catch (FileNotFoundException e) { return null; } } private String getAcceptHeader() { return accept; } private InputSource create(String type, InputStream in, String systemId) throws UnsupportedEncodingException { Matcher m = CHARSET.matcher(type); if (m.find()) { Reader reader = new InputStreamReader(in, m.group(1)); InputSource source = new InputSource(reader); if (systemId != null) { source.setSystemId(systemId); } return source; } InputSource source = new InputSource(in); if (systemId != null) { source.setSystemId(systemId); } return source; } }
src/org/callimachusproject/xml/InputSourceResolver.java
package org.callimachusproject.xml; import info.aduna.net.ParsedURI; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamSource; import net.sf.saxon.lib.ModuleURIResolver; import net.sf.saxon.trans.XPathException; import org.apache.http.client.HttpClient; import org.callimachusproject.client.HttpUriClient; import org.callimachusproject.client.HttpUriEntity; import org.callimachusproject.server.exceptions.NotFound; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; public class InputSourceResolver implements EntityResolver, URIResolver, ModuleURIResolver { private static final Pattern CHARSET = Pattern .compile("\\bcharset\\s*=\\s*([\\w-:]+)"); private final HttpUriClient client; private final String accept; public InputSourceResolver(String accept, final HttpClient client) { this.accept = accept; this.client = new HttpUriClient() { protected HttpClient getDelegate() { return client; } }; } @Override public StreamSource resolve(String href, String base) throws TransformerException { try { InputSource input = resolve(resolveURI(href, base)); if (input == null) return null; InputStream in = input.getByteStream(); if (in != null) { if (input.getSystemId() == null) return new StreamSource(in); return new StreamSource(in, input.getSystemId()); } Reader reader = input.getCharacterStream(); if (reader != null) { if (input.getSystemId() == null) return new StreamSource(reader); return new StreamSource(reader, input.getSystemId()); } if (input.getSystemId() == null) return new StreamSource(); return new StreamSource(input.getSystemId()); } catch (IOException e) { throw new TransformerException(e); } } @Override public StreamSource[] resolve(String moduleURI, String baseURI, String[] locations) throws XPathException { List<StreamSource> list = new ArrayList<StreamSource>(); try { if (locations == null || locations.length == 0) { list.add(resolve(moduleURI, baseURI)); } else { for (String location : locations) { list.add(resolve(location, baseURI)); } } } catch (XPathException e) { throw e; } catch (TransformerException e) { throw new XPathException(e); } return list.toArray(new StreamSource[list.size()]); } @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException { return resolve(systemId); } public InputSource resolve(String systemId) throws IOException { if (systemId.startsWith("http:") || systemId.startsWith("https:")) return resolveHttp(systemId); return resolveURL(systemId); } private String resolveURI(String href, String base) { ParsedURI parsed = null; if (href != null) { parsed = new ParsedURI(href); if (parsed.isAbsolute()) return href; } ParsedURI abs = null; if (base != null) { abs = new ParsedURI(base); } if (parsed != null) { if (abs == null) { abs = parsed; } else { abs = abs.resolve(parsed); } } return abs.toString(); } /** * returns null for 404 resources. */ private InputSource resolveHttp(String systemId) throws IOException { try { HttpUriEntity entity = client.getEntity(systemId, getAcceptHeader()); if (entity == null) return null; InputStream in = entity.getContent(); String type = entity.getContentType().getValue(); systemId = entity.getSystemId(); return create(type, in, systemId); } catch (NotFound e) { return null; } } /** * returns null for 404 resources. */ private InputSource resolveURL(String systemId) throws IOException { URLConnection con = new URL(systemId).openConnection(); con.addRequestProperty("Accept", getAcceptHeader()); con.addRequestProperty("Accept-Encoding", "gzip"); try { String base = con.getURL().toExternalForm(); String type = con.getContentType(); String encoding = con.getHeaderField("Content-Encoding"); InputStream in = con.getInputStream(); if (encoding != null && encoding.contains("gzip")) { in = new GZIPInputStream(in); } return create(type, in, base); } catch (FileNotFoundException e) { return null; } } private String getAcceptHeader() { return accept; } private InputSource create(String type, InputStream in, String systemId) throws UnsupportedEncodingException { Matcher m = CHARSET.matcher(type); if (m.find()) { Reader reader = new InputStreamReader(in, m.group(1)); InputSource source = new InputSource(reader); if (systemId != null) { source.setSystemId(systemId); } return source; } InputSource source = new InputSource(in); if (systemId != null) { source.setSystemId(systemId); } return source; } }
Throw error if XQuery module cannot be found
src/org/callimachusproject/xml/InputSourceResolver.java
Throw error if XQuery module cannot be found
<ide><path>rc/org/callimachusproject/xml/InputSourceResolver.java <ide> List<StreamSource> list = new ArrayList<StreamSource>(); <ide> try { <ide> if (locations == null || locations.length == 0) { <del> list.add(resolve(moduleURI, baseURI)); <add> StreamSource resolved = resolve(moduleURI, baseURI); <add> if (resolved == null) { <add> XPathException se = new XPathException( <add> "Cannot locate module for namespace " + moduleURI); <add> se.setErrorCode("XQST0059"); <add> se.setIsStaticError(true); <add> throw se; <add> } <add> list.add(resolved); <ide> } else { <ide> for (String location : locations) { <del> list.add(resolve(location, baseURI)); <add> StreamSource resolved = resolve(location, baseURI); <add> if (resolved == null) { <add> XPathException se = new XPathException( <add> "Could not load module at " + location); <add> se.setErrorCode("XQST0059"); <add> se.setIsStaticError(true); <add> throw se; <add> } <add> list.add(resolved); <ide> } <ide> } <ide> } catch (XPathException e) {
JavaScript
mit
130d179a128f284eef7581e0f84451931b858cdf
0
hemerajs/hemera,hemerajs/hemera
'use strict' /** * Copyright 2016-present, Dustin Deus ([email protected]) * All rights reserved. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. * */ const Errors = require('./errors') /** * @class ExtensionManager */ class ExtensionManager { constructor() { this._stack = [] this._types = [ 'onClientPreRequest', 'onClientPostRequest', 'onServerPreHandler', 'onServerPreRequest', 'onServerPreResponse' ] this.onClientPreRequest = [] this.onClientPostRequest = [] this.onServerPreHandler = [] this.onServerPreRequest = [] this.onServerPreResponse = [] } /** * * * @param {any} handler * * @memberof Extension */ _add(type, handler) { if (this._types.indexOf(type) === -1) { let error = new Errors.HemeraError('Extension type is unknown', { type, handler }) throw error } this[type].push(handler) } /** * * * @param {any} handler * * @memberOf Extension */ add(type, handler) { if (Array.isArray(handler)) { handler.forEach(h => this._add(type, h)) } else { this._add(type, handler) } } /** * * @param {*} e */ static build(e) { const extensions = new ExtensionManager() extensions.onClientPreRequest = e.onClientPreRequest.slice() extensions.onClientPostRequest = e.onClientPostRequest.slice() extensions.onServerPreHandler = e.onServerPreHandler.slice() extensions.onServerPreRequest = e.onServerPreRequest.slice() extensions.onServerPreResponse = e.onServerPreResponse.slice() return extensions } } module.exports = ExtensionManager
packages/hemera/lib/extensionManager.js
'use strict' /** * Copyright 2016-present, Dustin Deus ([email protected]) * All rights reserved. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. * */ const Errors = require('./errors') /** * @class ExtensionManager */ class ExtensionManager { constructor() { this._stack = [] this._types = [ 'onClientPreRequest', 'onClientPostRequest', 'onServerPreHandler', 'onServerPreRequest', 'onServerPreResponse' ] this.onClientPreRequest = [] this.onClientPostRequest = [] this.onServerPreHandler = [] this.onServerPreRequest = [] this.onServerPreResponse = [] } /** * * * @param {any} handler * * @memberof Extension */ _add(type, handler) { if (this._types.indexOf(type) === -1) { let error = new Errors.HemeraError('Extension type is unknown', { type, handler }) throw error } this[type].push(handler) } /** * * * @param {any} handler * * @memberOf Extension */ add(type, handler) { if (Array.isArray(handler)) { handler.forEach(h => this._add(type, h)) } else { this._add(type, handler) } } /** * * @param {*} e */ static build(e) { const extensions = new ExtensionManager() extensions.onClientPreRequest = e.onClientPreRequest.slice() extensions.onClientPostRequest = e.onClientPostRequest.slice() extensions.onServerPreHandler = e.onServerPreHandler.slice() extensions.onServerPreRequest = e.onServerPreRequest.slice() extensions.onServerPreResponse = e.onServerPreResponse.slice() return extensions } } module.exports = ExtensionManager
[ci skip] newline
packages/hemera/lib/extensionManager.js
[ci skip] newline
<ide><path>ackages/hemera/lib/extensionManager.js <ide> this._add(type, handler) <ide> } <ide> } <add> <ide> /** <ide> * <ide> * @param {*} e
Java
apache-2.0
aa0c34f66ba727cb353739c95107ca67d81de896
0
Xhanim/libgdx,toa5/libgdx,srwonka/libGdx,Badazdz/libgdx,gouessej/libgdx,samskivert/libgdx,toa5/libgdx,JFixby/libgdx,alex-dorokhov/libgdx,kagehak/libgdx,gdos/libgdx,Dzamir/libgdx,kotcrab/libgdx,tommyettinger/libgdx,309746069/libgdx,SidneyXu/libgdx,tell10glu/libgdx,zommuter/libgdx,sarkanyi/libgdx,SidneyXu/libgdx,haedri/libgdx-1,anserran/libgdx,andyvand/libgdx,UnluckyNinja/libgdx,luischavez/libgdx,azakhary/libgdx,alireza-hosseini/libgdx,sinistersnare/libgdx,ryoenji/libgdx,stickyd/libgdx,ThiagoGarciaAlves/libgdx,ryoenji/libgdx,kzganesan/libgdx,MathieuDuponchelle/gdx,tell10glu/libgdx,ThiagoGarciaAlves/libgdx,nudelchef/libgdx,Xhanim/libgdx,MadcowD/libgdx,billgame/libgdx,ztv/libgdx,yangweigbh/libgdx,revo09/libgdx,bgroenks96/libgdx,JDReutt/libgdx,josephknight/libgdx,SidneyXu/libgdx,czyzby/libgdx,Xhanim/libgdx,designcrumble/libgdx,Deftwun/libgdx,xranby/libgdx,Dzamir/libgdx,UnluckyNinja/libgdx,jsjolund/libgdx,stickyd/libgdx,Thotep/libgdx,collinsmith/libgdx,ya7lelkom/libgdx,djom20/libgdx,titovmaxim/libgdx,designcrumble/libgdx,hyvas/libgdx,tell10glu/libgdx,tommyettinger/libgdx,BlueRiverInteractive/libgdx,xoppa/libgdx,MetSystem/libgdx,youprofit/libgdx,Wisienkas/libgdx,josephknight/libgdx,tell10glu/libgdx,jberberick/libgdx,nrallakis/libgdx,ninoalma/libgdx,tommyettinger/libgdx,Heart2009/libgdx,MovingBlocks/libgdx,andyvand/libgdx,zommuter/libgdx,Xhanim/libgdx,luischavez/libgdx,saltares/libgdx,samskivert/libgdx,lordjone/libgdx,Dzamir/libgdx,nave966/libgdx,kzganesan/libgdx,hyvas/libgdx,junkdog/libgdx,sinistersnare/libgdx,josephknight/libgdx,saqsun/libgdx,309746069/libgdx,ya7lelkom/libgdx,PedroRomanoBarbosa/libgdx,saqsun/libgdx,realitix/libgdx,tommycli/libgdx,toa5/libgdx,noelsison2/libgdx,TheAks999/libgdx,Arcnor/libgdx,stickyd/libgdx,TheAks999/libgdx,billgame/libgdx,samskivert/libgdx,yangweigbh/libgdx,Senth/libgdx,jasonwee/libgdx,nooone/libgdx,bladecoder/libgdx,Zonglin-Li6565/libgdx,srwonka/libGdx,zommuter/libgdx,jsjolund/libgdx,EsikAntony/libgdx,MovingBlocks/libgdx,haedri/libgdx-1,MovingBlocks/libgdx,revo09/libgdx,JDReutt/libgdx,Badazdz/libgdx,djom20/libgdx,MetSystem/libgdx,bsmr-java/libgdx,NathanSweet/libgdx,czyzby/libgdx,nave966/libgdx,NathanSweet/libgdx,gdos/libgdx,mumer92/libgdx,saltares/libgdx,revo09/libgdx,js78/libgdx,ninoalma/libgdx,Badazdz/libgdx,bgroenks96/libgdx,stickyd/libgdx,FredGithub/libgdx,js78/libgdx,nudelchef/libgdx,ninoalma/libgdx,hyvas/libgdx,UnluckyNinja/libgdx,xoppa/libgdx,tommycli/libgdx,hyvas/libgdx,shiweihappy/libgdx,saqsun/libgdx,toloudis/libgdx,nave966/libgdx,czyzby/libgdx,gouessej/libgdx,gouessej/libgdx,xranby/libgdx,jasonwee/libgdx,gdos/libgdx,sjosegarcia/libgdx,youprofit/libgdx,ryoenji/libgdx,Gliby/libgdx,realitix/libgdx,codepoke/libgdx,ztv/libgdx,xranby/libgdx,alex-dorokhov/libgdx,Xhanim/libgdx,anserran/libgdx,Zonglin-Li6565/libgdx,youprofit/libgdx,ya7lelkom/libgdx,BlueRiverInteractive/libgdx,jberberick/libgdx,luischavez/libgdx,xranby/libgdx,mumer92/libgdx,copystudy/libgdx,ninoalma/libgdx,gf11speed/libgdx,thepullman/libgdx,xpenatan/libgdx-LWJGL3,Gliby/libgdx,bsmr-java/libgdx,fwolff/libgdx,kagehak/libgdx,EsikAntony/libgdx,UnluckyNinja/libgdx,haedri/libgdx-1,NathanSweet/libgdx,codepoke/libgdx,nrallakis/libgdx,JFixby/libgdx,alex-dorokhov/libgdx,basherone/libgdxcn,Thotep/libgdx,snovak/libgdx,tell10glu/libgdx,toloudis/libgdx,collinsmith/libgdx,srwonka/libGdx,sjosegarcia/libgdx,xoppa/libgdx,Heart2009/libgdx,FyiurAmron/libgdx,NathanSweet/libgdx,Badazdz/libgdx,nelsonsilva/libgdx,alireza-hosseini/libgdx,shiweihappy/libgdx,kotcrab/libgdx,FyiurAmron/libgdx,309746069/libgdx,petugez/libgdx,gouessej/libgdx,MikkelTAndersen/libgdx,Thotep/libgdx,zhimaijoy/libgdx,EsikAntony/libgdx,Dzamir/libgdx,KrisLee/libgdx,libgdx/libgdx,js78/libgdx,anserran/libgdx,gdos/libgdx,josephknight/libgdx,nelsonsilva/libgdx,hyvas/libgdx,1yvT0s/libgdx,bsmr-java/libgdx,Wisienkas/libgdx,MadcowD/libgdx,davebaol/libgdx,designcrumble/libgdx,azakhary/libgdx,billgame/libgdx,nooone/libgdx,KrisLee/libgdx,1yvT0s/libgdx,bladecoder/libgdx,stinsonga/libgdx,alex-dorokhov/libgdx,Gliby/libgdx,haedri/libgdx-1,kzganesan/libgdx,katiepino/libgdx,zommuter/libgdx,codepoke/libgdx,Gliby/libgdx,FredGithub/libgdx,bsmr-java/libgdx,Xhanim/libgdx,shiweihappy/libgdx,SidneyXu/libgdx,josephknight/libgdx,ya7lelkom/libgdx,antag99/libgdx,tommycli/libgdx,sjosegarcia/libgdx,xpenatan/libgdx-LWJGL3,zommuter/libgdx,JDReutt/libgdx,ttencate/libgdx,saltares/libgdx,Senth/libgdx,zhimaijoy/libgdx,Dzamir/libgdx,collinsmith/libgdx,MadcowD/libgdx,sinistersnare/libgdx,azakhary/libgdx,fiesensee/libgdx,BlueRiverInteractive/libgdx,cypherdare/libgdx,ttencate/libgdx,titovmaxim/libgdx,Zonglin-Li6565/libgdx,Heart2009/libgdx,gouessej/libgdx,Senth/libgdx,MathieuDuponchelle/gdx,ninoalma/libgdx,fiesensee/libgdx,FredGithub/libgdx,snovak/libgdx,nave966/libgdx,MetSystem/libgdx,nudelchef/libgdx,Zonglin-Li6565/libgdx,Wisienkas/libgdx,1yvT0s/libgdx,cypherdare/libgdx,JDReutt/libgdx,firefly2442/libgdx,antag99/libgdx,Zonglin-Li6565/libgdx,ttencate/libgdx,titovmaxim/libgdx,revo09/libgdx,collinsmith/libgdx,andyvand/libgdx,ryoenji/libgdx,MadcowD/libgdx,kagehak/libgdx,BlueRiverInteractive/libgdx,gf11speed/libgdx,fwolff/libgdx,katiepino/libgdx,copystudy/libgdx,ztv/libgdx,MadcowD/libgdx,anserran/libgdx,billgame/libgdx,shiweihappy/libgdx,TheAks999/libgdx,nudelchef/libgdx,sjosegarcia/libgdx,yangweigbh/libgdx,luischavez/libgdx,noelsison2/libgdx,curtiszimmerman/libgdx,ryoenji/libgdx,Zomby2D/libgdx,Zomby2D/libgdx,shiweihappy/libgdx,sinistersnare/libgdx,antag99/libgdx,davebaol/libgdx,ricardorigodon/libgdx,MathieuDuponchelle/gdx,FyiurAmron/libgdx,Xhanim/libgdx,xpenatan/libgdx-LWJGL3,noelsison2/libgdx,UnluckyNinja/libgdx,alex-dorokhov/libgdx,tell10glu/libgdx,fiesensee/libgdx,nrallakis/libgdx,anserran/libgdx,srwonka/libGdx,libgdx/libgdx,junkdog/libgdx,MovingBlocks/libgdx,noelsison2/libgdx,Deftwun/libgdx,andyvand/libgdx,djom20/libgdx,Zomby2D/libgdx,JDReutt/libgdx,ztv/libgdx,designcrumble/libgdx,ricardorigodon/libgdx,alireza-hosseini/libgdx,tommycli/libgdx,ThiagoGarciaAlves/libgdx,jasonwee/libgdx,Heart2009/libgdx,nelsonsilva/libgdx,anserran/libgdx,haedri/libgdx-1,flaiker/libgdx,designcrumble/libgdx,zhimaijoy/libgdx,zhimaijoy/libgdx,Dzamir/libgdx,Zonglin-Li6565/libgdx,billgame/libgdx,toloudis/libgdx,Thotep/libgdx,haedri/libgdx-1,czyzby/libgdx,xoppa/libgdx,ya7lelkom/libgdx,codepoke/libgdx,lordjone/libgdx,flaiker/libgdx,firefly2442/libgdx,js78/libgdx,MathieuDuponchelle/gdx,saqsun/libgdx,nave966/libgdx,saqsun/libgdx,designcrumble/libgdx,xranby/libgdx,Wisienkas/libgdx,josephknight/libgdx,Deftwun/libgdx,shiweihappy/libgdx,snovak/libgdx,noelsison2/libgdx,samskivert/libgdx,thepullman/libgdx,katiepino/libgdx,ninoalma/libgdx,firefly2442/libgdx,kotcrab/libgdx,ThiagoGarciaAlves/libgdx,tommyettinger/libgdx,SidneyXu/libgdx,FyiurAmron/libgdx,alex-dorokhov/libgdx,yangweigbh/libgdx,sarkanyi/libgdx,josephknight/libgdx,KrisLee/libgdx,Gliby/libgdx,fwolff/libgdx,Arcnor/libgdx,sarkanyi/libgdx,djom20/libgdx,Xhanim/libgdx,Badazdz/libgdx,EsikAntony/libgdx,kotcrab/libgdx,Senth/libgdx,toa5/libgdx,gdos/libgdx,kotcrab/libgdx,fwolff/libgdx,Zomby2D/libgdx,GreenLightning/libgdx,mumer92/libgdx,copystudy/libgdx,gdos/libgdx,FyiurAmron/libgdx,Senth/libgdx,yangweigbh/libgdx,TheAks999/libgdx,nudelchef/libgdx,jasonwee/libgdx,lordjone/libgdx,jsjolund/libgdx,designcrumble/libgdx,kagehak/libgdx,bgroenks96/libgdx,PedroRomanoBarbosa/libgdx,tell10glu/libgdx,davebaol/libgdx,del-sol/libgdx,ninoalma/libgdx,gouessej/libgdx,kotcrab/libgdx,KrisLee/libgdx,gf11speed/libgdx,Zonglin-Li6565/libgdx,zhimaijoy/libgdx,kagehak/libgdx,bgroenks96/libgdx,curtiszimmerman/libgdx,josephknight/libgdx,ThiagoGarciaAlves/libgdx,junkdog/libgdx,yangweigbh/libgdx,xpenatan/libgdx-LWJGL3,del-sol/libgdx,youprofit/libgdx,firefly2442/libgdx,toloudis/libgdx,bgroenks96/libgdx,bladecoder/libgdx,nrallakis/libgdx,ya7lelkom/libgdx,xranby/libgdx,309746069/libgdx,kotcrab/libgdx,revo09/libgdx,TheAks999/libgdx,nave966/libgdx,JDReutt/libgdx,junkdog/libgdx,billgame/libgdx,junkdog/libgdx,TheAks999/libgdx,copystudy/libgdx,flaiker/libgdx,del-sol/libgdx,stinsonga/libgdx,shiweihappy/libgdx,ricardorigodon/libgdx,codepoke/libgdx,bsmr-java/libgdx,ztv/libgdx,Wisienkas/libgdx,samskivert/libgdx,sinistersnare/libgdx,SidneyXu/libgdx,codepoke/libgdx,zommuter/libgdx,curtiszimmerman/libgdx,MovingBlocks/libgdx,cypherdare/libgdx,nooone/libgdx,collinsmith/libgdx,1yvT0s/libgdx,djom20/libgdx,codepoke/libgdx,GreenLightning/libgdx,mumer92/libgdx,EsikAntony/libgdx,ya7lelkom/libgdx,basherone/libgdxcn,Dzamir/libgdx,bsmr-java/libgdx,EsikAntony/libgdx,TheAks999/libgdx,realitix/libgdx,noelsison2/libgdx,JFixby/libgdx,alireza-hosseini/libgdx,luischavez/libgdx,revo09/libgdx,luischavez/libgdx,gf11speed/libgdx,xranby/libgdx,nooone/libgdx,UnluckyNinja/libgdx,fwolff/libgdx,ThiagoGarciaAlves/libgdx,FyiurAmron/libgdx,toa5/libgdx,fwolff/libgdx,azakhary/libgdx,snovak/libgdx,MathieuDuponchelle/gdx,MovingBlocks/libgdx,ztv/libgdx,fwolff/libgdx,309746069/libgdx,JDReutt/libgdx,UnluckyNinja/libgdx,xpenatan/libgdx-LWJGL3,collinsmith/libgdx,Badazdz/libgdx,libgdx/libgdx,titovmaxim/libgdx,thepullman/libgdx,Dzamir/libgdx,jsjolund/libgdx,kzganesan/libgdx,stickyd/libgdx,del-sol/libgdx,nrallakis/libgdx,ryoenji/libgdx,curtiszimmerman/libgdx,bgroenks96/libgdx,BlueRiverInteractive/libgdx,MetSystem/libgdx,toa5/libgdx,KrisLee/libgdx,jsjolund/libgdx,FyiurAmron/libgdx,djom20/libgdx,GreenLightning/libgdx,stinsonga/libgdx,alireza-hosseini/libgdx,lordjone/libgdx,alireza-hosseini/libgdx,sarkanyi/libgdx,Badazdz/libgdx,kzganesan/libgdx,Arcnor/libgdx,xoppa/libgdx,alex-dorokhov/libgdx,lordjone/libgdx,davebaol/libgdx,tommycli/libgdx,luischavez/libgdx,titovmaxim/libgdx,azakhary/libgdx,xpenatan/libgdx-LWJGL3,thepullman/libgdx,flaiker/libgdx,FredGithub/libgdx,katiepino/libgdx,jberberick/libgdx,JFixby/libgdx,fiesensee/libgdx,yangweigbh/libgdx,petugez/libgdx,nooone/libgdx,MadcowD/libgdx,jberberick/libgdx,Senth/libgdx,PedroRomanoBarbosa/libgdx,youprofit/libgdx,1yvT0s/libgdx,ThiagoGarciaAlves/libgdx,MathieuDuponchelle/gdx,hyvas/libgdx,lordjone/libgdx,djom20/libgdx,fwolff/libgdx,SidneyXu/libgdx,mumer92/libgdx,BlueRiverInteractive/libgdx,revo09/libgdx,srwonka/libGdx,hyvas/libgdx,BlueRiverInteractive/libgdx,Senth/libgdx,fiesensee/libgdx,JFixby/libgdx,zhimaijoy/libgdx,azakhary/libgdx,srwonka/libGdx,ztv/libgdx,saltares/libgdx,Zomby2D/libgdx,realitix/libgdx,alex-dorokhov/libgdx,flaiker/libgdx,snovak/libgdx,jsjolund/libgdx,xoppa/libgdx,TheAks999/libgdx,bsmr-java/libgdx,Gliby/libgdx,Gliby/libgdx,MetSystem/libgdx,antag99/libgdx,czyzby/libgdx,haedri/libgdx-1,Zonglin-Li6565/libgdx,JDReutt/libgdx,xpenatan/libgdx-LWJGL3,bladecoder/libgdx,snovak/libgdx,bgroenks96/libgdx,kzganesan/libgdx,Heart2009/libgdx,mumer92/libgdx,basherone/libgdxcn,stickyd/libgdx,curtiszimmerman/libgdx,gf11speed/libgdx,Thotep/libgdx,andyvand/libgdx,jsjolund/libgdx,sarkanyi/libgdx,GreenLightning/libgdx,copystudy/libgdx,srwonka/libGdx,ninoalma/libgdx,nave966/libgdx,PedroRomanoBarbosa/libgdx,billgame/libgdx,andyvand/libgdx,GreenLightning/libgdx,junkdog/libgdx,MikkelTAndersen/libgdx,tommycli/libgdx,junkdog/libgdx,flaiker/libgdx,lordjone/libgdx,gdos/libgdx,EsikAntony/libgdx,Deftwun/libgdx,1yvT0s/libgdx,sjosegarcia/libgdx,petugez/libgdx,MikkelTAndersen/libgdx,cypherdare/libgdx,PedroRomanoBarbosa/libgdx,FredGithub/libgdx,antag99/libgdx,basherone/libgdxcn,kotcrab/libgdx,Thotep/libgdx,realitix/libgdx,kagehak/libgdx,MikkelTAndersen/libgdx,stinsonga/libgdx,lordjone/libgdx,curtiszimmerman/libgdx,JFixby/libgdx,toloudis/libgdx,zhimaijoy/libgdx,sinistersnare/libgdx,gf11speed/libgdx,js78/libgdx,Thotep/libgdx,Gliby/libgdx,basherone/libgdxcn,libgdx/libgdx,antag99/libgdx,sjosegarcia/libgdx,KrisLee/libgdx,zhimaijoy/libgdx,snovak/libgdx,czyzby/libgdx,KrisLee/libgdx,titovmaxim/libgdx,sarkanyi/libgdx,andyvand/libgdx,JFixby/libgdx,ricardorigodon/libgdx,GreenLightning/libgdx,Wisienkas/libgdx,saqsun/libgdx,djom20/libgdx,MikkelTAndersen/libgdx,Arcnor/libgdx,xpenatan/libgdx-LWJGL3,ttencate/libgdx,czyzby/libgdx,ttencate/libgdx,del-sol/libgdx,czyzby/libgdx,xoppa/libgdx,BlueRiverInteractive/libgdx,MikkelTAndersen/libgdx,nrallakis/libgdx,gouessej/libgdx,ThiagoGarciaAlves/libgdx,js78/libgdx,Heart2009/libgdx,Badazdz/libgdx,bgroenks96/libgdx,mumer92/libgdx,davebaol/libgdx,MathieuDuponchelle/gdx,nrallakis/libgdx,309746069/libgdx,petugez/libgdx,FyiurAmron/libgdx,del-sol/libgdx,JFixby/libgdx,saqsun/libgdx,tommyettinger/libgdx,PedroRomanoBarbosa/libgdx,MathieuDuponchelle/gdx,MikkelTAndersen/libgdx,alireza-hosseini/libgdx,Senth/libgdx,samskivert/libgdx,ya7lelkom/libgdx,revo09/libgdx,andyvand/libgdx,Arcnor/libgdx,jberberick/libgdx,FredGithub/libgdx,davebaol/libgdx,nrallakis/libgdx,jberberick/libgdx,gouessej/libgdx,ttencate/libgdx,PedroRomanoBarbosa/libgdx,saltares/libgdx,tommycli/libgdx,Deftwun/libgdx,nelsonsilva/libgdx,ricardorigodon/libgdx,youprofit/libgdx,curtiszimmerman/libgdx,309746069/libgdx,MovingBlocks/libgdx,thepullman/libgdx,js78/libgdx,MovingBlocks/libgdx,zommuter/libgdx,jasonwee/libgdx,tell10glu/libgdx,sjosegarcia/libgdx,curtiszimmerman/libgdx,gf11speed/libgdx,GreenLightning/libgdx,kagehak/libgdx,tommycli/libgdx,anserran/libgdx,Deftwun/libgdx,309746069/libgdx,saltares/libgdx,Deftwun/libgdx,mumer92/libgdx,antag99/libgdx,shiweihappy/libgdx,flaiker/libgdx,katiepino/libgdx,youprofit/libgdx,sarkanyi/libgdx,noelsison2/libgdx,Thotep/libgdx,copystudy/libgdx,nudelchef/libgdx,1yvT0s/libgdx,ricardorigodon/libgdx,copystudy/libgdx,kzganesan/libgdx,realitix/libgdx,basherone/libgdxcn,zommuter/libgdx,nelsonsilva/libgdx,1yvT0s/libgdx,anserran/libgdx,jasonwee/libgdx,del-sol/libgdx,ricardorigodon/libgdx,petugez/libgdx,SidneyXu/libgdx,firefly2442/libgdx,katiepino/libgdx,katiepino/libgdx,GreenLightning/libgdx,thepullman/libgdx,xoppa/libgdx,firefly2442/libgdx,fiesensee/libgdx,Deftwun/libgdx,EsikAntony/libgdx,NathanSweet/libgdx,firefly2442/libgdx,cypherdare/libgdx,js78/libgdx,stinsonga/libgdx,petugez/libgdx,MadcowD/libgdx,xranby/libgdx,snovak/libgdx,nudelchef/libgdx,firefly2442/libgdx,billgame/libgdx,toloudis/libgdx,realitix/libgdx,fiesensee/libgdx,toa5/libgdx,saqsun/libgdx,Wisienkas/libgdx,collinsmith/libgdx,MetSystem/libgdx,copystudy/libgdx,MathieuDuponchelle/gdx,jsjolund/libgdx,bsmr-java/libgdx,yangweigbh/libgdx,youprofit/libgdx,jasonwee/libgdx,thepullman/libgdx,stickyd/libgdx,titovmaxim/libgdx,katiepino/libgdx,haedri/libgdx-1,noelsison2/libgdx,FredGithub/libgdx,jberberick/libgdx,sjosegarcia/libgdx,MetSystem/libgdx,saltares/libgdx,fiesensee/libgdx,toloudis/libgdx,nelsonsilva/libgdx,nudelchef/libgdx,nooone/libgdx,petugez/libgdx,KrisLee/libgdx,ttencate/libgdx,Heart2009/libgdx,Arcnor/libgdx,MadcowD/libgdx,stickyd/libgdx,alireza-hosseini/libgdx,junkdog/libgdx,del-sol/libgdx,jberberick/libgdx,antag99/libgdx,thepullman/libgdx,kagehak/libgdx,Wisienkas/libgdx,toloudis/libgdx,sarkanyi/libgdx,ryoenji/libgdx,hyvas/libgdx,saltares/libgdx,gdos/libgdx,codepoke/libgdx,ttencate/libgdx,petugez/libgdx,collinsmith/libgdx,Heart2009/libgdx,PedroRomanoBarbosa/libgdx,samskivert/libgdx,luischavez/libgdx,MikkelTAndersen/libgdx,nave966/libgdx,jasonwee/libgdx,FredGithub/libgdx,libgdx/libgdx,gf11speed/libgdx,samskivert/libgdx,bladecoder/libgdx,toa5/libgdx,designcrumble/libgdx,srwonka/libGdx,UnluckyNinja/libgdx,flaiker/libgdx,ricardorigodon/libgdx,ztv/libgdx,MetSystem/libgdx,realitix/libgdx,titovmaxim/libgdx
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.utils; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.MathUtils; /** Executes tasks in the future on the main loop thread. * @author Nathan Sweet */ public class Timer { static final Array<Timer> instances = new Array(1); static { Thread thread = new Thread("Timer") { public void run () { while (true) { synchronized (instances) { float time = System.nanoTime() * MathUtils.nanoToSec; float wait = Float.MAX_VALUE; for (int i = 0, n = instances.size; i < n; i++) wait = Math.min(wait, instances.get(i).update(time)); long waitMillis = (long)(wait * 1000); try { if (waitMillis > 0) instances.wait(waitMillis); } catch (InterruptedException ignored) { } } } } }; thread.setDaemon(true); thread.start(); } /** Timer instance for general application wide usage. Static methods on {@link Timer} make convenient use of this instance. */ static public final Timer instance = new Timer(); static private final int CANCELLED = -1; static private final int FOREVER = -2; private final Array<Task> tasks = new Array(false, 8); public Timer () { start(); } /** Schedules a task to occur once as soon as possible, but not sooner than the start of the next frame. */ public void postTask (Task task) { scheduleTask(task, 0, 0, 0); } /** Schedules a task to occur once after the specified delay. */ public void scheduleTask (Task task, float delaySeconds) { scheduleTask(task, delaySeconds, 0, 0); } /** Schedules a task to occur once after the specified delay and then repeatedly at the specified interval until cancelled. */ public void scheduleTask (Task task, float delaySeconds, float intervalSeconds) { scheduleTask(task, delaySeconds, intervalSeconds, FOREVER); } /** Schedules a task to occur once after the specified delay and then a number of additional times at the specified interval. */ public void scheduleTask (Task task, float delaySeconds, float intervalSeconds, int repeatCount) { if (task.repeatCount != CANCELLED) throw new IllegalArgumentException("The same task may not be scheduled twice."); task.executeTime = System.nanoTime() * MathUtils.nanoToSec + delaySeconds; task.intervalSeconds = intervalSeconds; task.repeatCount = repeatCount; tasks.add(task); wake(); } /** Stops the timer, tasks will not be executed and time that passes will not be applied to the task delays. */ public void stop () { synchronized (instances) { instances.removeValue(this, true); } } /** Starts the timer if it was stopped. */ public void start () { synchronized (instances) { if (instances.contains(this, true)) return; instances.add(this); wake(); } } /** Cancels all tasks. */ public void clear () { for (int i = 0, n = tasks.size; i < n; i++) tasks.get(i).cancel(); tasks.clear(); } float update (float time) { float wait = Float.MAX_VALUE; for (int i = 0, n = tasks.size; i < n; i++) { Task task = tasks.get(i); if (task.executeTime > time) { wait = Math.min(wait, task.executeTime - time); continue; } if (task.repeatCount != CANCELLED) { if (task.repeatCount == 0) task.repeatCount = CANCELLED; // Set cancelled before run so it may be rescheduled in run. Gdx.app.postRunnable(task); } if (task.repeatCount == CANCELLED) { tasks.removeIndex(i); i--; n--; } else { task.executeTime = time + task.intervalSeconds; wait = Math.min(wait, task.executeTime - time); if (task.repeatCount > 0) task.repeatCount--; } } return wait; } static private void wake () { synchronized (instances) { instances.notifyAll(); } } /** Schedules a task on {@link #instance}. * @see #postTask(Task) */ static public void post (Task task) { instance.postTask(task); } /** Schedules a task on {@link #instance}. * @see #scheduleTask(Task, float) */ static public void schedule (Task task, float delaySeconds) { instance.scheduleTask(task, delaySeconds); } /** Schedules a task on {@link #instance}. * @see #scheduleTask(Task, float, float) */ static public void schedule (Task task, float delaySeconds, float intervalSeconds) { instance.scheduleTask(task, delaySeconds, intervalSeconds); } /** Schedules a task on {@link #instance}. * @see #scheduleTask(Task, float, float, int) */ static public void schedule (Task task, float delaySeconds, float intervalSeconds, int repeatCount) { instance.scheduleTask(task, delaySeconds, intervalSeconds, repeatCount); } /** Runnable with a cancel method. * @see Timer * @author Nathan Sweet */ static abstract public class Task implements Runnable { float executeTime; float intervalSeconds; int repeatCount = CANCELLED; /** If this is the last time the task will be ran or the task is first cancelled, it may be scheduled again in this method. */ abstract public void run (); /** Cancels the task. It will not be executed until it is scheduled again. This method can be called at any time. */ public void cancel () { executeTime = 0; repeatCount = CANCELLED; } /** Returns true if this task is scheduled to be executed in the future by a timer. */ public boolean isScheduled () { return repeatCount != CANCELLED; } } }
gdx/src/com/badlogic/gdx/utils/Timer.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.utils; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.MathUtils; /** Executes tasks in the future on the main loop thread. * @author Nathan Sweet */ public class Timer { static final Array<Timer> instances = new Array(1); static { Thread thread = new Thread("Timer") { public void run () { while (true) { synchronized (instances) { float time = System.nanoTime() * MathUtils.nanoToSec; float wait = Float.MAX_VALUE; for (int i = 0, n = instances.size; i < n; i++) wait = Math.min(wait, instances.get(i).update(time)); try { instances.wait((long)(wait * 1000)); } catch (InterruptedException ignored) { } } } } }; thread.setDaemon(true); thread.start(); } /** Timer instance for general application wide usage. Static methods on {@link Timer} make convenient use of this instance. */ static public final Timer instance = new Timer(); static private final int CANCELLED = -1; static private final int FOREVER = -2; private final Array<Task> tasks = new Array(false, 8); public Timer () { start(); } /** Schedules a task to occur once as soon as possible, but not sooner than the start of the next frame. */ public void postTask (Task task) { scheduleTask(task, 0, 0, 0); } /** Schedules a task to occur once after the specified delay. */ public void scheduleTask (Task task, float delaySeconds) { scheduleTask(task, delaySeconds, 0, 0); } /** Schedules a task to occur once after the specified delay and then repeatedly at the specified interval until cancelled. */ public void scheduleTask (Task task, float delaySeconds, float intervalSeconds) { scheduleTask(task, delaySeconds, intervalSeconds, FOREVER); } /** Schedules a task to occur once after the specified delay and then a number of additional times at the specified interval. */ public void scheduleTask (Task task, float delaySeconds, float intervalSeconds, int repeatCount) { if (task.repeatCount != CANCELLED) throw new IllegalArgumentException("The same task may not be scheduled twice."); task.executeTime = System.nanoTime() * MathUtils.nanoToSec + delaySeconds; task.intervalSeconds = intervalSeconds; task.repeatCount = repeatCount; tasks.add(task); wake(); } /** Stops the timer, tasks will not be executed and time that passes will not be applied to the task delays. */ public void stop () { synchronized (instances) { instances.removeValue(this, true); } } /** Starts the timer if it was stopped. */ public void start () { synchronized (instances) { if (instances.contains(this, true)) return; instances.add(this); wake(); } } /** Cancels all tasks. */ public void clear () { for (int i = 0, n = tasks.size; i < n; i++) tasks.get(i).cancel(); tasks.clear(); } float update (float time) { float wait = Float.MAX_VALUE; for (int i = 0, n = tasks.size; i < n; i++) { Task task = tasks.get(i); if (task.executeTime > time) { wait = Math.min(wait, task.executeTime - time); continue; } if (task.repeatCount != CANCELLED) { if (task.repeatCount == 0) task.repeatCount = CANCELLED; // Set cancelled before run so it may be rescheduled in run. Gdx.app.postRunnable(task); } if (task.repeatCount == CANCELLED) { tasks.removeIndex(i); i--; n--; } else { task.executeTime = time + task.intervalSeconds; wait = Math.min(wait, task.executeTime - time); if (task.repeatCount > 0) task.repeatCount--; } } return wait; } static private void wake () { synchronized (instances) { instances.notifyAll(); } } /** Schedules a task on {@link #instance}. * @see #postTask(Task) */ static public void post (Task task) { instance.postTask(task); } /** Schedules a task on {@link #instance}. * @see #scheduleTask(Task, float) */ static public void schedule (Task task, float delaySeconds) { instance.scheduleTask(task, delaySeconds); } /** Schedules a task on {@link #instance}. * @see #scheduleTask(Task, float, float) */ static public void schedule (Task task, float delaySeconds, float intervalSeconds) { instance.scheduleTask(task, delaySeconds, intervalSeconds); } /** Schedules a task on {@link #instance}. * @see #scheduleTask(Task, float, float, int) */ static public void schedule (Task task, float delaySeconds, float intervalSeconds, int repeatCount) { instance.scheduleTask(task, delaySeconds, intervalSeconds, repeatCount); } /** Runnable with a cancel method. * @see Timer * @author Nathan Sweet */ static abstract public class Task implements Runnable { float executeTime; float intervalSeconds; int repeatCount = CANCELLED; /** If this is the last time the task will be ran or the task is first cancelled, it may be scheduled again in this method. */ abstract public void run (); /** Cancels the task. It will not be executed until it is scheduled again. This method can be called at any time. */ public void cancel () { executeTime = 0; repeatCount = CANCELLED; } /** Returns true if this task is scheduled to be executed in the future by a timer. */ public boolean isScheduled () { return repeatCount != CANCELLED; } } }
Timer, fixed it (I had broke it...).
gdx/src/com/badlogic/gdx/utils/Timer.java
Timer, fixed it (I had broke it...).
<ide><path>dx/src/com/badlogic/gdx/utils/Timer.java <ide> float wait = Float.MAX_VALUE; <ide> for (int i = 0, n = instances.size; i < n; i++) <ide> wait = Math.min(wait, instances.get(i).update(time)); <add> long waitMillis = (long)(wait * 1000); <ide> try { <del> instances.wait((long)(wait * 1000)); <add> if (waitMillis > 0) instances.wait(waitMillis); <ide> } catch (InterruptedException ignored) { <ide> } <ide> }
Java
apache-2.0
ec3529d7c2db5a91015cedd743551f57ba69f78c
0
mtransitapps/ca-gatineau-sto-bus-parser
package org.mtransit.parser.ca_gatineau_sto_bus; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MDirectionType; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; // http://www.sto.ca/index.php?id=575 // http://www.sto.ca/index.php?id=596 // http://www.contenu.sto.ca/GTFS/GTFS.zip public class GatineauSTOBusAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-gatineau-sto-bus-android/res/raw/"; args[2] = ""; // files-prefix } new GatineauSTOBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating STO bus data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this, true); super.start(args); System.out.printf("\nGenerating STO bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public long getRouteId(GRoute gRoute) { return Long.parseLong(gRoute.getRouteShortName()); // using route short name as route ID } @Override public String getRouteLongName(GRoute gRoute) { if ("33".equals(gRoute.getRouteShortName())) { return "Station De La Cité / Cegep Gabrielle-Roy / Ottawa"; } return cleanRouteLongName(gRoute); } private String cleanRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = routeLongName.toLowerCase(Locale.ENGLISH); routeLongName = CleanUtils.cleanSlashes(routeLongName); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR_BLUE = "007F89"; // BLUE PANTONE 7474 (from Corporate Logo Usage PDF) private static final String AGENCY_COLOR = AGENCY_COLOR_BLUE; @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final String REGULAR_COLOR = "231F20"; // "000000"; // BLACK (from PDF) private static final String PEAK_COLOR = "9B0078"; // VIOLET (from PDF) private static final String RB100_COLOR = "0067AC"; // BLUE (from PDF) private static final String RB200_COLOR = "DA002E"; // RED (from PDF) private static final String SCHOOL_BUS_COLOR = "FFD800"; // YELLOW (from Wikipedia) @Override public String getRouteColor(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteColor())) { int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 11: return PEAK_COLOR; case 15: return PEAK_COLOR; case 17: return PEAK_COLOR; case 20: return PEAK_COLOR; case 21: return REGULAR_COLOR; case 22: return PEAK_COLOR; case 24: return PEAK_COLOR; case 25: return PEAK_COLOR; case 26: return PEAK_COLOR; case 27: return PEAK_COLOR; case 28: return PEAK_COLOR; case 29: return PEAK_COLOR; case 31: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 32: return PEAK_COLOR; case 33: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 35: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 36: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 37: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 38: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 39: return REGULAR_COLOR; case 40: return PEAK_COLOR; case 41: return PEAK_COLOR; case 44: return PEAK_COLOR; case 45: return PEAK_COLOR; case 46: return PEAK_COLOR; case 47: return PEAK_COLOR; case 48: return PEAK_COLOR; case 49: return REGULAR_COLOR; case 50: return PEAK_COLOR; case 51: return REGULAR_COLOR; case 52: return REGULAR_COLOR; case 53: return REGULAR_COLOR; case 54: return PEAK_COLOR; case 55: return REGULAR_COLOR; case 57: return REGULAR_COLOR; case 58: return PEAK_COLOR; case 59: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 60: return PEAK_COLOR; case 61: return PEAK_COLOR; case 62: return REGULAR_COLOR; case 63: return REGULAR_COLOR; case 64: return REGULAR_COLOR; case 65: return REGULAR_COLOR; case 66: return REGULAR_COLOR; case 67: return PEAK_COLOR; case 68: return REGULAR_COLOR; // RAPIBUS_COLOR case 69: return REGULAR_COLOR; case 71: return REGULAR_COLOR; case 73: return REGULAR_COLOR; case 74: return PEAK_COLOR; case 75: return REGULAR_COLOR; case 76: return REGULAR_COLOR; case 77: return REGULAR_COLOR; case 78: return REGULAR_COLOR; case 79: return REGULAR_COLOR; case 85: return PEAK_COLOR; case 87: return PEAK_COLOR; case 88: return PEAK_COLOR; case 93: return PEAK_COLOR; // RAPIBUS_COLOR case 95: return PEAK_COLOR; // RAPIBUS_COLOR case 94: return PEAK_COLOR; case 97: return REGULAR_COLOR; case 98: return PEAK_COLOR; case 100: return RB100_COLOR; // RAPIBUS_COLOR case 200: return RB200_COLOR; // RAPIBUS_COLOR case 300: return REGULAR_COLOR; // RAPIBUS_COLOR case 325: return SCHOOL_BUS_COLOR; case 327: return SCHOOL_BUS_COLOR; case 331: return SCHOOL_BUS_COLOR; case 333: return SCHOOL_BUS_COLOR; case 338: return SCHOOL_BUS_COLOR; case 339: return SCHOOL_BUS_COLOR; case 400: return REGULAR_COLOR; // RAPIBUS_COLOR case 439: return SCHOOL_BUS_COLOR; case 500: return REGULAR_COLOR; // RAPIBUS_COLOR case 533: return SCHOOL_BUS_COLOR; case 539: return SCHOOL_BUS_COLOR; case 564: return SCHOOL_BUS_COLOR; case 625: return SCHOOL_BUS_COLOR; case 627: return SCHOOL_BUS_COLOR; case 629: return SCHOOL_BUS_COLOR; case 739: return SCHOOL_BUS_COLOR; case 800: return PEAK_COLOR; // RAPIBUS_COLOR case 810: return PEAK_COLOR; // RAPIBUS_COLOR case 870: return PEAK_COLOR; // RAPIBUS_COLOR // TODO ?? case 901: return null; // @formatter:on } System.out.printf("\nUnexpected route color %s!\n", gRoute); System.exit(-1); return null; } return super.getRouteColor(gRoute); } private static final String SLASH = " / "; private static final String STATION_ = ""; // "Ston "; private static final String LABROSSE_STATION = STATION_ + "Labrosse"; private static final String MUSEE_CANADIEN_HISTOIRE = "Musée Canadien de l'Histoire"; private static final String MUSEE_CANADIEN_HISTOIRE_SHORT = "Musée de l'Histoire"; private static final String FREEMAN = "Freeman"; private static final String OTTAWA = "Ottawa"; private static final String PLACE_D_ACCUEIL = "Pl.Accueil"; // "Place d'Accueil"; private static final String DE_LA_CITÉ = "Cité"; // De La private static final String LORRAIN = "Lorrain"; private static final String RIVERMEAD = "Rivermead"; private static final String P_O_B_SHORT = "P-O-B"; private static final String P_O_B_ALLUM = P_O_B_SHORT + " Allum"; private static final String DE_LA_GALÈNE = "Galène"; // De La private static final String DES_TREMBLES = "Trembles"; // Des private static final String PLATEAU = "Plateau"; private static final String OTTAWA_MUSEE_HISTOIRE = OTTAWA + SLASH + MUSEE_CANADIEN_HISTOIRE; private static final String TERRASSES_DE_LA_CHAUDIERE = "Tsses de la Chaudière"; private static final String CEGEP_GABRIELLE_ROY_SHORT = "Cgp GRoy"; private static final String COLLEGE_SAINT_ALEXANDRE_SHORT = "Col St-Alex"; private static final String COLLEGE_SAINT_JOSEPH_SHORT = "Col St-Jo"; private static final String COLLEGE_NOUVELLES_FRONTIERES_SHORT = "Col NF"; private static final String ECOLE_SECONDAIRE_DE_L_ILE_SHORT = "ES De L'Île"; private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); map2.put(26l, new RouteTripSpec(26l, // 0, MTrip.HEADSIGN_TYPE_STRING, PLATEAU, // 1, MTrip.HEADSIGN_TYPE_STRING, OTTAWA) // .addTripSort(0, // Arrays.asList(new String[] { "5026", "2510", "2769" })) // .addTripSort(1, // Arrays.asList(new String[] { "2767", "2508", "5016" })) // .compileBothTripSort()); map2.put(33l, new RouteTripSpec(33l, // 0, MTrip.HEADSIGN_TYPE_STRING, DE_LA_CITÉ, // 1, MTrip.HEADSIGN_TYPE_STRING, MUSEE_CANADIEN_HISTOIRE_SHORT) // .addTripSort(0, // Arrays.asList(new String[] { // "2618", "2692", "5050", "2010", "2015", "2155", "3500" // })) // .addTripSort(1, // Arrays.asList(new String[] { // "3480", // "3501", // == "8081", // != "3590", "3593", // != "3604", // == "2155", "2153", "2011", "2618", "5048" // })) // .compileBothTripSort()); map2.put(79l, new RouteTripSpec(79l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, LORRAIN, // St-Thomas MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, LABROSSE_STATION) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "3991", // Quai local LABROSSE #5 "3994", // Quai local LABROSSE #8 "4476", // LORRAIN/des POMMETIERS est "4482", // == LORRAIN/BLANCHETTE est "4483", "4502", // != "4484", "4512", // != "4481", // == LORRAIN/THÉRÈSE ouest // "4502" // de CHAMBORD/LORRAIN nord })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // // "4502", // de CHAMBORD/LORRAIN nord "4481", // == LORRAIN/THÉRÈSE ouest "4167", // LORRAIN/des FLEURS ouest "8502" // arrivée quai local LABROSSE ligne 79 })) // .compileBothTripSort()); map2.put(325l, new RouteTripSpec(325l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_ALEXANDRE_SHORT, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLATEAU) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2767", // PINK/de la SAPINIÈRE nord "2273", // du PLATEAU/SAINT-RAYMOND sud "3440" // SAINT-LOUIS/LEBAUDY est })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "3442", // SAINT-LOUIS/LEBAUDY ouest "2767", // PINK/de la SAPINIÈRE nord "2273" // du PLATEAU/SAINT-RAYMOND sud })) // .compileBothTripSort()); map2.put(327l, new RouteTripSpec(327l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_ALEXANDRE_SHORT, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Hautes-Plaines") // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2777", // MARIE-BURGER/de la GALÈNE est "3440" // SAINT-LOUIS/LEBAUDY est })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "3442", // SAINT-LOUIS/LEBAUDY ouest "2653" // de la GALÈNE/des MINEURS ouest })) // .compileBothTripSort()); map2.put(333l, new RouteTripSpec(333l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_ALEXANDRE_SHORT, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, FREEMAN) // CEGEP_GABRIELLE_ROY_SHORT) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2015", // CEGEP GABRIELLE-ROY # "3440" // SAINT-LOUIS/LEBAUDY est })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "3442", // SAINT-LOUIS/LEBAUDY ouest "2153" // TERMINUS FREEMAN })) // .compileBothTripSort()); map2.put(339l, new RouteTripSpec(339l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_ALEXANDRE_SHORT, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLATEAU) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2602", // TERRASSES de la CHAUDIÈRE nord "2004", // ALEXANDRE-TACHÉ/SAINT-RAYMOND sud "3440" // SAINT-LOUIS/LEBAUDY est })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "3442", // SAINT-LOUIS/LEBAUDY ouest "2604" // TERRASSES de la CHAUDIÈRE sud })) // .compileBothTripSort()); map2.put(439l, new RouteTripSpec(439l, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, ECOLE_SECONDAIRE_DE_L_ILE_SHORT, // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLATEAU) // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "2271", // du PLATEAU/SAINT-RAYMOND nord "2642" // SAINT-RÉDEMPTEUR/SACRÉ-COEUR ouest })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "2644", // SAINT-RÉDEMPTEUR/SACRÉ-CŒUR est "2604" // TERRASSES de la CHAUDIÈRE sud })) // .compileBothTripSort()); map2.put(533l, new RouteTripSpec(533l, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Promenades", // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Cité des jeunes") // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "2422", // LIONEL-ÉMOND/SAINT-RAYMOND est "3588" // de la CITÉ/LAMARCHE ouest })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "3587", // de la CITÉ/LAMARCHE est "2420" // LIONEL-ÉMOND/SAINT-RAYMOND ouest })) // .compileBothTripSort()); map2.put(539l, new RouteTripSpec(539l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_NOUVELLES_FRONTIERES_SHORT, // "Émond / Gamelin" MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_JOSEPH_SHORT) // "Taché / St-Joseph" .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2427", // LIONEL-ÉMOND/GAMELIN ouest "2064" // ALEXANDRE-TACHÉ/SAINT-JOSEPH sud })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "2065", // ALEXANDRE-TACHÉ/SAINT-JOSEPH nord "2239", // du PLATEAU/des CÈDRES nord "2421" // LIONEL-ÉMOND/GAMELIN ouest })) // .compileBothTripSort()); map2.put(564L, new RouteTripSpec(564L, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Promenades", // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_NOUVELLES_FRONTIERES_SHORT) // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "2422", // LIONEL-ÉMOND/SAINT-RAYMOND est "4377" // de la GAPPE/BELLEHUMEUR sud })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "4376", // de la GAPPE/BELLEHUMEUR nord "2421" // LIONEL-ÉMOND/GAMELIN ouest })) // .compileBothTripSort()); map2.put(625L, new RouteTripSpec(625L, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, ECOLE_SECONDAIRE_DE_L_ILE_SHORT, // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Pink / Conservatoire") // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "1459", // du CONSERVATOIRE/du LOUVRE ouest "2642" // SAINT-RÉDEMPTEUR/SACRÉ-COEUR ouest })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "2644", // SAINT-RÉDEMPTEUR/SACRÉ-CŒUR est "1460" // du CONSERVATOIRE/du LOUVRE est })) // .compileBothTripSort()); map2.put(633l, new RouteTripSpec(633l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, FREEMAN, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, ECOLE_SECONDAIRE_DE_L_ILE_SHORT) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2644", "2015", "2151" // })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "2153", "2642" // })) // .compileBothTripSort()); map2.put(737l, new RouteTripSpec(737l, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, TERRASSES_DE_LA_CHAUDIERE, // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "E Montbleu") // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "2192", // de la CITÉ-DES-JEUNES/TALBOT ouest "2604" // TERRASSES de la CHAUDIÈRE sud })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "2602", // TERRASSES de la CHAUDIÈRE nord "2120", // SAINT-JOSEPH/RENÉ-MARENGÈRE est "2188" // de la CITÉ-DES-JEUNES/TALBOT est })) // .compileBothTripSort()); map2.put(753l, new RouteTripSpec(753l, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Lucerne / Robert-Sterward", // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "ESGRivière") // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "1073", "1298" // })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "1298", "1075" // })) // .compileBothTripSort()); map2.put(870l, new RouteTripSpec(870l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Arena Guertin", // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Wellington/Metcalfe") // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "5030", // WELLINGTON/METCALFE nord "2643", // SAINT-RÉDEMPTEUR/ALLARD ouest })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "2643", // SAINT-RÉDEMPTEUR/ALLARD ouest "5032", // WELLINGTON/METCALFE sud })) // .compileBothTripSort()); ALL_ROUTE_TRIPS2 = map2; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } return super.splitTrip(mRoute, gTrip, gtfs); } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId())); } return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS); } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } String tripHeadsign = gTrip.getTripHeadsign(); if (StringUtils.isEmpty(tripHeadsign)) { tripHeadsign = mRoute.getLongName(); } if (mRoute.getId() == 21l) { if (OTTAWA_MUSEE_HISTOIRE.equalsIgnoreCase(mTrip.getHeadsignValue())) { mTrip.setHeadsignString(MUSEE_CANADIEN_HISTOIRE_SHORT, gTrip.getDirectionId()); return; } } mTrip.setHeadsignString(cleanTripHeadsign(tripHeadsign), gTrip.getDirectionId()); } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { if (mTrip.getRouteId() == 11l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(PLACE_D_ACCUEIL, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 17l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(PLACE_D_ACCUEIL, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 20l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 21l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(FREEMAN, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(MUSEE_CANADIEN_HISTOIRE_SHORT, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 24l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(PLATEAU, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 25l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(PLATEAU, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 27l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString("Hplaines", mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString("Ottawa", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 29l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(DES_TREMBLES, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 31l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 32l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 33l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(DE_LA_CITÉ, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 35l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(DE_LA_GALÈNE, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 36l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 37l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 38l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(FREEMAN, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 39l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(FREEMAN, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 40l) { if (mTrip.getHeadsignId() == 1) { } } else if (mTrip.getRouteId() == 41l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 49l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 50l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 51l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 52l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 53l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 54l) { if (mTrip.getHeadsignId() == 0) { } else if (mTrip.getHeadsignId() == 1) { } } else if (mTrip.getRouteId() == 57l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 58l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 59l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 64l) { if (mTrip.getHeadsignId() == 0) { } else if (mTrip.getHeadsignId() == 1) { } } else if (mTrip.getRouteId() == 66l) { if (mTrip.getHeadsignId() == 0) { } else if (mTrip.getHeadsignId() == 1) { } } else if (mTrip.getRouteId() == 67l) { if (mTrip.getHeadsignId() == 0) { } else if (mTrip.getRouteId() == 87l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(PLACE_D_ACCUEIL, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 88l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(LABROSSE_STATION, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 650l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 731l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString("Coll St-Jo", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 735l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString("E Montbleu", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 737l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString("E Montbleu", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 739l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString("Plateau", mTrip.getHeadsignId()); return true; } } System.out.printf("\nUnexpected trips to merge: %s & %s!\n", mTrip, mTripToMerge); System.exit(-1); return false; } private static final Pattern TO = Pattern.compile("((^|\\W){1}(to)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final Pattern VIA = Pattern.compile("((^|\\W){1}(via)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final Pattern MUSEE_CANADIEN_HISTOIRE_ = Pattern.compile("((^|\\W){1}(mus[e|é]e canadien de l'histoire)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String MUSEE_CANADIEN_HISTOIRE_REPLACEMENT = "$2" + MUSEE_CANADIEN_HISTOIRE_SHORT + "$4"; private static final Pattern CLEAN_STATION = Pattern.compile("((^|\\W){1}(station|ston|sta)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String CLEAN_STATION_REPLACEMENT = "$2" + STATION_ + "$4"; private static final Pattern CEGEP_GABRIELLE_ROY_ = Pattern.compile( "((^|\\W){1}(c[é|É|e|è|È]gep gabrielle-roy|c[é|É|e|è|È]gep groy|cgp gabrielle-r|cgp groy|cgp g-roy|Cegep Gab\\.Roy)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String CEGEP_GABRIELLE_ROY_REPLACEMENT = "$2" + CEGEP_GABRIELLE_ROY_SHORT + "$4"; private static final Pattern ECOLE_SECONDAIRE_DE_L_ILE_ = Pattern.compile("((^|\\W){1}([e|é]cole De l'[i|î]le)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String ECOLE_SECONDAIRE_DE_L_ILE_REPLACEMENT = "$2" + ECOLE_SECONDAIRE_DE_L_ILE_SHORT + "$4"; private static final Pattern COLLEGE_SAINY_ALEXANDRE_ = Pattern.compile("((^|\\W){1}(Col Stalex)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String COLLEGE_SAINY_ALEXANDRE_REPLACEMENT = "$2" + COLLEGE_SAINT_ALEXANDRE_SHORT + "$4"; private static final Pattern P_O_B = Pattern.compile("((^|\\W){1}(pob|p\\-o\\-b)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String P_O_B_REPLACEMENT = "$2" + P_O_B_SHORT + "$4"; private static final Pattern PRE_TUNNEY_ = Pattern.compile("((^|\\W){1}(pr[e|é|É] tunney)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String PRE_TUNNEY__REPLACEMENT = "$2" + "Pré-Tunney" + "$4"; @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = tripHeadsign.toLowerCase(Locale.ENGLISH); Matcher matcherTO = TO.matcher(tripHeadsign); if (matcherTO.find()) { String gTripHeadsignAfterTO = tripHeadsign.substring(matcherTO.end()); tripHeadsign = gTripHeadsignAfterTO; } Matcher matcherVIA = VIA.matcher(tripHeadsign); if (matcherVIA.find()) { String gTripHeadsignBeforeVIA = tripHeadsign.substring(0, matcherVIA.start()); tripHeadsign = gTripHeadsignBeforeVIA; } tripHeadsign = CLEAN_STATION.matcher(tripHeadsign).replaceAll(CLEAN_STATION_REPLACEMENT); tripHeadsign = CEGEP_GABRIELLE_ROY_.matcher(tripHeadsign).replaceAll(CEGEP_GABRIELLE_ROY_REPLACEMENT); tripHeadsign = COLLEGE_SAINY_ALEXANDRE_.matcher(tripHeadsign).replaceAll(COLLEGE_SAINY_ALEXANDRE_REPLACEMENT); tripHeadsign = ECOLE_SECONDAIRE_DE_L_ILE_.matcher(tripHeadsign).replaceAll(ECOLE_SECONDAIRE_DE_L_ILE_REPLACEMENT); tripHeadsign = P_O_B.matcher(tripHeadsign).replaceAll(P_O_B_REPLACEMENT); tripHeadsign = PRE_TUNNEY_.matcher(tripHeadsign).replaceAll(PRE_TUNNEY__REPLACEMENT); tripHeadsign = MUSEE_CANADIEN_HISTOIRE_.matcher(tripHeadsign).replaceAll(MUSEE_CANADIEN_HISTOIRE_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_ET.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_ET_REPLACEMENT); tripHeadsign = CleanUtils.cleanSlashes(tripHeadsign); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); tripHeadsign = CleanUtils.removePoints(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypesFRCA(tripHeadsign); return CleanUtils.cleanLabelFR(tripHeadsign); } private static final Pattern ENDS_WITH_BOUNDS = Pattern.compile("((dir )?(est|ouest|nord|sud)$)", Pattern.CASE_INSENSITIVE); private static final Pattern STARTS_ENDS_WITH_ARRIVAL_DEPARTURE = Pattern.compile("(" + "^(arriv[e|é]e|d[e|é]part)" + "|" + "(arr[e|ê]t d'arriv[e|é]e|arriv[e|é]e|d[e|é]part)$" + ")", Pattern.CASE_INSENSITIVE); private static final Pattern CLEAN_ARRET_DE_COURTOISIE = Pattern.compile("((arr[e|ê|Ê]t de courtoisie[\\s]*)(.*))", Pattern.CASE_INSENSITIVE); private static final String CLEAN_ARRET_DE_COURTOISIE_REPLACEMENT = "$3 (Arrêt de Courtoisie)"; @Override public String cleanStopName(String gStopName) { gStopName = gStopName.toLowerCase(Locale.ENGLISH); gStopName = ENDS_WITH_BOUNDS.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = STARTS_ENDS_WITH_ARRIVAL_DEPARTURE.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = CLEAN_ARRET_DE_COURTOISIE.matcher(gStopName).replaceAll(CLEAN_ARRET_DE_COURTOISIE_REPLACEMENT); gStopName = CleanUtils.SAINT.matcher(gStopName).replaceAll(CleanUtils.SAINT_REPLACEMENT); gStopName = CleanUtils.CLEAN_ET.matcher(gStopName).replaceAll(CleanUtils.CLEAN_ET_REPLACEMENT); gStopName = CleanUtils.cleanSlashes(gStopName); gStopName = CleanUtils.removePoints(gStopName); gStopName = CleanUtils.cleanStreetTypesFRCA(gStopName); return CleanUtils.cleanLabelFR(gStopName); } @Override public String getStopCode(GStop gStop) { if (StringUtils.isEmpty(gStop.getStopCode())) { return String.valueOf(gStop.getStopId()); // use stop ID as stop code } return super.getStopCode(gStop); } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); @Override public int getStopId(GStop gStop) { if (!Utils.isDigitsOnly(gStop.getStopId())) { Matcher matcher = DIGITS.matcher(gStop.getStopId()); if (matcher.find()) { int digits = Integer.parseInt(matcher.group()); if (gStop.getStopId().toLowerCase(Locale.ENGLISH).endsWith("a")) { return 100000 + digits; } } System.out.printf("\nUnexpected stop ID for %s!\n", gStop); System.exit(-1); return -1; } return super.getStopId(gStop); } }
src/org/mtransit/parser/ca_gatineau_sto_bus/GatineauSTOBusAgencyTools.java
package org.mtransit.parser.ca_gatineau_sto_bus; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MDirectionType; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; // http://www.sto.ca/index.php?id=575 // http://www.sto.ca/index.php?id=596 // http://www.contenu.sto.ca/GTFS/GTFS.zip public class GatineauSTOBusAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-gatineau-sto-bus-android/res/raw/"; args[2] = ""; // files-prefix } new GatineauSTOBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating STO bus data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this, true); super.start(args); System.out.printf("\nGenerating STO bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public long getRouteId(GRoute gRoute) { return Long.parseLong(gRoute.getRouteShortName()); // using route short name as route ID } @Override public String getRouteLongName(GRoute gRoute) { if ("33".equals(gRoute.getRouteShortName())) { return "Station De La Cité / Cegep Gabrielle-Roy / Ottawa"; } return cleanRouteLongName(gRoute); } private String cleanRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = routeLongName.toLowerCase(Locale.ENGLISH); routeLongName = CleanUtils.cleanSlashes(routeLongName); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR_BLUE = "007F89"; // BLUE PANTONE 7474 (from Corporate Logo Usage PDF) private static final String AGENCY_COLOR = AGENCY_COLOR_BLUE; @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final String REGULAR_COLOR = "231F20"; // "000000"; // BLACK (from PDF) private static final String PEAK_COLOR = "9B0078"; // VIOLET (from PDF) private static final String RB100_COLOR = "0067AC"; // BLUE (from PDF) private static final String RB200_COLOR = "DA002E"; // RED (from PDF) private static final String SCHOOL_BUS_COLOR = "FFD800"; // YELLOW (from Wikipedia) @Override public String getRouteColor(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteColor())) { int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 11: return PEAK_COLOR; case 15: return PEAK_COLOR; case 17: return PEAK_COLOR; case 20: return PEAK_COLOR; case 21: return REGULAR_COLOR; case 22: return PEAK_COLOR; case 24: return PEAK_COLOR; case 25: return PEAK_COLOR; case 26: return PEAK_COLOR; case 27: return PEAK_COLOR; case 28: return PEAK_COLOR; case 29: return PEAK_COLOR; case 31: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 32: return PEAK_COLOR; case 33: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 35: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 36: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 37: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 38: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 39: return REGULAR_COLOR; case 40: return PEAK_COLOR; case 41: return PEAK_COLOR; case 44: return PEAK_COLOR; case 45: return PEAK_COLOR; case 46: return PEAK_COLOR; case 47: return PEAK_COLOR; case 48: return PEAK_COLOR; case 49: return REGULAR_COLOR; case 50: return PEAK_COLOR; case 51: return REGULAR_COLOR; case 52: return REGULAR_COLOR; case 53: return REGULAR_COLOR; case 54: return PEAK_COLOR; case 55: return REGULAR_COLOR; case 57: return REGULAR_COLOR; case 58: return PEAK_COLOR; case 59: return REGULAR_COLOR; // OCCASIONAL_COLOR; case 60: return PEAK_COLOR; case 61: return PEAK_COLOR; case 62: return REGULAR_COLOR; case 63: return REGULAR_COLOR; case 64: return REGULAR_COLOR; case 65: return REGULAR_COLOR; case 66: return REGULAR_COLOR; case 67: return PEAK_COLOR; case 68: return REGULAR_COLOR; // RAPIBUS_COLOR case 69: return REGULAR_COLOR; case 71: return REGULAR_COLOR; case 73: return REGULAR_COLOR; case 74: return PEAK_COLOR; case 75: return REGULAR_COLOR; case 76: return REGULAR_COLOR; case 77: return REGULAR_COLOR; case 78: return REGULAR_COLOR; case 79: return REGULAR_COLOR; case 85: return PEAK_COLOR; case 87: return PEAK_COLOR; case 88: return PEAK_COLOR; case 93: return PEAK_COLOR; // RAPIBUS_COLOR case 95: return PEAK_COLOR; // RAPIBUS_COLOR case 94: return PEAK_COLOR; case 97: return REGULAR_COLOR; case 98: return PEAK_COLOR; case 100: return RB100_COLOR; // RAPIBUS_COLOR case 200: return RB200_COLOR; // RAPIBUS_COLOR case 300: return REGULAR_COLOR; // RAPIBUS_COLOR case 325: return SCHOOL_BUS_COLOR; case 327: return SCHOOL_BUS_COLOR; case 331: return SCHOOL_BUS_COLOR; case 333: return SCHOOL_BUS_COLOR; case 338: return SCHOOL_BUS_COLOR; case 339: return SCHOOL_BUS_COLOR; case 400: return REGULAR_COLOR; // RAPIBUS_COLOR case 439: return SCHOOL_BUS_COLOR; case 500: return REGULAR_COLOR; // RAPIBUS_COLOR case 533: return SCHOOL_BUS_COLOR; case 539: return SCHOOL_BUS_COLOR; case 564: return SCHOOL_BUS_COLOR; case 625: return SCHOOL_BUS_COLOR; case 627: return SCHOOL_BUS_COLOR; case 629: return SCHOOL_BUS_COLOR; case 739: return SCHOOL_BUS_COLOR; case 800: return PEAK_COLOR; // RAPIBUS_COLOR case 810: return PEAK_COLOR; // RAPIBUS_COLOR case 901: return null; // @formatter:on } System.out.printf("\nUnexpected route color %s!\n", gRoute); System.exit(-1); return null; } return super.getRouteColor(gRoute); } private static final String SLASH = " / "; private static final String STATION_ = ""; // "Ston "; private static final String LABROSSE_STATION = STATION_ + "Labrosse"; private static final String MUSEE_CANADIEN_HISTOIRE = "Musée Canadien de l'Histoire"; private static final String MUSEE_CANADIEN_HISTOIRE_SHORT = "Musée de l'Histoire"; private static final String FREEMAN = "Freeman"; private static final String OTTAWA = "Ottawa"; private static final String PLACE_D_ACCUEIL = "Pl.Accueil"; // "Place d'Accueil"; private static final String DE_LA_CITÉ = "Cité"; // De La private static final String LORRAIN = "Lorrain"; private static final String RIVERMEAD = "Rivermead"; private static final String P_O_B_SHORT = "P-O-B"; private static final String P_O_B_ALLUM = P_O_B_SHORT + " Allum"; private static final String DE_LA_GALÈNE = "Galène"; // De La private static final String DES_TREMBLES = "Trembles"; // Des private static final String PLATEAU = "Plateau"; private static final String OTTAWA_MUSEE_HISTOIRE = OTTAWA + SLASH + MUSEE_CANADIEN_HISTOIRE; private static final String TERRASSES_DE_LA_CHAUDIERE = "Tsses de la Chaudière"; private static final String CEGEP_GABRIELLE_ROY_SHORT = "Cgp GRoy"; private static final String COLLEGE_SAINT_ALEXANDRE_SHORT = "Col St-Alex"; private static final String COLLEGE_SAINT_JOSEPH_SHORT = "Col St-Jo"; private static final String COLLEGE_NOUVELLES_FRONTIERES_SHORT = "Col NF"; private static final String ECOLE_SECONDAIRE_DE_L_ILE_SHORT = "ES De L'Île"; private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); map2.put(26l, new RouteTripSpec(26l, // 0, MTrip.HEADSIGN_TYPE_STRING, PLATEAU, // 1, MTrip.HEADSIGN_TYPE_STRING, OTTAWA) // .addTripSort(0, // Arrays.asList(new String[] { "5026", "2510", "2769" })) // .addTripSort(1, // Arrays.asList(new String[] { "2767", "2508", "5016" })) // .compileBothTripSort()); map2.put(33l, new RouteTripSpec(33l, // 0, MTrip.HEADSIGN_TYPE_STRING, DE_LA_CITÉ, // 1, MTrip.HEADSIGN_TYPE_STRING, MUSEE_CANADIEN_HISTOIRE_SHORT) // .addTripSort(0, // Arrays.asList(new String[] { // "2618", "2692", "5050", "2010", "2015", "2155", "3500" // })) // .addTripSort(1, // Arrays.asList(new String[] { // "3480", // "3501", // == "8081", // != "3590", "3593", // != "3604", // == "2155", "2153", "2011", "2618", "5048" // })) // .compileBothTripSort()); map2.put(79l, new RouteTripSpec(79l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, LORRAIN, // St-Thomas MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, LABROSSE_STATION) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "3991", // Quai local LABROSSE #5 "3994", // Quai local LABROSSE #8 "4476", // LORRAIN/des POMMETIERS est "4482", // == LORRAIN/BLANCHETTE est "4483", "4502", // != "4484", "4512", // != "4481", // == LORRAIN/THÉRÈSE ouest // "4502" // de CHAMBORD/LORRAIN nord })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // // "4502", // de CHAMBORD/LORRAIN nord "4481", // == LORRAIN/THÉRÈSE ouest "4167", // LORRAIN/des FLEURS ouest "8502" // arrivée quai local LABROSSE ligne 79 })) // .compileBothTripSort()); map2.put(325l, new RouteTripSpec(325l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_ALEXANDRE_SHORT, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLATEAU) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2767", // PINK/de la SAPINIÈRE nord "2273", // du PLATEAU/SAINT-RAYMOND sud "3440" // SAINT-LOUIS/LEBAUDY est })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "3442", // SAINT-LOUIS/LEBAUDY ouest "2767", // PINK/de la SAPINIÈRE nord "2273" // du PLATEAU/SAINT-RAYMOND sud })) // .compileBothTripSort()); map2.put(327l, new RouteTripSpec(327l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_ALEXANDRE_SHORT, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Hautes-Plaines") // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2777", // MARIE-BURGER/de la GALÈNE est "3440" // SAINT-LOUIS/LEBAUDY est })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "3442", // SAINT-LOUIS/LEBAUDY ouest "2653" // de la GALÈNE/des MINEURS ouest })) // .compileBothTripSort()); map2.put(333l, new RouteTripSpec(333l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_ALEXANDRE_SHORT, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, FREEMAN) // CEGEP_GABRIELLE_ROY_SHORT) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2015", // CEGEP GABRIELLE-ROY # "3440" // SAINT-LOUIS/LEBAUDY est })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "3442", // SAINT-LOUIS/LEBAUDY ouest "2153" // TERMINUS FREEMAN })) // .compileBothTripSort()); map2.put(339l, new RouteTripSpec(339l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_ALEXANDRE_SHORT, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLATEAU) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2602", // TERRASSES de la CHAUDIÈRE nord "2004", // ALEXANDRE-TACHÉ/SAINT-RAYMOND sud "3440" // SAINT-LOUIS/LEBAUDY est })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "3442", // SAINT-LOUIS/LEBAUDY ouest "2604" // TERRASSES de la CHAUDIÈRE sud })) // .compileBothTripSort()); map2.put(439l, new RouteTripSpec(439l, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "École De L'île", // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLATEAU) // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "2271", // du PLATEAU/SAINT-RAYMOND nord "2642" // SAINT-RÉDEMPTEUR/SACRÉ-COEUR ouest })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "2644", // SAINT-RÉDEMPTEUR/SACRÉ-CŒUR est "2604" // TERRASSES de la CHAUDIÈRE sud })) // .compileBothTripSort()); map2.put(533l, new RouteTripSpec(533l, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Promenades", // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Cité des jeunes") // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "2422", // LIONEL-ÉMOND/SAINT-RAYMOND est "3588" // de la CITÉ/LAMARCHE ouest })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "3587", // de la CITÉ/LAMARCHE est "2420" // LIONEL-ÉMOND/SAINT-RAYMOND ouest })) // .compileBothTripSort()); map2.put(539l, new RouteTripSpec(539l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_NOUVELLES_FRONTIERES_SHORT, // "Émond / Gamelin" MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_SAINT_JOSEPH_SHORT) // "Taché / St-Joseph" .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2427", // LIONEL-ÉMOND/GAMELIN ouest "2064" // ALEXANDRE-TACHÉ/SAINT-JOSEPH sud })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "2065", // ALEXANDRE-TACHÉ/SAINT-JOSEPH nord "2239", // du PLATEAU/des CÈDRES nord "2421" // LIONEL-ÉMOND/GAMELIN ouest })) // .compileBothTripSort()); map2.put(564L, new RouteTripSpec(564L, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Promenades", // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, COLLEGE_NOUVELLES_FRONTIERES_SHORT) // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "2422", // LIONEL-ÉMOND/SAINT-RAYMOND est "4377" // de la GAPPE/BELLEHUMEUR sud })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "4376", // de la GAPPE/BELLEHUMEUR nord "2421" // LIONEL-ÉMOND/GAMELIN ouest })) // .compileBothTripSort()); map2.put(625L, new RouteTripSpec(625L, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, ECOLE_SECONDAIRE_DE_L_ILE_SHORT, // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Pink / Conservatoire") // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "1459", // du CONSERVATOIRE/du LOUVRE ouest "2642" // SAINT-RÉDEMPTEUR/SACRÉ-COEUR ouest })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "2644", // SAINT-RÉDEMPTEUR/SACRÉ-CŒUR est "1460" // du CONSERVATOIRE/du LOUVRE est })) // .compileBothTripSort()); map2.put(633l, new RouteTripSpec(633l, // MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, FREEMAN, // MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, ECOLE_SECONDAIRE_DE_L_ILE_SHORT) // .addTripSort(MDirectionType.NORTH.intValue(), // Arrays.asList(new String[] { // "2644", "2015", "2151" // })) // .addTripSort(MDirectionType.SOUTH.intValue(), // Arrays.asList(new String[] { // "2153", "2642" // })) // .compileBothTripSort()); map2.put(737l, new RouteTripSpec(737l, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, TERRASSES_DE_LA_CHAUDIERE, // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "E Montbleu") // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "2192", // de la CITÉ-DES-JEUNES/TALBOT ouest "2604" // TERRASSES de la CHAUDIÈRE sud })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "2602", // TERRASSES de la CHAUDIÈRE nord "2120", // SAINT-JOSEPH/RENÉ-MARENGÈRE est "2188" // de la CITÉ-DES-JEUNES/TALBOT est })) // .compileBothTripSort()); map2.put(753l, new RouteTripSpec(753l, // MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Lucerne / Robert-Sterward", // MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "ESGRivière") // .addTripSort(MDirectionType.EAST.intValue(), // Arrays.asList(new String[] { // "1073", "1298" // })) // .addTripSort(MDirectionType.WEST.intValue(), // Arrays.asList(new String[] { // "1298", "1075" // })) // .compileBothTripSort()); ALL_ROUTE_TRIPS2 = map2; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } return super.splitTrip(mRoute, gTrip, gtfs); } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId())); } return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS); } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } String tripHeadsign = gTrip.getTripHeadsign(); if (StringUtils.isEmpty(tripHeadsign)) { tripHeadsign = mRoute.getLongName(); } if (mRoute.getId() == 21l) { if (OTTAWA_MUSEE_HISTOIRE.equalsIgnoreCase(mTrip.getHeadsignValue())) { mTrip.setHeadsignString(MUSEE_CANADIEN_HISTOIRE_SHORT, gTrip.getDirectionId()); return; } } mTrip.setHeadsignString(cleanTripHeadsign(tripHeadsign), gTrip.getDirectionId()); } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { if (mTrip.getRouteId() == 11l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(PLACE_D_ACCUEIL, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 17l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(PLACE_D_ACCUEIL, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 20l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 21l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(FREEMAN, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(MUSEE_CANADIEN_HISTOIRE_SHORT, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 24l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(PLATEAU, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 25l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(PLATEAU, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 27l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString("Hplaines", mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString("Ottawa", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 29l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(DES_TREMBLES, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 31l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 32l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 33l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(DE_LA_CITÉ, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 35l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(DE_LA_GALÈNE, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 36l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 37l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 38l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(FREEMAN, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 39l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(FREEMAN, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 40l) { if (mTrip.getHeadsignId() == 1) { } } else if (mTrip.getRouteId() == 41l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 49l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 50l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 51l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 52l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 53l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(P_O_B_ALLUM, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 54l) { if (mTrip.getHeadsignId() == 0) { } else if (mTrip.getHeadsignId() == 1) { } } else if (mTrip.getRouteId() == 57l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 58l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 59l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(OTTAWA, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 64l) { if (mTrip.getHeadsignId() == 0) { } else if (mTrip.getHeadsignId() == 1) { } } else if (mTrip.getRouteId() == 66l) { if (mTrip.getHeadsignId() == 0) { } else if (mTrip.getHeadsignId() == 1) { } } else if (mTrip.getRouteId() == 67l) { if (mTrip.getHeadsignId() == 0) { } else if (mTrip.getRouteId() == 87l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString(PLACE_D_ACCUEIL, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 88l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(LABROSSE_STATION, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 650l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(RIVERMEAD, mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 731l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString(CEGEP_GABRIELLE_ROY_SHORT, mTrip.getHeadsignId()); return true; } else if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString("Coll St-Jo", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 735l) { if (mTrip.getHeadsignId() == 1) { mTrip.setHeadsignString("E Montbleu", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 737l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString("E Montbleu", mTrip.getHeadsignId()); return true; } } else if (mTrip.getRouteId() == 739l) { if (mTrip.getHeadsignId() == 0) { mTrip.setHeadsignString("Plateau", mTrip.getHeadsignId()); return true; } } System.out.printf("\nUnexpected trips to merge: %s & %s!\n", mTrip, mTripToMerge); System.exit(-1); return false; } private static final Pattern TO = Pattern.compile("((^|\\W){1}(to)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final Pattern VIA = Pattern.compile("((^|\\W){1}(via)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final Pattern MUSEE_CANADIEN_HISTOIRE_ = Pattern.compile("((^|\\W){1}(mus[e|é]e canadien de l'histoire)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String MUSEE_CANADIEN_HISTOIRE_REPLACEMENT = "$2" + MUSEE_CANADIEN_HISTOIRE_SHORT + "$4"; private static final Pattern CLEAN_STATION = Pattern.compile("((^|\\W){1}(station|ston|sta)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String CLEAN_STATION_REPLACEMENT = "$2" + STATION_ + "$4"; private static final Pattern CEGEP_GABRIELLE_ROY_ = Pattern.compile( "((^|\\W){1}(c[é|É|e|è|È]gep gabrielle-roy|c[é|É|e|è|È]gep groy|cgp gabrielle-r|cgp groy|cgp g-roy|Cegep Gab\\.Roy)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String CEGEP_GABRIELLE_ROY_REPLACEMENT = "$2" + CEGEP_GABRIELLE_ROY_SHORT + "$4"; private static final Pattern ECOLE_SECONDAIRE_DE_L_ILE_ = Pattern.compile("((^|\\W){1}([e|é]cole De l'[i|î]le)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String ECOLE_SECONDAIRE_DE_L_ILE_REPLACEMENT = "$2" + ECOLE_SECONDAIRE_DE_L_ILE_SHORT + "$4"; private static final Pattern COLLEGE_SAINY_ALEXANDRE_ = Pattern.compile("((^|\\W){1}(Col Stalex)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String COLLEGE_SAINY_ALEXANDRE_REPLACEMENT = "$2" + COLLEGE_SAINT_ALEXANDRE_SHORT + "$4"; private static final Pattern P_O_B = Pattern.compile("((^|\\W){1}(pob|p\\-o\\-b)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String P_O_B_REPLACEMENT = "$2" + P_O_B_SHORT + "$4"; private static final Pattern PRE_TUNNEY_ = Pattern.compile("((^|\\W){1}(pr[e|é|É] tunney)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String PRE_TUNNEY__REPLACEMENT = "$2" + "Pré-Tunney" + "$4"; @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = tripHeadsign.toLowerCase(Locale.ENGLISH); Matcher matcherTO = TO.matcher(tripHeadsign); if (matcherTO.find()) { String gTripHeadsignAfterTO = tripHeadsign.substring(matcherTO.end()); tripHeadsign = gTripHeadsignAfterTO; } Matcher matcherVIA = VIA.matcher(tripHeadsign); if (matcherVIA.find()) { String gTripHeadsignBeforeVIA = tripHeadsign.substring(0, matcherVIA.start()); tripHeadsign = gTripHeadsignBeforeVIA; } tripHeadsign = CLEAN_STATION.matcher(tripHeadsign).replaceAll(CLEAN_STATION_REPLACEMENT); tripHeadsign = CEGEP_GABRIELLE_ROY_.matcher(tripHeadsign).replaceAll(CEGEP_GABRIELLE_ROY_REPLACEMENT); tripHeadsign = COLLEGE_SAINY_ALEXANDRE_.matcher(tripHeadsign).replaceAll(COLLEGE_SAINY_ALEXANDRE_REPLACEMENT); tripHeadsign = ECOLE_SECONDAIRE_DE_L_ILE_.matcher(tripHeadsign).replaceAll(ECOLE_SECONDAIRE_DE_L_ILE_REPLACEMENT); tripHeadsign = P_O_B.matcher(tripHeadsign).replaceAll(P_O_B_REPLACEMENT); tripHeadsign = PRE_TUNNEY_.matcher(tripHeadsign).replaceAll(PRE_TUNNEY__REPLACEMENT); tripHeadsign = MUSEE_CANADIEN_HISTOIRE_.matcher(tripHeadsign).replaceAll(MUSEE_CANADIEN_HISTOIRE_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_ET.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_ET_REPLACEMENT); tripHeadsign = CleanUtils.cleanSlashes(tripHeadsign); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); tripHeadsign = CleanUtils.removePoints(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypesFRCA(tripHeadsign); return CleanUtils.cleanLabelFR(tripHeadsign); } private static final Pattern ENDS_WITH_BOUNDS = Pattern.compile("((dir )?(est|ouest|nord|sud)$)", Pattern.CASE_INSENSITIVE); private static final Pattern STARTS_ENDS_WITH_ARRIVAL_DEPARTURE = Pattern.compile("(" + "^(arriv[e|é]e|d[e|é]part)" + "|" + "(arr[e|ê]t d'arriv[e|é]e|arriv[e|é]e|d[e|é]part)$" + ")", Pattern.CASE_INSENSITIVE); private static final Pattern CLEAN_ARRET_DE_COURTOISIE = Pattern.compile("((arr[e|ê|Ê]t de courtoisie[\\s]*)(.*))", Pattern.CASE_INSENSITIVE); private static final String CLEAN_ARRET_DE_COURTOISIE_REPLACEMENT = "$3 (Arrêt de Courtoisie)"; @Override public String cleanStopName(String gStopName) { gStopName = gStopName.toLowerCase(Locale.ENGLISH); gStopName = ENDS_WITH_BOUNDS.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = STARTS_ENDS_WITH_ARRIVAL_DEPARTURE.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = CLEAN_ARRET_DE_COURTOISIE.matcher(gStopName).replaceAll(CLEAN_ARRET_DE_COURTOISIE_REPLACEMENT); gStopName = CleanUtils.SAINT.matcher(gStopName).replaceAll(CleanUtils.SAINT_REPLACEMENT); gStopName = CleanUtils.CLEAN_ET.matcher(gStopName).replaceAll(CleanUtils.CLEAN_ET_REPLACEMENT); gStopName = CleanUtils.cleanSlashes(gStopName); gStopName = CleanUtils.removePoints(gStopName); gStopName = CleanUtils.cleanStreetTypesFRCA(gStopName); return CleanUtils.cleanLabelFR(gStopName); } @Override public String getStopCode(GStop gStop) { if (StringUtils.isEmpty(gStop.getStopCode())) { return String.valueOf(gStop.getStopId()); // use stop ID as stop code } return super.getStopCode(gStop); } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); @Override public int getStopId(GStop gStop) { if (!Utils.isDigitsOnly(gStop.getStopId())) { Matcher matcher = DIGITS.matcher(gStop.getStopId()); if (matcher.find()) { int digits = Integer.parseInt(matcher.group()); if (gStop.getStopId().toLowerCase(Locale.ENGLISH).endsWith("a")) { return 100000 + digits; } } System.out.printf("\nUnexpected stop ID for %s!\n", gStop); System.exit(-1); return -1; } return super.getStopId(gStop); } }
Compatibility with latest update.
src/org/mtransit/parser/ca_gatineau_sto_bus/GatineauSTOBusAgencyTools.java
Compatibility with latest update.
<ide><path>rc/org/mtransit/parser/ca_gatineau_sto_bus/GatineauSTOBusAgencyTools.java <ide> case 739: return SCHOOL_BUS_COLOR; <ide> case 800: return PEAK_COLOR; // RAPIBUS_COLOR <ide> case 810: return PEAK_COLOR; // RAPIBUS_COLOR <add> case 870: return PEAK_COLOR; // RAPIBUS_COLOR // TODO ?? <ide> case 901: return null; <ide> // @formatter:on <ide> } <ide> })) // <ide> .compileBothTripSort()); <ide> map2.put(439l, new RouteTripSpec(439l, // <del> MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, "École De L'île", // <add> MDirectionType.EAST.intValue(), MTrip.HEADSIGN_TYPE_STRING, ECOLE_SECONDAIRE_DE_L_ILE_SHORT, // <ide> MDirectionType.WEST.intValue(), MTrip.HEADSIGN_TYPE_STRING, PLATEAU) // <ide> .addTripSort(MDirectionType.EAST.intValue(), // <ide> Arrays.asList(new String[] { // <ide> .addTripSort(MDirectionType.WEST.intValue(), // <ide> Arrays.asList(new String[] { // <ide> "1298", "1075" // <add> })) // <add> .compileBothTripSort()); <add> map2.put(870l, new RouteTripSpec(870l, // <add> MDirectionType.NORTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Arena Guertin", // <add> MDirectionType.SOUTH.intValue(), MTrip.HEADSIGN_TYPE_STRING, "Wellington/Metcalfe") // <add> .addTripSort(MDirectionType.NORTH.intValue(), // <add> Arrays.asList(new String[] { // <add> "5030", // WELLINGTON/METCALFE nord <add> "2643", // SAINT-RÉDEMPTEUR/ALLARD ouest <add> })) // <add> .addTripSort(MDirectionType.SOUTH.intValue(), // <add> Arrays.asList(new String[] { // <add> "2643", // SAINT-RÉDEMPTEUR/ALLARD ouest <add> "5032", // WELLINGTON/METCALFE sud <ide> })) // <ide> .compileBothTripSort()); <ide> ALL_ROUTE_TRIPS2 = map2;
JavaScript
mit
11cb0281a6f3510330d3b2f923c285f21bbee2cc
0
FCOO/modernizr-mq-device,FCOO/modernizr-device,NielsHolt/media-queries,FCOO/device-modernizr,FCOO/device-modernizr,FCOO/modernizr-mq-device,FCOO/modernizr-device,NielsHolt/media-queries
module.exports = function(grunt) { "use strict"; var stripJsonComments = require('strip-json-comments'); var semver = require('semver'); function readFile(filename, isJSON, defaultContents){ if (grunt.file.exists(filename)){ var contents = grunt.file.read(filename) ; return isJSON ? JSON.parse( stripJsonComments(contents) ) : contents; } else return defaultContents; } //******************************************************* // Variables to define the type of repository var gruntfile_setup = readFile('Gruntfile_setup.json', true, { isApplication : false, //true for stand-alone applications. false for packages/plugins haveStyleSheet : false, //true if the packages have css and/or scss-files exitOnJSHintError : true //if false any error in JSHint will not exit the task }), isApplication = gruntfile_setup.isApplication, haveStyleSheet = gruntfile_setup.haveStyleSheet, //new variable for easy syntax isPackage = !isApplication; //******************************************************* var today = grunt.template.today("yyyy-mm-dd-HH-MM-ss"), todayStr = grunt.template.today("dd-mmm-yyyy HH:MM"), //pkg = grunt.file.readJSON('package.json'), bwr = grunt.file.readJSON('bower.json'), currentVersion = bwr.version, name = bwr.name, adjustedName = name.toLowerCase().replace(' ','_'), name_today = adjustedName +'_' + today, githubTasks = []; //Capture the log.header function to remove the 'Running tast SOMETHING" message grunt.log.header = function(txt){ grunt.log.writeln('-'+txt+'-'); }; //merge: Merge all the options given into a new object function merge(){ var result = {}; for(var i=0; i<arguments.length; i++) for(var key in arguments[i]) if(arguments[i].hasOwnProperty(key)) result[key] = arguments[i][key]; return result; } function srcExclude_(mask){ mask = typeof mask === 'string' ? [mask] : mask; mask.push('!**/_*/**', '!**/_*.*'); return mask; } var src_to_src_files = { expand: true, cwd: 'src', dest: 'src' }, //src/**/*.* => src/**/*.* temp_to_temp_files = { expand: true, cwd: 'temp', dest: 'temp' }, //temp/**/*.* => temp/**/*.* temp_to_temp_dist_files = { expand: true, cwd: 'temp', dest: 'temp_dist' }, //temp/**/*.* => temp_dist/**/*.* // temp_dist_to_dist_files = { expand: true, cwd: 'temp_dist', dest: 'dist' }, //temp_dist/**/*.* => dist/**/*.* sass_to_css_files = { src: srcExclude_('**/*.scss'), ext: '.css' }, //*.scss => *.css src_sass_to_src_css_files = merge( src_to_src_files, sass_to_css_files ), //src/*.scss => src/*.css temp_sass_to_temp_css_files = merge( temp_to_temp_files, sass_to_css_files ), //temp/*.scss => temp/*.css bower_concat_options = readFile('bower_main.json', true, {}), jshint_options = readFile('.jshintrc', true, {}), title = 'fcoo.dk - ' + name, head_contents = '', body_contents = ''; if (isApplication){ //Read the contents for the <HEAD>..</HEAD> and <BODY</BODY> head_contents = readFile('src/head.html', false, ''); body_contents = readFile('src/body.html', false, '<body>BODY IS MISSING</body>'); } //*********************************************** grunt.initConfig({ //** clean ** clean: { temp : ["temp"], temp_dist : ["temp_dist"], dist : ["dist"], temp_disk_jscss : ["temp_dist/*.js", "temp_dist/*.css"] }, //** concat ** concat: { options: { separator: ';' }, temp_to_temp_dist_srcjs: { files: { 'temp_dist/src.js' : ['temp/**/*.js'] } }, temp_to_temp_dist_srccss: { files: { 'temp_dist/src.css' : ['temp/**/*.css'] } }, temp_to_temp_dist_srcminjs: { files: { 'temp_dist/src.min.js' : ['temp/**/*.min.js'] } }, temp_to_temp_dist_srcmincss: { files: { 'temp_dist/src.min.css': ['temp/**/*.min.css'] } }, temp_dist_js_to_appnamejs : { dest: 'dist/'+name_today+'.js', src: ['temp_dist/bower_components.js', 'temp_dist/src.js' ] }, //Combine the src.js and bower_components.js => APPLICATIONNAME_TODAY.js temp_dist_css_to_appnamecss : { dest: 'dist/'+name_today+'.css', src: ['temp_dist/bower_components.css', 'temp_dist/src.css' ] }, //Combine the src.css and bower_components.css => APPLICATIONNAME_TODAY.css temp_dist_minjs_to_appnameminjs : { dest: 'dist/'+name_today+'.min.js', src: ['temp_dist/bower_components.js', 'temp_dist/src.min.js' ] }, //Combine the src.min.js and bower_components.js => APPLICATIONNAME_TODAY.min.js temp_dist_mincss_to_appnamemincss : { dest: 'dist/'+name_today+'.min.css', src: ['temp_dist/bower_components.css', 'temp_dist/src.min.css' ] }, //Combine the src.min.css and bower_components.css => APPLICATIONNAME_TODAY.min.css }, //** copy ** copy: { temp_images_to_temp_dist: merge( temp_to_temp_dist_files, { flatten: true, src: srcExclude_(['**/images/*.*']), dest: 'temp_dist/images' } ), temp_fonts_to_temp_dist : merge( temp_to_temp_dist_files, { flatten: true, src: srcExclude_(['**/fonts/*.*']), dest: 'temp_dist/fonts'} ), temp_dist_to_dist: { expand: true, cwd: 'temp_dist', src: ['**/*.*'], dest: 'dist' }, temp_dist_to_demo: { expand: true, cwd: 'temp_dist', src: ['**/*.*'], dest: 'demo' }, //Copies alle files in src to temp, incl '_*.*' but NOT *.min.js/css src_to_temp : { expand: true, filter: 'isFile', cwd: 'src/', src: ['**/*.*', '!**/*.min.js', '!**/*.min.css'], dest: 'temp' }, //Copy all *.js and *.css from temp_dist to dist temp_dist_jscss_to_dist : { expand: false, filter: 'isFile', cwd: 'temp_dist/', src: ['*.js', '*.css'], dest: 'dist' }, //Copy src/index_TEMPLATE.html to dist/index.html src_indexhtml_to_dist : { expand: false, filter: 'isFile', cwd: '', src: ['src/index_TEMPLATE.html'], dest: 'dist/index.html' }, }, //** rename ** rename: { srcjs_to_namejs: { files: [ {src: ['temp_dist/src.js'], dest: 'temp_dist/'+name+'.js'}, {src: ['temp_dist/src.min.js'], dest: 'temp_dist/'+name+'.min.js'} ] }, srccss_to_namecss: { files: [ {src: ['temp_dist/src.css'], dest: 'temp_dist/'+name+'.css'}, {src: ['temp_dist/src.min.css'], dest: 'temp_dist/'+name+'.min.css'} ] } }, //** sass ** sass: { //check: Check syntax - no files generated check: { options : { noCache : true, sourcemap : 'none', check : true, update : true, }, files: [src_sass_to_src_css_files], }, //compile: Generate css-files with debug-info in same folder as scss-files compile: { options: { //sourcemap : 'auto', sourceMap : true, debugInfo : true, lineNumbers : true, update : false, style : 'expanded', }, files: [src_sass_to_src_css_files], }, //build: Generate 'normal' css-files in /temp build: { options: { debugInfo : false, lineNumbers : false, update : false, noCache : true, sourcemap : 'none', style : 'nested', }, files: [temp_sass_to_temp_css_files], } }, //** bower: Copy all main-files from /bower_components to /temp/. Only used to get all images and fonts into /temp ** bower: { to_temp: { base: 'bower_components', dest: 'temp', options: { checkExistence: false, debugging : false, paths: { bowerDirectory : 'bower_components', bowerrc : '.bowerrc', bowerJson : 'bower.json' } } } }, //** bower_concat ** bower_concat: { options: { separator : ';' }, all: { dest : 'temp_dist/bower_components.js', cssDest : 'temp_dist/bower_components.css', dependencies: bower_concat_options.dependencies || {}, exclude : bower_concat_options.exclude || {}, mainFiles : bower_concat_options.mainFiles || {}, } }, //** jshint ** jshint: { options : merge( { force: !gruntfile_setup.exitOnJSHintError }, jshint_options //All options are placed in .jshintrc allowing jshint to be run as stand-alone command ), all : srcExclude_('src/**/*.js'), //['src/**/*.js'], }, // ** uglify ** uglify: { 'temp_js' : { files: [{ expand: true, filter: 'isFile', src: srcExclude_(['temp/**/*.js', '!**/*.min.js']), dest: '', ext: '.min.js', extDot: 'first' }] } }, // ** cssmin cssmin: { 'temp_css' : { files: [{ expand: true, filter: 'isFile', src: srcExclude_(['temp/**/*.css', '!**/*.min.css']), dest: '', ext: '.min.css', extDot: 'first' }] } }, // ** exec ** exec: { bower_update: 'bower update', npm_install : 'npm install', git_add_all : 'git add -A', git_checkout_master : 'git checkout master', git_checkout_ghpages: 'git checkout gh-pages', git_merge_master : 'git merge master', git_merge: { cmd: function(){ //if (grunt.config('ghpages')) return 'git checkout gh-pages && git merge master && git checkout master'; //else return ''; } } }, // ** replace ** replace: { 'dist_indexhtml_meta': { src : ['dist/index.html'], overwrite : true, replacements: [ {from: '{APPLICATION_NAME}', to: bwr.name }, // {from: '{VERSION}', to: bwr.version }, {from: '{BUILD}', to: todayStr }, {from: '{TITLE}', to: title }, {from: '{HEAD}', to: head_contents }, {from: '{BODY}', to: body_contents }, {from: '{CSS_FILE_NAME}', to: name_today+'.min.css' }, {from: '{JS_FILE_NAME}', to: name_today+'.min.js' } ] }, 'dist_indexhtml_version': { src : ['dist/index.html'], overwrite : true, replacements: [{ from: '{VERSION}', to: bwr.version }] } }, // ** grunt-prompt ** prompt: { github: { options: { questions: [ { config : 'build', type : 'confirm', message : 'Build/compile the '+(isApplication ? 'application' : 'packages')+'?', // Question to ask the user, function needs to return a string, }, { config: 'newVersion', type: 'list', message: 'Current version of "' + name +'" is ' + currentVersion + '. Select new release version:', choices: [ { value: 'patch', name: 'Patch : ' + semver.inc(currentVersion, 'patch') + ' Backwards-compatible bug fixes.' }, { value: 'minor', name: 'Minor : ' + semver.inc(currentVersion, 'minor') + ' Add functionality in a backwards-compatible manner.' }, { value: 'major', name: 'Major : ' + semver.inc(currentVersion, 'major') + ' Incompatible API changes.'}, { value: 'none', name: 'None : No new version. Just commit and push.'}, /* custom version not implemented { value: 'custom', name: 'Custom: ?.?.? Specify version...'} */ ] }, /* custom version not implemented { config : 'newVersion', type : 'input', message : 'What specific version would you like', when : function (answers) { return answers['newVersion'] === 'custom'; }, validate: function (value) { return semver.valid(value) || 'Must be a valid semver, such as 1.2.3'; } }, */ { config : 'ghpages', type : 'confirm', message : 'Merge "master" branch into "gh-pages" branch?', }, { config : 'commitMessage', type : 'input', message : 'Message/description for new version:', }, ] } }, //end of prompt.version continue: { options: { questions: [{ config : 'continue', type : 'confirm', message : 'Continue?', }] } }, //end of prompt.continue /* target: { options: { questions: [ { config: 'config.name', // arbitrary name or config for any other grunt task type: 'input', // list, checkbox, confirm, input, password message: 'String|function()', // Question to ask the user, function needs to return a string, default: 'default-value', // default value if nothing is entered choices: 'Array|function(answers)', validate: function(value){return true;}, // return true if valid, error message if invalid. works only with type:input filter: function(value){return value}, // modify the answer when: function(answers){return true} // only ask this question when this function returns true } ] } }, */ }, // ** grunt-release ** release: { options: { bump : true, file : 'bower.json', additionalFiles : ['package.json'], add : true, addFiles: ['.'], commit : true, push : true, tag : true, tagName : '<%= version %>', pushTags: true, npm : false, npmtag : false, commitMessage : 'Release <%= version %>', tagMessage : 'Version <%= version %>', beforeBump : [], // optional grunt tasks to run before file versions are bumped afterBump : ['replace:dist_indexhtml_version'], // optional grunt tasks to run after file versions are bumped beforeRelease : ['exec:git_add_all', 'exec:git_merge' /*'github_merge'*/], // optional grunt tasks to run after release version is bumped up but before release is packaged afterRelease : [], // optional grunt tasks to run after release is packaged updateVars : ['bwr'], // optional grunt config objects to update (this will update/set the version property on the object specified) /************************* //github: {..} obmitted github: { apiRoot : 'https://github.com', repo : 'fcoo/dette-er-en-github-test', accessTokenVar: 'GITHUB_ACCESS_TOKEN' //ENVIRONMENT VARIABLE that contains GitHub Access Token } **************************/ } } });//end of grunt.initConfig({... //**************************************************************** require('load-grunt-tasks')(grunt); //Load grunt-packages grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-rename'); grunt.loadNpmTasks('grunt-text-replace'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-continue'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('main-bower-files'); grunt.loadNpmTasks('grunt-bower-concat'); grunt.loadNpmTasks('grunt-exec'); grunt.loadNpmTasks('grunt-release'); grunt.loadNpmTasks('grunt-prompt'); //********************************************************* //CREATE THE "DEFAULT" TAST //********************************************************* grunt.registerTask('default', function() { grunt.log.writeln('*************************************************************************'); grunt.log.writeln('Run one of the following commands:'); grunt.log.writeln('>grunt check => Check the syntax of all .js and .scss files'); grunt.log.writeln('>grunt dev => Creates a development version'); grunt.log.writeln('>grunt prod => Creates a production version in /dist'); grunt.log.writeln('>grunt github => Create a new Github release incl. new version and tag'); grunt.log.writeln('*************************************************************************'); }); //********************************************************* //CREATE THE "CHECK" TAST //********************************************************* //'jshint:all' = Check the syntax of all .js-files with jshint //'sass:check' = Check the syntax of all .scss-files in scr if (haveStyleSheet) grunt.registerTask('check', ['jshint:all', 'sass:check'] ); else grunt.registerTask('check', 'jshint:all'); //********************************************************* //CREATE THE "GITHUB" TAST //********************************************************* //_github_confirm: write all selected action grunt.registerTask('_github_confirm', function() { githubTasks = []; grunt.log.writeln('**************************************************'); grunt.log.writeln('Actions:'); if (grunt.config('build')){ grunt.log.writeln('- Build/compile the '+(isApplication ? 'application' : 'packages')); githubTasks.push('prod'); } if (grunt.config('newVersion') != 'none'){ grunt.log.writeln('- Commit all files and create new tag="v'+semver.inc(currentVersion, grunt.config('newVersion'))+'"'); var postMessage = '" -m "' + (grunt.config('commitMessage') === '' ? '' : grunt.config('commitMessage') + '" -m "') + 'Released by '+bwr.authors+' ' +todayStr; grunt.config.set('release.options.commitMessage', 'Release <%= version %>' + postMessage); grunt.config.set('release.options.tagMessage', 'Version <%= version %>' + postMessage); githubTasks.push('release:'+grunt.config('newVersion')); } else { grunt.log.writeln('- Commit all files'); grunt.config.set('release.options.commitMessage', grunt.config('commitMessage') || '* No message *'); grunt.config.set('release.options.bump', false); grunt.config.set('release.options.beforeBump', []); grunt.config.set('release.options.afterBump', []); grunt.config.set('release.options.tag', false); grunt.config.set('release.options.pushTags', false); githubTasks.push('release'); } if (grunt.config('ghpages')) grunt.log.writeln('- Merge "master" branch into "gh-pages" branch'); if (grunt.config('newVersion') != 'none') grunt.log.writeln('- Push all branches and tags to GitHub'); else grunt.log.writeln('- Push all branches to GitHub'); grunt.log.writeln('**************************************************'); }); grunt.registerTask('NIELS', function(){ grunt.log.writeln('NIELS'); }); //github_merge grunt.registerTask('github_merge', function(){ grunt.log.writeln('ghpages='+grunt.config('ghpages')); if (grunt.config('ghpages')) grunt.task.run([ 'exec:git_checkout_ghpages', 'exec:git_merge_master', 'exec:git_checkout_master' ]); }); //_github_run_tasks: if confirm is true => run the github tasks (githubTasks) grunt.registerTask('_github_run_tasks', function() { if (grunt.config('continue')) grunt.task.run(githubTasks); }); grunt.registerTask('github', [ 'prompt:github', '_github_confirm', 'prompt:continue', '_github_run_tasks' ] ); //********************************************************* //CREATE THE "DEV" AND "PROD" TAST //********************************************************* var tasks = [], isProdTasks = true, isDevTasks; for (var i=0; i<2; i++ ){ tasks = []; isDevTasks = !isProdTasks; //ALWAYS CLEAN /temp, AND /temp_dist AND CHECK SYNTAX tasks.push( 'clean:temp', 'clean:temp_dist', 'check' ); //BUILD JS (AND CSS) FROM SRC if (isProdTasks){ tasks.push( 'clean:dist', 'copy:src_to_temp', //Copy all ** from src to temp 'concat:temp_to_temp_dist_srcjs', //Concat all *.js files from temp into temp_dist/src.js 'uglify:temp_js', //Minify *.js 'concat:temp_to_temp_dist_srcminjs' //Concat all *.min.js files from temp into temp_dist/src.min.js ); if (haveStyleSheet) tasks.push( 'sass:build', //compile all sass 'concat:temp_to_temp_dist_srccss', //Concat all *.css files from temp into temp_dist/src.css 'cssmin:temp_css', //Minify all *.css (but not *.min.css) to *.min.css 'concat:temp_to_temp_dist_srcmincss' //Concat all *.min.css files from temp into temp_dist/src.min.css ); tasks.push( 'copy:temp_images_to_temp_dist', //Copy all image-files from temp to temp_dist/images 'copy:temp_fonts_to_temp_dist', //Copy all font-files from temp to temp_dist/fonts 'clean:temp' //clean /temp ); } //end of if (isProdTasks){... //BUILD BOWER COMPONENTS if (isDevTasks || isApplication){ //Build bower_components.js/css and /images, and /fonts from the bower components tasks.push( 'clean:temp', //clean /temp 'exec:bower_update', //Update all bower components 'bower', //Copy all "main" files to /temp 'bower_concat' //Create bower_components.js and bower_components.css in temp_dist ); tasks.push( 'copy:temp_images_to_temp_dist', //Copy all image-files from temp to temp_dist/images 'copy:temp_fonts_to_temp_dist', //Copy all font-files from temp to temp_dist/fonts 'clean:temp' //clean /temp ); } //MODIFY (RENAME AND/OR MOVE) FILES IN TEMP_DIST BEFORE THEY ARE MOVED TO DIST if (isApplication && isProdTasks){ //Concat js/css files to APPLICATIONNAME_TODAY[.min].js/css in DIST and delete from test_dist tasks.push( 'concat:temp_dist_js_to_appnamejs', //Combine the src.js and bower_components.js => APPLICATIONNAME_TODAY.js 'concat:temp_dist_css_to_appnamecss', //Combine the src.css and bower_components.css => APPLICATIONNAME_TODAY.css 'concat:temp_dist_minjs_to_appnameminjs', //Combine the src.min.js and bower_components.js => APPLICATIONNAME_TODAY.min.js 'concat:temp_dist_mincss_to_appnamemincss', //Combine the src.min.css and bower_components.css => APPLICATIONNAME_TODAY.min.css 'copy:src_indexhtml_to_dist', //Copy index_TEMPLATE.html from src => dist 'replace:dist_indexhtml_meta', //Insert meta-data and links into dist/index.html 'clean:temp_disk_jscss' //Delete *.js/css from temp_dist ); } if (isPackage && isProdTasks){ //Rename all src.* to "name".* tasks.push('rename:srcjs_to_namejs'); if (haveStyleSheet) tasks.push('rename:srccss_to_namecss'); } if (isPackage && isDevTasks){ tasks.push( 'copy:temp_dist_to_demo' ); //Copy all files from temp_dist to demo } if (isProdTasks){ tasks.push( 'copy:temp_dist_to_dist' ); //Copy all files from temp_dist to dist } if (isApplication && isDevTasks){ //TODO - } tasks.push( 'clean:temp_dist'); //Register tasks grunt.registerTask(isProdTasks ? 'prod' : 'dev' , tasks); isProdTasks = !isProdTasks; } };
gruntfile.js
module.exports = function(grunt) { "use strict"; var stripJsonComments = require('strip-json-comments'); var semver = require('semver'); function readFile(filename, isJSON, defaultContents){ if (grunt.file.exists(filename)){ var contents = grunt.file.read(filename) ; return isJSON ? JSON.parse( stripJsonComments(contents) ) : contents; } else return defaultContents; } //******************************************************* // Variables to define the type of repository var gruntfile_setup = readFile('Gruntfile_setup.json', true, { isApplication : false, //true for stand-alone applications. false for packages/plugins haveStyleSheet : false, //true if the packages have css and/or scss-files exitOnJSHintError : true //if false any error in JSHint will not exit the task }), isApplication = gruntfile_setup.isApplication, haveStyleSheet = gruntfile_setup.haveStyleSheet, //new variable for easy syntax isPackage = !isApplication; //******************************************************* var today = grunt.template.today("yyyy-mm-dd-HH-MM-ss"), todayStr = grunt.template.today("dd-mmm-yyyy HH:MM"), //pkg = grunt.file.readJSON('package.json'), bwr = grunt.file.readJSON('bower.json'), currentVersion = bwr.version, name = bwr.name, adjustedName = name.toLowerCase().replace(' ','_'), name_today = adjustedName +'_' + today, githubTasks = []; //Capture the log.header function to remove the 'Running tast SOMETHING" message grunt.log.header = function(txt){ grunt.log.writeln('-'+txt+'-'); }; //merge: Merge all the options given into a new object function merge(){ var result = {}; for(var i=0; i<arguments.length; i++) for(var key in arguments[i]) if(arguments[i].hasOwnProperty(key)) result[key] = arguments[i][key]; return result; } function srcExclude_(mask){ mask = typeof mask === 'string' ? [mask] : mask; mask.push('!**/_*/**', '!**/_*.*'); return mask; } var src_to_src_files = { expand: true, cwd: 'src', dest: 'src' }, //src/**/*.* => src/**/*.* temp_to_temp_files = { expand: true, cwd: 'temp', dest: 'temp' }, //temp/**/*.* => temp/**/*.* temp_to_temp_dist_files = { expand: true, cwd: 'temp', dest: 'temp_dist' }, //temp/**/*.* => temp_dist/**/*.* // temp_dist_to_dist_files = { expand: true, cwd: 'temp_dist', dest: 'dist' }, //temp_dist/**/*.* => dist/**/*.* sass_to_css_files = { src: srcExclude_('**/*.scss'), ext: '.css' }, //*.scss => *.css src_sass_to_src_css_files = merge( src_to_src_files, sass_to_css_files ), //src/*.scss => src/*.css temp_sass_to_temp_css_files = merge( temp_to_temp_files, sass_to_css_files ), //temp/*.scss => temp/*.css bower_concat_options = readFile('bower_main.json', true, {}), jshint_options = readFile('.jshintrc', true, {}), title = 'fcoo.dk - ' + name, head_contents = '', body_contents = ''; if (isApplication){ //Read the contents for the <HEAD>..</HEAD> and <BODY</BODY> head_contents = readFile('src/head.html', false, ''); body_contents = readFile('src/body.html', false, '<body>BODY IS MISSING</body>'); } //*********************************************** grunt.initConfig({ //** clean ** clean: { temp : ["temp"], temp_dist : ["temp_dist"], dist : ["dist"], temp_disk_jscss : ["temp_dist/*.js", "temp_dist/*.css"] }, //** concat ** concat: { options: { separator: ';' }, temp_to_temp_dist_srcjs: { files: { 'temp_dist/src.js' : ['temp/**/*.js'] } }, temp_to_temp_dist_srccss: { files: { 'temp_dist/src.css' : ['temp/**/*.css'] } }, temp_to_temp_dist_srcminjs: { files: { 'temp_dist/src.min.js' : ['temp/**/*.min.js'] } }, temp_to_temp_dist_srcmincss: { files: { 'temp_dist/src.min.css': ['temp/**/*.min.css'] } }, temp_dist_js_to_appnamejs : { dest: 'dist/'+name_today+'.js', src: ['temp_dist/bower_components.js', 'temp_dist/src.js' ] }, //Combine the src.js and bower_components.js => APPLICATIONNAME_TODAY.js temp_dist_css_to_appnamecss : { dest: 'dist/'+name_today+'.css', src: ['temp_dist/bower_components.css', 'temp_dist/src.css' ] }, //Combine the src.css and bower_components.css => APPLICATIONNAME_TODAY.css temp_dist_minjs_to_appnameminjs : { dest: 'dist/'+name_today+'.min.js', src: ['temp_dist/bower_components.js', 'temp_dist/src.min.js' ] }, //Combine the src.min.js and bower_components.js => APPLICATIONNAME_TODAY.min.js temp_dist_mincss_to_appnamemincss : { dest: 'dist/'+name_today+'.min.css', src: ['temp_dist/bower_components.css', 'temp_dist/src.min.css' ] }, //Combine the src.min.css and bower_components.css => APPLICATIONNAME_TODAY.min.css }, //** copy ** copy: { temp_images_to_temp_dist: merge( temp_to_temp_dist_files, { flatten: true, src: srcExclude_(['**/images/*.*']), dest: 'temp_dist/images' } ), temp_fonts_to_temp_dist : merge( temp_to_temp_dist_files, { flatten: true, src: srcExclude_(['**/fonts/*.*']), dest: 'temp_dist/fonts'} ), temp_dist_to_dist: { expand: true, cwd: 'temp_dist', src: ['**/*.*'], dest: 'dist' }, temp_dist_to_demo: { expand: true, cwd: 'temp_dist', src: ['**/*.*'], dest: 'demo' }, //Copies alle files in src to temp, incl '_*.*' but NOT *.min.js/css src_to_temp : { expand: true, filter: 'isFile', cwd: 'src/', src: ['**/*.*', '!**/*.min.js', '!**/*.min.css'], dest: 'temp' }, //Copy all *.js and *.css from temp_dist to dist temp_dist_jscss_to_dist : { expand: false, filter: 'isFile', cwd: 'temp_dist/', src: ['*.js', '*.css'], dest: 'dist' }, //Copy src/index_TEMPLATE.html to dist/index.html src_indexhtml_to_dist : { expand: false, filter: 'isFile', cwd: '', src: ['src/index_TEMPLATE.html'], dest: 'dist/index.html' }, }, //** rename ** rename: { srcjs_to_namejs: { files: [ {src: ['temp_dist/src.js'], dest: 'temp_dist/'+name+'.js'}, {src: ['temp_dist/src.min.js'], dest: 'temp_dist/'+name+'.min.js'} ] }, srccss_to_namecss: { files: [ {src: ['temp_dist/src.css'], dest: 'temp_dist/'+name+'.css'}, {src: ['temp_dist/src.min.css'], dest: 'temp_dist/'+name+'.min.css'} ] } }, //** sass ** sass: { //check: Check syntax - no files generated check: { options : { noCache : true, sourcemap : 'none', check : true, update : true, }, files: [src_sass_to_src_css_files], }, //compile: Generate css-files with debug-info in same folder as scss-files compile: { options: { //sourcemap : 'auto', sourceMap : true, debugInfo : true, lineNumbers : true, update : false, style : 'expanded', }, files: [src_sass_to_src_css_files], }, //build: Generate 'normal' css-files in /temp build: { options: { debugInfo : false, lineNumbers : false, update : false, noCache : true, sourcemap : 'none', style : 'nested', }, files: [temp_sass_to_temp_css_files], } }, //** bower: Copy all main-files from /bower_components to /temp/. Only used to get all images and fonts into /temp ** bower: { to_temp: { base: 'bower_components', dest: 'temp', options: { checkExistence: false, debugging : false, paths: { bowerDirectory : 'bower_components', bowerrc : '.bowerrc', bowerJson : 'bower.json' } } } }, //** bower_concat ** bower_concat: { options: { separator : ';' }, all: { dest : 'temp_dist/bower_components.js', cssDest : 'temp_dist/bower_components.css', dependencies: bower_concat_options.dependencies || {}, exclude : bower_concat_options.exclude || {}, mainFiles : bower_concat_options.mainFiles || {}, } }, //** jshint ** jshint: { options : merge( { force: !gruntfile_setup.exitOnJSHintError }, jshint_options //All options are placed in .jshintrc allowing jshint to be run as stand-alone command ), all : srcExclude_('src/**/*.js'), //['src/**/*.js'], }, // ** uglify ** uglify: { 'temp_js' : { files: [{ expand: true, filter: 'isFile', src: srcExclude_(['temp/**/*.js', '!**/*.min.js']), dest: '', ext: '.min.js', extDot: 'first' }] } }, // ** cssmin cssmin: { 'temp_css' : { files: [{ expand: true, filter: 'isFile', src: srcExclude_(['temp/**/*.css', '!**/*.min.css']), dest: '', ext: '.min.css', extDot: 'first' }] } }, // ** exec ** exec: { bower_update: 'bower update', npm_install : 'npm install', git_add_all : 'git add -A', git_checkout_master : 'git checkout master', git_checkout_ghpages: 'git checkout gh-pages', git_merge_master : 'git merge master', git_merge: { cmd: function(){ if (grunt.config('ghpages')) return 'git checkout gh-pages && git merge master && git checkout master'; else return ''; } } }, // ** replace ** replace: { 'dist_indexhtml_meta': { src : ['dist/index.html'], overwrite : true, replacements: [ {from: '{APPLICATION_NAME}', to: bwr.name }, // {from: '{VERSION}', to: bwr.version }, {from: '{BUILD}', to: todayStr }, {from: '{TITLE}', to: title }, {from: '{HEAD}', to: head_contents }, {from: '{BODY}', to: body_contents }, {from: '{CSS_FILE_NAME}', to: name_today+'.min.css' }, {from: '{JS_FILE_NAME}', to: name_today+'.min.js' } ] }, 'dist_indexhtml_version': { src : ['dist/index.html'], overwrite : true, replacements: [{ from: '{VERSION}', to: bwr.version }] } }, // ** grunt-prompt ** prompt: { github: { options: { questions: [ { config : 'build', type : 'confirm', message : 'Build/compile the '+(isApplication ? 'application' : 'packages')+'?', // Question to ask the user, function needs to return a string, }, { config: 'newVersion', type: 'list', message: 'Current version of "' + name +'" is ' + currentVersion + '. Select new release version:', choices: [ { value: 'patch', name: 'Patch : ' + semver.inc(currentVersion, 'patch') + ' Backwards-compatible bug fixes.' }, { value: 'minor', name: 'Minor : ' + semver.inc(currentVersion, 'minor') + ' Add functionality in a backwards-compatible manner.' }, { value: 'major', name: 'Major : ' + semver.inc(currentVersion, 'major') + ' Incompatible API changes.'}, { value: 'none', name: 'None : No new version. Just commit and push.'}, /* custom version not implemented { value: 'custom', name: 'Custom: ?.?.? Specify version...'} */ ] }, /* custom version not implemented { config : 'newVersion', type : 'input', message : 'What specific version would you like', when : function (answers) { return answers['newVersion'] === 'custom'; }, validate: function (value) { return semver.valid(value) || 'Must be a valid semver, such as 1.2.3'; } }, */ { config : 'ghpages', type : 'confirm', message : 'Merge "master" branch into "gh-pages" branch?', }, { config : 'commitMessage', type : 'input', message : 'Message/description for new version:', }, ] } }, //end of prompt.version continue: { options: { questions: [{ config : 'continue', type : 'confirm', message : 'Continue?', }] } }, //end of prompt.continue /* target: { options: { questions: [ { config: 'config.name', // arbitrary name or config for any other grunt task type: 'input', // list, checkbox, confirm, input, password message: 'String|function()', // Question to ask the user, function needs to return a string, default: 'default-value', // default value if nothing is entered choices: 'Array|function(answers)', validate: function(value){return true;}, // return true if valid, error message if invalid. works only with type:input filter: function(value){return value}, // modify the answer when: function(answers){return true} // only ask this question when this function returns true } ] } }, */ }, // ** grunt-release ** release: { options: { bump : true, file : 'bower.json', additionalFiles : ['package.json'], add : true, addFiles: ['.'], commit : true, push : true, tag : true, tagName : '<%= version %>', pushTags: true, npm : false, npmtag : false, commitMessage : 'Release <%= version %>', tagMessage : 'Version <%= version %>', beforeBump : [], // optional grunt tasks to run before file versions are bumped afterBump : ['replace:dist_indexhtml_version'], // optional grunt tasks to run after file versions are bumped beforeRelease : ['exec:git_add_all', 'exec:git_merge' /*'github_merge'*/], // optional grunt tasks to run after release version is bumped up but before release is packaged afterRelease : [], // optional grunt tasks to run after release is packaged updateVars : ['bwr'], // optional grunt config objects to update (this will update/set the version property on the object specified) /************************* //github: {..} obmitted github: { apiRoot : 'https://github.com', repo : 'fcoo/dette-er-en-github-test', accessTokenVar: 'GITHUB_ACCESS_TOKEN' //ENVIRONMENT VARIABLE that contains GitHub Access Token } **************************/ } } });//end of grunt.initConfig({... //**************************************************************** require('load-grunt-tasks')(grunt); //Load grunt-packages grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-rename'); grunt.loadNpmTasks('grunt-text-replace'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-continue'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-sass'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('main-bower-files'); grunt.loadNpmTasks('grunt-bower-concat'); grunt.loadNpmTasks('grunt-exec'); grunt.loadNpmTasks('grunt-release'); grunt.loadNpmTasks('grunt-prompt'); //********************************************************* //CREATE THE "DEFAULT" TAST //********************************************************* grunt.registerTask('default', function() { grunt.log.writeln('*************************************************************************'); grunt.log.writeln('Run one of the following commands:'); grunt.log.writeln('>grunt check => Check the syntax of all .js and .scss files'); grunt.log.writeln('>grunt dev => Creates a development version'); grunt.log.writeln('>grunt prod => Creates a production version in /dist'); grunt.log.writeln('>grunt github => Create a new Github release incl. new version and tag'); grunt.log.writeln('*************************************************************************'); }); //********************************************************* //CREATE THE "CHECK" TAST //********************************************************* //'jshint:all' = Check the syntax of all .js-files with jshint //'sass:check' = Check the syntax of all .scss-files in scr if (haveStyleSheet) grunt.registerTask('check', ['jshint:all', 'sass:check'] ); else grunt.registerTask('check', 'jshint:all'); //********************************************************* //CREATE THE "GITHUB" TAST //********************************************************* //_github_confirm: write all selected action grunt.registerTask('_github_confirm', function() { githubTasks = []; grunt.log.writeln('**************************************************'); grunt.log.writeln('Actions:'); if (grunt.config('build')){ grunt.log.writeln('- Build/compile the '+(isApplication ? 'application' : 'packages')); githubTasks.push('prod'); } if (grunt.config('newVersion') != 'none'){ grunt.log.writeln('- Commit all files and create new tag="v'+semver.inc(currentVersion, grunt.config('newVersion'))+'"'); var postMessage = '" -m "' + (grunt.config('commitMessage') === '' ? '' : grunt.config('commitMessage') + '" -m "') + 'Released by '+bwr.authors+' ' +todayStr; grunt.config.set('release.options.commitMessage', 'Release <%= version %>' + postMessage); grunt.config.set('release.options.tagMessage', 'Version <%= version %>' + postMessage); githubTasks.push('release:'+grunt.config('newVersion')); } else { grunt.log.writeln('- Commit all files'); grunt.config.set('release.options.commitMessage', grunt.config('commitMessage') || '* No message *'); grunt.config.set('release.options.bump', false); grunt.config.set('release.options.beforeBump', []); grunt.config.set('release.options.afterBump', []); grunt.config.set('release.options.tag', false); grunt.config.set('release.options.pushTags', false); githubTasks.push('release'); } if (grunt.config('ghpages')) grunt.log.writeln('- Merge "master" branch into "gh-pages" branch'); if (grunt.config('newVersion') != 'none') grunt.log.writeln('- Push all branches and tags to GitHub'); else grunt.log.writeln('- Push all branches to GitHub'); grunt.log.writeln('**************************************************'); }); grunt.registerTask('NIELS', function(){ grunt.log.writeln('NIELS'); }); //github_merge grunt.registerTask('github_merge', function(){ grunt.log.writeln('ghpages='+grunt.config('ghpages')); if (grunt.config('ghpages')) grunt.task.run([ 'exec:git_checkout_ghpages', 'exec:git_merge_master', 'exec:git_checkout_master' ]); }); //_github_run_tasks: if confirm is true => run the github tasks (githubTasks) grunt.registerTask('_github_run_tasks', function() { if (grunt.config('continue')) grunt.task.run(githubTasks); }); grunt.registerTask('github', [ 'prompt:github', '_github_confirm', 'prompt:continue', '_github_run_tasks' ] ); //********************************************************* //CREATE THE "DEV" AND "PROD" TAST //********************************************************* var tasks = [], isProdTasks = true, isDevTasks; for (var i=0; i<2; i++ ){ tasks = []; isDevTasks = !isProdTasks; //ALWAYS CLEAN /temp, AND /temp_dist AND CHECK SYNTAX tasks.push( 'clean:temp', 'clean:temp_dist', 'check' ); //BUILD JS (AND CSS) FROM SRC if (isProdTasks){ tasks.push( 'clean:dist', 'copy:src_to_temp', //Copy all ** from src to temp 'concat:temp_to_temp_dist_srcjs', //Concat all *.js files from temp into temp_dist/src.js 'uglify:temp_js', //Minify *.js 'concat:temp_to_temp_dist_srcminjs' //Concat all *.min.js files from temp into temp_dist/src.min.js ); if (haveStyleSheet) tasks.push( 'sass:build', //compile all sass 'concat:temp_to_temp_dist_srccss', //Concat all *.css files from temp into temp_dist/src.css 'cssmin:temp_css', //Minify all *.css (but not *.min.css) to *.min.css 'concat:temp_to_temp_dist_srcmincss' //Concat all *.min.css files from temp into temp_dist/src.min.css ); tasks.push( 'copy:temp_images_to_temp_dist', //Copy all image-files from temp to temp_dist/images 'copy:temp_fonts_to_temp_dist', //Copy all font-files from temp to temp_dist/fonts 'clean:temp' //clean /temp ); } //end of if (isProdTasks){... //BUILD BOWER COMPONENTS if (isDevTasks || isApplication){ //Build bower_components.js/css and /images, and /fonts from the bower components tasks.push( 'clean:temp', //clean /temp 'exec:bower_update', //Update all bower components 'bower', //Copy all "main" files to /temp 'bower_concat' //Create bower_components.js and bower_components.css in temp_dist ); tasks.push( 'copy:temp_images_to_temp_dist', //Copy all image-files from temp to temp_dist/images 'copy:temp_fonts_to_temp_dist', //Copy all font-files from temp to temp_dist/fonts 'clean:temp' //clean /temp ); } //MODIFY (RENAME AND/OR MOVE) FILES IN TEMP_DIST BEFORE THEY ARE MOVED TO DIST if (isApplication && isProdTasks){ //Concat js/css files to APPLICATIONNAME_TODAY[.min].js/css in DIST and delete from test_dist tasks.push( 'concat:temp_dist_js_to_appnamejs', //Combine the src.js and bower_components.js => APPLICATIONNAME_TODAY.js 'concat:temp_dist_css_to_appnamecss', //Combine the src.css and bower_components.css => APPLICATIONNAME_TODAY.css 'concat:temp_dist_minjs_to_appnameminjs', //Combine the src.min.js and bower_components.js => APPLICATIONNAME_TODAY.min.js 'concat:temp_dist_mincss_to_appnamemincss', //Combine the src.min.css and bower_components.css => APPLICATIONNAME_TODAY.min.css 'copy:src_indexhtml_to_dist', //Copy index_TEMPLATE.html from src => dist 'replace:dist_indexhtml_meta', //Insert meta-data and links into dist/index.html 'clean:temp_disk_jscss' //Delete *.js/css from temp_dist ); } if (isPackage && isProdTasks){ //Rename all src.* to "name".* tasks.push('rename:srcjs_to_namejs'); if (haveStyleSheet) tasks.push('rename:srccss_to_namecss'); } if (isPackage && isDevTasks){ tasks.push( 'copy:temp_dist_to_demo' ); //Copy all files from temp_dist to demo } if (isProdTasks){ tasks.push( 'copy:temp_dist_to_dist' ); //Copy all files from temp_dist to dist } if (isApplication && isDevTasks){ //TODO - } tasks.push( 'clean:temp_dist'); //Register tasks grunt.registerTask(isProdTasks ? 'prod' : 'dev' , tasks); isProdTasks = !isProdTasks; } };
* No message *
gruntfile.js
* No message *
<ide><path>runtfile.js <ide> <ide> git_merge: { <ide> cmd: function(){ <del> if (grunt.config('ghpages')) <add> //if (grunt.config('ghpages')) <ide> return 'git checkout gh-pages && git merge master && git checkout master'; <del> else <add> //else <ide> return ''; <ide> } <ide> }
Java
apache-2.0
29c1ddc06e39e92598433af6ff1d0a1d657e9d6e
0
Adobe-Consulting-Services/acs-aem-samples,Adobe-Consulting-Services/acs-aem-samples,Adobe-Consulting-Services/acs-aem-samples
package com.adobe.acs.samples.authentication.impl; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.auth.core.spi.AuthenticationFeedbackHandler; import org.apache.sling.auth.core.spi.AuthenticationHandler; import org.apache.sling.auth.core.spi.AuthenticationInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.IOException; import java.util.Map; @Component( label = "ACS AEM Samples - Authentication Login Hook" ) @Properties({ @Property(name = "service.ranking", intValue = 10000), @Property(name = "path", value = "/content") }) @Service public class SampleLoginHookAuthenticationHandler implements AuthenticationHandler, AuthenticationFeedbackHandler { private static final Logger log = LoggerFactory.getLogger(SampleLoginHookAuthenticationHandler.class); @Reference(target = "(service.pid=com.day.crx.security.token.impl.impl.TokenAuthenticationHandler)") private AuthenticationHandler wrappedAuthHandler; private boolean wrappedIsAuthFeedbackHandler = false; @Override public AuthenticationInfo extractCredentials(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { // Wrap the response object to capture any calls to sendRedirect(..) so it can be released in a controlled // manner later. final DeferredRedirectHttpServletResponse deferredRedirectResponse = new DeferredRedirectHttpServletResponse(httpServletRequest, httpServletResponse); return wrappedAuthHandler.extractCredentials(httpServletRequest, deferredRedirectResponse); } @Override public boolean requestCredentials(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { return wrappedAuthHandler.requestCredentials(httpServletRequest, httpServletResponse); } @Override public void dropCredentials(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { wrappedAuthHandler.dropCredentials(httpServletRequest, httpServletResponse); } @Override public void authenticationFailed(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationInfo authenticationInfo) { // Wrap the response so we can release any previously deferred redirects final DeferredRedirectHttpServletResponse deferredRedirectResponse = new DeferredRedirectHttpServletResponse(httpServletRequest, httpServletResponse); if (this.wrappedIsAuthFeedbackHandler) { ((AuthenticationFeedbackHandler) wrappedAuthHandler).authenticationFailed(httpServletRequest, deferredRedirectResponse, authenticationInfo); } try { deferredRedirectResponse.releaseRedirect(); } catch (IOException e) { log.error("Could not release redirect", e); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } @Override public boolean authenticationSucceeded(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationInfo authenticationInfo) { boolean result = false; // Wrap the response so we can release any previously deferred redirects final DeferredRedirectHttpServletResponse deferredRedirectResponse = new DeferredRedirectHttpServletResponse(httpServletRequest, httpServletResponse); if (this.wrappedIsAuthFeedbackHandler) { result = ((AuthenticationFeedbackHandler) wrappedAuthHandler).authenticationSucceeded(httpServletRequest, httpServletResponse, authenticationInfo); } try { deferredRedirectResponse.releaseRedirect(); } catch (IOException e) { log.error("Could not release redirect", e); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return result; } @Activate protected void activate(final Map<String, String> config) { this.wrappedIsAuthFeedbackHandler = false; if (wrappedAuthHandler != null) { log.debug("Registered wrapped authentication feedback handler"); this.wrappedIsAuthFeedbackHandler = wrappedAuthHandler instanceof AuthenticationFeedbackHandler; } } /** * It is not uncommon (Example: OOTB SAML Authentication Handler) for response.sendRedirect(..) to be called * in extractCredentials(..). When sendRedirect(..) is called, the response immediately flushes causing the browser * to redirect. */ private class DeferredRedirectHttpServletResponse extends HttpServletResponseWrapper { private String ATTR_KEY = DeferredRedirectHttpServletResponse.class.getName() + "_redirectLocation"; private HttpServletRequest request = null; public DeferredRedirectHttpServletResponse(final HttpServletRequest request, final HttpServletResponse response) { super(response); this.request = request; } /** * This method captures the redirect request and stores it to the Request so it can be leveraged later. * @param location the location to redirect to */ @Override public void sendRedirect(String location) { // Capture the sendRedirect location, and hold onto it so it can be released later (via releaseRedirect()) this.request.setAttribute(ATTR_KEY, location); } /** * Invokes super.sendRedirect(..) with the value captured in this.sendRedirect(..) * @throws IOException */ public final void releaseRedirect() throws IOException { final String location = (String) this.request.getAttribute(ATTR_KEY); if (location != null) { super.sendRedirect(location); } } } }
bundle/src/main/java/com/adobe/acs/samples/authentication/impl/SampleLoginHookAuthenticationHandler.java
package com.adobe.acs.samples.authentication.impl; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.auth.core.spi.AuthenticationFeedbackHandler; import org.apache.sling.auth.core.spi.AuthenticationHandler; import org.apache.sling.auth.core.spi.AuthenticationInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.IOException; import java.util.Map; @Component( label = "ACS AEM Samples - Authentication Login Hook" ) @Properties({ @Property(name = "service.ranking", intValue = 10000), @Property(name = "path", value = "/content") }) @Service public class SampleLoginHookAuthenticationHandler implements AuthenticationHandler, AuthenticationFeedbackHandler { private static final Logger log = LoggerFactory.getLogger(SampleLoginHookAuthenticationHandler.class); @Reference(target = "(service.pid=com.day.crx.security.token.impl.impl.TokenAuthenticationHandler)") private AuthenticationHandler wrappedAuthHandler; private boolean wrappedIsAuthFeedbackHandler = false; @Override public AuthenticationInfo extractCredentials(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) { // Wrap the response object to capture any calls to sendRedirect(..) so it can be released in a controlled // manner later. final DeferredRedirectHttpServletResponse deferredRedirectResponse = new DeferredRedirectHttpServletResponse(httpServletRequest, httpServletResponse); return wrappedAuthHandler.extractCredentials(httpServletRequest, deferredRedirectResponse); } @Override public boolean requestCredentials(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { return wrappedAuthHandler.requestCredentials(httpServletRequest, httpServletResponse); } @Override public void dropCredentials(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException { wrappedAuthHandler.dropCredentials(httpServletRequest, httpServletResponse); } @Override public void authenticationFailed(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationInfo authenticationInfo) { // Wrap the response so we can release any previously deferred redirects final DeferredRedirectHttpServletResponse deferredRedirectResponse = new DeferredRedirectHttpServletResponse(httpServletRequest, httpServletResponse); if (this.wrappedIsAuthFeedbackHandler) { ((AuthenticationFeedbackHandler) wrappedAuthHandler).authenticationFailed(httpServletRequest, wrappedResponse, authenticationInfo); } try { deferredRedirectResponse.releaseRedirect(); } catch (IOException e) { log.error("Could not release redirect", e); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } @Override public boolean authenticationSucceeded(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationInfo authenticationInfo) { boolean result = false; // Wrap the response so we can release any previously deferred redirects final DeferredRedirectHttpServletResponse deferredRedirectResponse = new DeferredRedirectHttpServletResponse(httpServletRequest, httpServletResponse); if (this.wrappedIsAuthFeedbackHandler) { result = ((AuthenticationFeedbackHandler) wrappedAuthHandler).authenticationSucceeded(httpServletRequest, httpServletResponse, authenticationInfo); } try { deferredRedirectResponse.releaseRedirect(); } catch (IOException e) { log.error("Could not release redirect", e); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return result; } @Activate protected void activate(final Map<String, String> config) { this.wrappedIsAuthFeedbackHandler = false; if (wrappedAuthHandler != null) { log.debug("Registered wrapped authentication feedback handler"); this.wrappedIsAuthFeedbackHandler = wrappedAuthHandler instanceof AuthenticationFeedbackHandler; } } /** * It is not uncommon (Example: OOTB SAML Authentication Handler) for response.sendRedirect(..) to be called * in extractCredentials(..). When sendRedirect(..) is called, the response immediately flushes causing the browser * to redirect. */ private class DeferredRedirectHttpServletResponse extends HttpServletResponseWrapper { private String ATTR_KEY = DeferredRedirectHttpServletResponse.class.getName() + "_redirectLocation"; private HttpServletRequest request = null; public DeferredRedirectHttpServletResponse(final HttpServletRequest request, final HttpServletResponse response) { super(response); this.request = request; } /** * This method captures the redirect request and stores it to the Request so it can be leveraged later. * @param location the location to redirect to */ @Override public void sendRedirect(String location) { // Capture the sendRedirect location, and hold onto it so it can be released later (via releaseRedirect()) this.request.setAttribute(ATTR_KEY, location); } /** * Invokes super.sendRedirect(..) with the value captured in this.sendRedirect(..) * @throws IOException */ public final void releaseRedirect() throws IOException { final String location = (String) this.request.getAttribute(ATTR_KEY); if (location != null) { super.sendRedirect(location); } } } }
Wrong variable name
bundle/src/main/java/com/adobe/acs/samples/authentication/impl/SampleLoginHookAuthenticationHandler.java
Wrong variable name
<ide><path>undle/src/main/java/com/adobe/acs/samples/authentication/impl/SampleLoginHookAuthenticationHandler.java <ide> new DeferredRedirectHttpServletResponse(httpServletRequest, httpServletResponse); <ide> <ide> if (this.wrappedIsAuthFeedbackHandler) { <del> ((AuthenticationFeedbackHandler) wrappedAuthHandler).authenticationFailed(httpServletRequest, wrappedResponse, authenticationInfo); <add> ((AuthenticationFeedbackHandler) wrappedAuthHandler).authenticationFailed(httpServletRequest, deferredRedirectResponse, authenticationInfo); <ide> } <ide> <ide> try {
Java
lgpl-2.1
f847495b5878c04824bff40d303a5e271a7819fc
0
sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs,sewe/spotbugs,johnscancella/spotbugs,sewe/spotbugs
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2003-2005 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.StringTokenizer; import org.apache.bcel.Constants; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.MethodGen; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.JavaClassAndMethod; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.ba.bcp.FieldVariable; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; /** * An instance of a bug pattern. * A BugInstance consists of several parts: * <p/> * <ul> * <li> the type, which is a string indicating what kind of bug it is; * used as a key for the FindBugsMessages resource bundle * <li> the priority; how likely this instance is to actually be a bug * <li> a list of <em>annotations</em> * </ul> * <p/> * The annotations describe classes, methods, fields, source locations, * and other relevant context information about the bug instance. * Every BugInstance must have at least one ClassAnnotation, which * describes the class in which the instance was found. This is the * "primary class annotation". * <p/> * <p> BugInstance objects are built up by calling a string of <code>add</code> * methods. (These methods all "return this", so they can be chained). * Some of the add methods are specialized to get information automatically from * a BetterVisitor or DismantleBytecode object. * * @author David Hovemeyer * @see BugAnnotation */ public class BugInstance implements Comparable, XMLWriteableWithMessages, Serializable, Cloneable { private static final long serialVersionUID = 1L; private String type; private int priority; private ArrayList<BugAnnotation> annotationList; private int cachedHashCode; @NonNull private String annotationText; private BugProperty propertyListHead, propertyListTail; private String uniqueId; /* * The following fields are used for tracking Bug instances across multiple versions of software. * They are meaningless in a BugCollection for just one version of software. */ private long firstVersion = 0; private long lastVersion = -1; private boolean introducedByChangeOfExistingClass; private boolean removedByChangeOfPersistingClass; /** * This value is used to indicate that the cached hashcode * is invalid, and should be recomputed. */ private static final int INVALID_HASH_CODE = 0; /** * This value is used to indicate whether BugInstances should be reprioritized very low, * when the BugPattern is marked as experimental */ private static boolean adjustExperimental = false; /** * Constructor. * * @param type the bug type * @param priority the bug priority */ public BugInstance(String type, int priority) { this.type = type; this.priority = priority < Detector.HIGH_PRIORITY ? Detector.HIGH_PRIORITY : priority; annotationList = new ArrayList<BugAnnotation>(4); cachedHashCode = INVALID_HASH_CODE; annotationText = ""; if (adjustExperimental && isExperimental()) this.priority = Detector.EXP_PRIORITY; } //@Override public Object clone() { BugInstance dup; try { dup = (BugInstance) super.clone(); // Do deep copying of mutable objects for (int i = 0; i < dup.annotationList.size(); ++i) { dup.annotationList.set(i, (BugAnnotation) dup.annotationList.get(i).clone()); } dup.propertyListHead = dup.propertyListTail = null; for (Iterator<BugProperty> i = propertyIterator(); i.hasNext(); ) { dup.addProperty((BugProperty) i.next().clone()); } return dup; } catch (CloneNotSupportedException e) { throw new IllegalStateException("impossible", e); } } /** * Create a new BugInstance. * This is the constructor that should be used by Detectors. * * @param detector the Detector that is reporting the BugInstance * @param type the bug type * @param priority the bug priority */ public BugInstance(Detector detector, String type, int priority) { this(type, priority); if (detector != null) { // Adjust priority if required DetectorFactory factory = DetectorFactoryCollection.instance().getFactoryByClassName(detector.getClass().getName()); if (factory != null) { this.priority += factory.getPriorityAdjustment(); if (this.priority < 0) this.priority = 0; } } if (adjustExperimental && isExperimental()) this.priority = Detector.EXP_PRIORITY; } public static void setAdjustExperimental(boolean adjust) { adjustExperimental = adjust; } /* ---------------------------------------------------------------------- * Accessors * ---------------------------------------------------------------------- */ /** * Get the bug type. */ public String getType() { return type; } /** * Get the BugPattern. */ public BugPattern getBugPattern() { return I18N.instance().lookupBugPattern(getType()); } /** * Get the bug priority. */ public int getPriority() { return priority; } /** * Set the bug priority. */ public void setPriority(int p) { priority = p < Detector.HIGH_PRIORITY ? Detector.HIGH_PRIORITY : p; } /** * Is this bug instance the result of an experimental detector? */ public boolean isExperimental() { BugPattern pattern = I18N.instance().lookupBugPattern(type); return (pattern != null) ? pattern.isExperimental() : false; } /** * Get the primary class annotation, which indicates where the bug occurs. */ public ClassAnnotation getPrimaryClass() { return (ClassAnnotation) findAnnotationOfType(ClassAnnotation.class); } /** * Get the primary method annotation, which indicates where the bug occurs. */ public MethodAnnotation getPrimaryMethod() { return (MethodAnnotation) findAnnotationOfType(MethodAnnotation.class); } /** * Get the primary method annotation, which indicates where the bug occurs. */ public FieldAnnotation getPrimaryField() { return (FieldAnnotation) findAnnotationOfType(FieldAnnotation.class); } /** * Find the first BugAnnotation in the list of annotations * that is the same type or a subtype as the given Class parameter. * * @param cls the Class parameter * @return the first matching BugAnnotation of the given type, * or null if there is no such BugAnnotation */ private BugAnnotation findAnnotationOfType(Class<? extends BugAnnotation> cls) { for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) { BugAnnotation annotation = i.next(); if (cls.isAssignableFrom(annotation.getClass())) return annotation; } return null; } /** * Get the primary source line annotation. * * @return the source line annotation, or null if there is * no source line annotation */ public SourceLineAnnotation getPrimarySourceLineAnnotation() { // Highest priority: return the first top level source line annotation Iterator<BugAnnotation> i = annotationList.iterator(); while (i.hasNext()) { BugAnnotation annotation = i.next(); if (annotation instanceof SourceLineAnnotation) return (SourceLineAnnotation) annotation; } // Second priority: return the source line annotation describing the // primary method MethodAnnotation primaryMethodAnnotation = getPrimaryMethod(); if (primaryMethodAnnotation != null) return primaryMethodAnnotation.getSourceLines(); else return null; } /** * Get an Iterator over all bug annotations. */ public Iterator<BugAnnotation> annotationIterator() { return annotationList.iterator(); } /** * Get the abbreviation of this bug instance's BugPattern. * This is the same abbreviation used by the BugCode which * the BugPattern is a particular species of. */ public String getAbbrev() { BugPattern pattern = I18N.instance().lookupBugPattern(getType()); return pattern != null ? pattern.getAbbrev() : "<unknown bug pattern>"; } /** * Set the user annotation text. * * @param annotationText the user annotation text */ public void setAnnotationText(@NonNull String annotationText) { this.annotationText = annotationText; } /** * Get the user annotation text. * * @return the user annotation text */ @NonNull public String getAnnotationText() { return annotationText; } /** * Determine whether or not the annotation text contains * the given word. * * @param word the word * @return true if the annotation text contains the word, false otherwise */ public boolean annotationTextContainsWord(String word) { return getTextAnnotationWords().contains(word); } /** * Get set of words in the text annotation. */ public Set<String> getTextAnnotationWords() { HashSet<String> result = new HashSet<String>(); StringTokenizer tok = new StringTokenizer(annotationText, " \t\r\n\f.,:;-"); while (tok.hasMoreTokens()) { result.add(tok.nextToken()); } return result; } /** * Get the BugInstance's unique id. * * @return the unique id, or null if no unique id has been assigned */ public String getUniqueId() { return uniqueId; } /** * Set the unique id of the BugInstance. * * @param uniqueId the unique id */ public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } /* ---------------------------------------------------------------------- * Property accessors * ---------------------------------------------------------------------- */ private class BugPropertyIterator implements Iterator<BugProperty> { private BugProperty prev, cur; private boolean removed; /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return findNext() != null; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public BugProperty next() { BugProperty next = findNext(); if (next == null) throw new NoSuchElementException(); prev = cur; cur = next; removed = false; return cur; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { if (cur == null || removed) throw new IllegalStateException(); if (prev == null) { propertyListHead = cur.getNext(); } else { prev.setNext(cur.getNext()); } if (cur == propertyListTail) { propertyListTail = prev; } removed = true; } private BugProperty findNext() { return cur == null ? propertyListHead : cur.getNext(); } }; /** * Get value of given property. * * @param name name of the property to get * @return the value of the named property, or null if * the property has not been set */ public String getProperty(String name) { BugProperty prop = lookupProperty(name); return prop != null ? prop.getValue() : null; } /** * Get value of given property, returning given default * value if the property has not been set. * * @param name name of the property to get * @param defaultValue default value to return if propery is not set * @return the value of the named property, or the default * value if the property has not been set */ public String getProperty(String name, String defaultValue) { String value = getProperty(name); return value != null ? value : defaultValue; } /** * Get an Iterator over the properties defined in this BugInstance. * * @return Iterator over properties */ public Iterator<BugProperty> propertyIterator() { return new BugPropertyIterator(); } /** * Set value of given property. * * @param name name of the property to set * @param value the value of the property * @return this object, so calls can be chained */ public BugInstance setProperty(String name, String value) { BugProperty prop = lookupProperty(name); if (prop != null) { prop.setValue(value); } else { prop = new BugProperty(name, value); addProperty(prop); } return this; } /** * Look up a property by name. * * @param name name of the property to look for * @return the BugProperty with the given name, * or null if the property has not been set */ public BugProperty lookupProperty(String name) { BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) break; prop = prop.getNext(); } return prop; } /** * Delete property with given name. * * @param name name of the property to delete * @return true if a property with that name was deleted, * or false if there is no such property */ public boolean deleteProperty(String name) { BugProperty prev = null; BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) break; prev = prop; prop = prop.getNext(); } if (prop != null) { if (prev != null) { // Deleted node in interior or at tail of list prev.setNext(prop.getNext()); } else { // Deleted node at head of list propertyListHead = prop.getNext(); } if (prop.getNext() == null) { // Deleted node at end of list propertyListTail = prev; } return true; } else { // No such property return false; } } private void addProperty(BugProperty prop) { if (propertyListTail != null) { propertyListTail.setNext(prop); propertyListTail = prop; } else { propertyListHead = propertyListTail = prop; } prop.setNext(null); } /* ---------------------------------------------------------------------- * Generic BugAnnotation adders * ---------------------------------------------------------------------- */ /** * Add a Collection of BugAnnotations. * * @param annotationCollection Collection of BugAnnotations */ public void addAnnotations(Collection<BugAnnotation> annotationCollection) { for (BugAnnotation annotation : annotationCollection) { add(annotation); } } /* ---------------------------------------------------------------------- * Combined annotation adders * ---------------------------------------------------------------------- */ /** * Add a class annotation and a method annotation for the class and method * which the given visitor is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addClassAndMethod(PreorderVisitor visitor) { addClass(visitor); addMethod(visitor); return this; } /** * Add class and method annotations for given method. * * @param methodAnnotation the method * @return this object */ public BugInstance addClassAndMethod(MethodAnnotation methodAnnotation) { addClass(methodAnnotation.getClassName()); addMethod(methodAnnotation); return this; } /** * Add class and method annotations for given method. * * @param methodGen the method * @param sourceFile source file the method is defined in * @return this object */ public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) { addClass(methodGen.getClassName()); addMethod(methodGen, sourceFile); return this; } /** * Add class and method annotations for given class and method. * * @param javaClass the class * @param method the method * @return this object */ public BugInstance addClassAndMethod(JavaClass javaClass, Method method) { addClass(javaClass.getClassName()); addMethod(javaClass, method); return this; } /* ---------------------------------------------------------------------- * Class annotation adders * ---------------------------------------------------------------------- */ /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param className the name of the class * @return this object */ public BugInstance addClass(String className) { ClassAnnotation classAnnotation = new ClassAnnotation(className); add(classAnnotation); return this; } /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param jclass the JavaClass object for the class * @return this object */ public BugInstance addClass(JavaClass jclass) { addClass(jclass.getClassName()); return this; } /** * Add a class annotation for the class that the visitor is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addClass(PreorderVisitor visitor) { String className = visitor.getDottedClassName(); addClass(className); return this; } /** * Add a class annotation for the superclass of the class the visitor * is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addSuperclass(PreorderVisitor visitor) { String className = visitor.getSuperclassName(); addClass(className); return this; } /* ---------------------------------------------------------------------- * Field annotation adders * ---------------------------------------------------------------------- */ /** * Add a field annotation. * * @param className name of the class containing the field * @param fieldName the name of the field * @param fieldSig type signature of the field * @param isStatic whether or not the field is static * @return this object */ public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) { addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic)); return this; } /** * Add a field annotation * * @param fieldAnnotation the field annotation * @return this object */ public BugInstance addField(FieldAnnotation fieldAnnotation) { add(fieldAnnotation); return this; } /** * Add a field annotation for a FieldVariable matched in a ByteCodePattern. * * @param field the FieldVariable * @return this object */ public BugInstance addField(FieldVariable field) { return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic()); } /** * Add a field annotation for an XField. * * @param xfield the XField * @return this object */ public BugInstance addField(XField xfield) { return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic()); } /** * Add a field annotation for the field which has just been accessed * by the method currently being visited by given visitor. * Assumes that a getfield/putfield or getstatic/putstatic * has just been seen. * * @param visitor the DismantleBytecode object * @return this object */ public BugInstance addReferencedField(DismantleBytecode visitor) { FieldAnnotation f = FieldAnnotation.fromReferencedField(visitor); addField(f); return this; } /** * Add a field annotation for the field referenced by the FieldAnnotation parameter */ public BugInstance addReferencedField(FieldAnnotation fa) { addField(fa); return this; } /** * Add a field annotation for the field which is being visited by * given visitor. * * @param visitor the visitor * @return this object */ public BugInstance addVisitedField(PreorderVisitor visitor) { FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor); addField(f); return this; } /* ---------------------------------------------------------------------- * Method annotation adders * ---------------------------------------------------------------------- */ /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * * @param className name of the class containing the method * @param methodName name of the method * @param methodSig type signature of the method * @param isStatic true if the method is static, false otherwise * @return this object */ public BugInstance addMethod(String className, String methodName, String methodSig, boolean isStatic) { addMethod(new MethodAnnotation(className, methodName, methodSig, isStatic)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param methodGen the MethodGen object for the method * @param sourceFile source file method is defined in * @return this object */ public BugInstance addMethod(MethodGen methodGen, String sourceFile) { MethodAnnotation methodAnnotation = new MethodAnnotation(methodGen.getClassName(), methodGen.getName(), methodGen.getSignature(), methodGen.isStatic()); addMethod(methodAnnotation); addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(methodGen, sourceFile)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param javaClass the class the method is defined in * @param method the method * @return this object */ public BugInstance addMethod(JavaClass javaClass, Method method) { MethodAnnotation methodAnnotation = new MethodAnnotation(javaClass.getClassName(), method.getName(), method.getSignature(), method.isStatic()); SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod( javaClass, method); methodAnnotation.setSourceLines(methodSourceLines); addMethod(methodAnnotation); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param classAndMethod JavaClassAndMethod identifying the method to add * @return this object */ public BugInstance addMethod(JavaClassAndMethod classAndMethod) { return addMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod()); } /** * Add a method annotation for the method which the given visitor is currently visiting. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addMethod(PreorderVisitor visitor) { MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor); addMethod(methodAnnotation); addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor)); return this; } /** * Add a method annotation for the method which has been called * by the method currently being visited by given visitor. * Assumes that the visitor has just looked at an invoke instruction * of some kind. * * @param visitor the DismantleBytecode object * @return this object */ public BugInstance addCalledMethod(DismantleBytecode visitor) { String className = visitor.getDottedClassConstantOperand(); String methodName = visitor.getNameConstantOperand(); String methodSig = visitor.getDottedSigConstantOperand(); addMethod(className, methodName, methodSig, visitor.getMethod().isStatic()); describe("METHOD_CALLED"); return this; } /** * Add a method annotation. * * @param className name of class containing called method * @param methodName name of called method * @param methodSig signature of called method * @param isStatic true if called method is static, false if not * @return this object */ public BugInstance addCalledMethod(String className, String methodName, String methodSig, boolean isStatic) { addMethod(className, methodName, methodSig, isStatic); describe("METHOD_CALLED"); return this; } /** * Add a method annotation for the method which is called by given * instruction. * * @param methodGen the method containing the call * @param inv the InvokeInstruction * @return this object */ public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) { ConstantPoolGen cpg = methodGen.getConstantPool(); String className = inv.getClassName(cpg); String methodName = inv.getMethodName(cpg); String methodSig = inv.getSignature(cpg); addMethod(className, methodName, methodSig, inv.getOpcode() == Constants.INVOKESTATIC); describe("METHOD_CALLED"); return this; } /** * Add a MethodAnnotation from an XMethod. * * @param xmethod the XMethod * @return this object */ public BugInstance addMethod(XMethod xmethod) { addMethod(MethodAnnotation.fromXMethod(xmethod)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * * @param methodAnnotation the method annotation * @return this object */ public BugInstance addMethod(MethodAnnotation methodAnnotation) { add(methodAnnotation); return this; } /* ---------------------------------------------------------------------- * Integer annotation adders * ---------------------------------------------------------------------- */ /** * Add an integer annotation. * * @param value the integer value * @return this object */ public BugInstance addInt(int value) { add(new IntAnnotation(value)); return this; } /* ---------------------------------------------------------------------- * Source line annotation adders * ---------------------------------------------------------------------- */ /** * Add a source line annotation. * * @param sourceLine the source line annotation * @return this object */ public BugInstance addSourceLine(SourceLineAnnotation sourceLine) { add(sourceLine); return this; } /** * Add a source line annotation for instruction whose PC is given * in the method that the given visitor is currently visiting. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BytecodeScanningDetector that is currently visiting the method * @param pc bytecode offset of the instruction * @return this object */ public BugInstance addSourceLine(BytecodeScanningDetector visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor.getClassContext(), visitor, pc); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for instruction whose PC is given * in the method that the given visitor is currently visiting. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a PreorderVisitor that is currently visiting the method * @param pc bytecode offset of the instruction * @return this object */ public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for the given instruction in the given method. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param methodGen the method being visited * @param sourceFile source file the method is defined in * @param handle the InstructionHandle containing the visited instruction * @return this object */ public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, @NonNull InstructionHandle handle) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing a range of instructions. * * @param classContext the ClassContext * @param methodGen the method * @param sourceFile source file the method is defined in * @param start the start instruction in the range * @param end the end instruction in the range (inclusive) * @return this object */ public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) { // Make sure start and end are really in the right order. if (start.getPosition() > end.getPosition()) { InstructionHandle tmp = start; start = end; end = tmp; } SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen, sourceFile, start, end); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return this object */ public BugInstance addSourceLineRange(BytecodeScanningDetector visitor, int startPC, int endPC) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(visitor.getClassContext(), visitor, startPC, endPC); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return this object */ public BugInstance addSourceLineRange(ClassContext classContext, PreorderVisitor visitor, int startPC, int endPC) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, visitor, startPC, endPC); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for instruction currently being visited * by given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a BytecodeScanningDetector visitor that is currently visiting the instruction * @return this object */ public BugInstance addSourceLine(BytecodeScanningDetector visitor) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a non-specific source line annotation. * This will result in the entire source file being displayed. * * @param className the class name * @param sourceFile the source file name * @return this object */ public BugInstance addUnknownSourceLine(String className, String sourceFile) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /* ---------------------------------------------------------------------- * Formatting support * ---------------------------------------------------------------------- */ /** * Format a string describing this bug instance. * * @return the description */ public String getMessage() { String pattern = I18N.instance().getMessage(type); FindBugsMessageFormat format = new FindBugsMessageFormat(pattern); return format.format((BugAnnotation[]) annotationList.toArray(new BugAnnotation[annotationList.size()])); } /** * Add a description to the most recently added bug annotation. * * @param description the description to add * @return this object */ public BugInstance describe(String description) { annotationList.get(annotationList.size() - 1).setDescription(description); return this; } /** * Convert to String. * This method returns the "short" message describing the bug, * as opposed to the longer format returned by getMessage(). * The short format is appropriate for the tree view in a GUI, * where the annotations are listed separately as part of the overall * bug instance. */ public String toString() { return I18N.instance().getShortMessage(type); } /* ---------------------------------------------------------------------- * XML Conversion support * ---------------------------------------------------------------------- */ public void writeXML(XMLOutput xmlOutput) throws IOException { writeXML(xmlOutput, false); } public void writeXML(XMLOutput xmlOutput, boolean addMessages) throws IOException { XMLAttributeList attributeList = new XMLAttributeList() .addAttribute("type", type) .addAttribute("priority", String.valueOf(priority)); BugPattern pattern = getBugPattern(); if (pattern != null) { // The bug abbreviation and pattern category are // emitted into the XML for informational purposes only. // (The information is redundant, but might be useful // for processing tools that want to make sense of // bug instances without looking at the plugin descriptor.) attributeList.addAttribute("abbrev", pattern.getAbbrev()); attributeList.addAttribute("category", pattern.getCategory()); } // Add a uid attribute, if we have a unique id. if (getUniqueId() != null) { attributeList.addAttribute("uid", getUniqueId()); } if (firstVersion > 0) attributeList.addAttribute("first", Long.toString(firstVersion)); if (lastVersion >= 0) attributeList.addAttribute("last", Long.toString(lastVersion)); if (introducedByChangeOfExistingClass) attributeList.addAttribute("introducedByChange", "true"); if (removedByChangeOfPersistingClass) attributeList.addAttribute("removedByChange", "true"); xmlOutput.openTag(ELEMENT_NAME, attributeList); if (!annotationText.equals("")) { xmlOutput.openTag("UserAnnotation"); xmlOutput.writeCDATA(annotationText); xmlOutput.closeTag("UserAnnotation"); } if (addMessages) { BugPattern bugPattern = getBugPattern(); xmlOutput.openTag("ShortMessage"); xmlOutput.writeText(bugPattern != null ? bugPattern.getShortDescription() : this.toString()); xmlOutput.closeTag("ShortMessage"); xmlOutput.openTag("LongMessage"); xmlOutput.writeText(this.getMessage()); xmlOutput.closeTag("LongMessage"); } for (Iterator<BugAnnotation> i = annotationList.iterator(); i.hasNext();) { BugAnnotation annotation = i.next(); annotation.writeXML(xmlOutput, addMessages); } if (propertyListHead != null) { BugProperty prop = propertyListHead; while (prop != null) { prop.writeXML(xmlOutput); prop = prop.getNext(); } } xmlOutput.closeTag(ELEMENT_NAME); } private static final String ELEMENT_NAME = "BugInstance"; private static final String USER_ANNOTATION_ELEMENT_NAME = "UserAnnotation"; /* ---------------------------------------------------------------------- * Implementation * ---------------------------------------------------------------------- */ void add(BugAnnotation annotation) { if (annotation == null) throw new IllegalStateException("Missing BugAnnotation!"); // Add to list annotationList.add(annotation); // This object is being modified, so the cached hashcode // must be invalidated cachedHashCode = INVALID_HASH_CODE; } private void addSourceLinesForMethod(MethodAnnotation methodAnnotation, SourceLineAnnotation sourceLineAnnotation) { if (sourceLineAnnotation != null) { // Note: we don't add the source line annotation directly to // the bug instance. Instead, we stash it in the MethodAnnotation. // It is much more useful there, and it would just be distracting // if it were displayed in the UI, since it would compete for attention // with the actual bug location source line annotation (which is much // more important and interesting). methodAnnotation.setSourceLines(sourceLineAnnotation); } } public int hashCode() { if (cachedHashCode == INVALID_HASH_CODE) { int hashcode = type.hashCode() + priority; Iterator<BugAnnotation> i = annotationIterator(); while (i.hasNext()) hashcode += i.next().hashCode(); if (hashcode == INVALID_HASH_CODE) hashcode = INVALID_HASH_CODE+1; cachedHashCode = hashcode; } return cachedHashCode; } public boolean equals(Object o) { if (!(o instanceof BugInstance)) return false; BugInstance other = (BugInstance) o; if (!type.equals(other.type) || priority != other.priority) return false; if (annotationList.size() != other.annotationList.size()) return false; int numAnnotations = annotationList.size(); for (int i = 0; i < numAnnotations; ++i) { BugAnnotation lhs = annotationList.get(i); BugAnnotation rhs = other.annotationList.get(i); if (!lhs.equals(rhs)) return false; } return true; } public int compareTo(Object o) { BugInstance other = (BugInstance) o; int cmp; cmp = type.compareTo(other.type); if (cmp != 0) return cmp; cmp = priority - other.priority; if (cmp != 0) return cmp; // Compare BugAnnotations lexicographically int pfxLen = Math.min(annotationList.size(), other.annotationList.size()); for (int i = 0; i < pfxLen; ++i) { BugAnnotation lhs = annotationList.get(i); BugAnnotation rhs = other.annotationList.get(i); cmp = lhs.compareTo(rhs); if (cmp != 0) return cmp; } // All elements in prefix were the same, // so use number of elements to decide return annotationList.size() - other.annotationList.size(); } /** * @param firstVersion The firstVersion to set. */ public void setFirstVersion(long firstVersion) { this.firstVersion = firstVersion; if (lastVersion >= 0 && firstVersion > lastVersion) throw new IllegalArgumentException( firstVersion + ".." + lastVersion); } /** * @return Returns the firstVersion. */ public long getFirstVersion() { return firstVersion; } /** * @param lastVersion The lastVersion to set. */ public void setLastVersion(long lastVersion) { if (lastVersion >= 0 && firstVersion > lastVersion) throw new IllegalArgumentException( firstVersion + ".." + lastVersion); this.lastVersion = lastVersion; } /** * @return Returns the lastVersion. */ public long getLastVersion() { return lastVersion; } /** * @param introducedByChangeOfExistingClass The introducedByChangeOfExistingClass to set. */ public void setIntroducedByChangeOfExistingClass(boolean introducedByChangeOfExistingClass) { this.introducedByChangeOfExistingClass = introducedByChangeOfExistingClass; } /** * @return Returns the introducedByChangeOfExistingClass. */ public boolean isIntroducedByChangeOfExistingClass() { return introducedByChangeOfExistingClass; } /** * @param removedByChangeOfPersistingClass The removedByChangeOfPersistingClass to set. */ public void setRemovedByChangeOfPersistingClass(boolean removedByChangeOfPersistingClass) { this.removedByChangeOfPersistingClass = removedByChangeOfPersistingClass; } /** * @return Returns the removedByChangeOfPersistingClass. */ public boolean isRemovedByChangeOfPersistingClass() { return removedByChangeOfPersistingClass; } } // vim:ts=4
findbugs/src/java/edu/umd/cs/findbugs/BugInstance.java
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2003-2005 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.StringTokenizer; import org.apache.bcel.Constants; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.MethodGen; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.JavaClassAndMethod; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.ba.bcp.FieldVariable; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; /** * An instance of a bug pattern. * A BugInstance consists of several parts: * <p/> * <ul> * <li> the type, which is a string indicating what kind of bug it is; * used as a key for the FindBugsMessages resource bundle * <li> the priority; how likely this instance is to actually be a bug * <li> a list of <em>annotations</em> * </ul> * <p/> * The annotations describe classes, methods, fields, source locations, * and other relevant context information about the bug instance. * Every BugInstance must have at least one ClassAnnotation, which * describes the class in which the instance was found. This is the * "primary class annotation". * <p/> * <p> BugInstance objects are built up by calling a string of <code>add</code> * methods. (These methods all "return this", so they can be chained). * Some of the add methods are specialized to get information automatically from * a BetterVisitor or DismantleBytecode object. * * @author David Hovemeyer * @see BugAnnotation */ public class BugInstance implements Comparable, XMLWriteableWithMessages, Serializable, Cloneable { private static final long serialVersionUID = 1L; private String type; private int priority; private ArrayList<BugAnnotation> annotationList; private int cachedHashCode; private String annotationText; private BugProperty propertyListHead, propertyListTail; private String uniqueId; /* * The following fields are used for tracking Bug instances across multiple versions of software. * They are meaningless in a BugCollection for just one version of software. */ private long firstVersion = 0; private long lastVersion = -1; private boolean introducedByChangeOfExistingClass; private boolean removedByChangeOfPersistingClass; /** * This value is used to indicate that the cached hashcode * is invalid, and should be recomputed. */ private static final int INVALID_HASH_CODE = 0; /** * This value is used to indicate whether BugInstances should be reprioritized very low, * when the BugPattern is marked as experimental */ private static boolean adjustExperimental = false; /** * Constructor. * * @param type the bug type * @param priority the bug priority */ public BugInstance(String type, int priority) { this.type = type; this.priority = priority < Detector.HIGH_PRIORITY ? Detector.HIGH_PRIORITY : priority; annotationList = new ArrayList<BugAnnotation>(4); cachedHashCode = INVALID_HASH_CODE; annotationText = ""; if (adjustExperimental && isExperimental()) this.priority = Detector.EXP_PRIORITY; } //@Override public Object clone() { BugInstance dup; try { dup = (BugInstance) super.clone(); // Do deep copying of mutable objects for (int i = 0; i < dup.annotationList.size(); ++i) { dup.annotationList.set(i, (BugAnnotation) dup.annotationList.get(i).clone()); } dup.propertyListHead = dup.propertyListTail = null; for (Iterator<BugProperty> i = propertyIterator(); i.hasNext(); ) { dup.addProperty((BugProperty) i.next().clone()); } return dup; } catch (CloneNotSupportedException e) { throw new IllegalStateException("impossible", e); } } /** * Create a new BugInstance. * This is the constructor that should be used by Detectors. * * @param detector the Detector that is reporting the BugInstance * @param type the bug type * @param priority the bug priority */ public BugInstance(Detector detector, String type, int priority) { this(type, priority); if (detector != null) { // Adjust priority if required DetectorFactory factory = DetectorFactoryCollection.instance().getFactoryByClassName(detector.getClass().getName()); if (factory != null) { this.priority += factory.getPriorityAdjustment(); if (this.priority < 0) this.priority = 0; } } if (adjustExperimental && isExperimental()) this.priority = Detector.EXP_PRIORITY; } public static void setAdjustExperimental(boolean adjust) { adjustExperimental = adjust; } /* ---------------------------------------------------------------------- * Accessors * ---------------------------------------------------------------------- */ /** * Get the bug type. */ public String getType() { return type; } /** * Get the BugPattern. */ public BugPattern getBugPattern() { return I18N.instance().lookupBugPattern(getType()); } /** * Get the bug priority. */ public int getPriority() { return priority; } /** * Set the bug priority. */ public void setPriority(int p) { priority = p < Detector.HIGH_PRIORITY ? Detector.HIGH_PRIORITY : p; } /** * Is this bug instance the result of an experimental detector? */ public boolean isExperimental() { BugPattern pattern = I18N.instance().lookupBugPattern(type); return (pattern != null) ? pattern.isExperimental() : false; } /** * Get the primary class annotation, which indicates where the bug occurs. */ public ClassAnnotation getPrimaryClass() { return (ClassAnnotation) findAnnotationOfType(ClassAnnotation.class); } /** * Get the primary method annotation, which indicates where the bug occurs. */ public MethodAnnotation getPrimaryMethod() { return (MethodAnnotation) findAnnotationOfType(MethodAnnotation.class); } /** * Get the primary method annotation, which indicates where the bug occurs. */ public FieldAnnotation getPrimaryField() { return (FieldAnnotation) findAnnotationOfType(FieldAnnotation.class); } /** * Find the first BugAnnotation in the list of annotations * that is the same type or a subtype as the given Class parameter. * * @param cls the Class parameter * @return the first matching BugAnnotation of the given type, * or null if there is no such BugAnnotation */ private BugAnnotation findAnnotationOfType(Class<? extends BugAnnotation> cls) { for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) { BugAnnotation annotation = i.next(); if (cls.isAssignableFrom(annotation.getClass())) return annotation; } return null; } /** * Get the primary source line annotation. * * @return the source line annotation, or null if there is * no source line annotation */ public SourceLineAnnotation getPrimarySourceLineAnnotation() { // Highest priority: return the first top level source line annotation Iterator<BugAnnotation> i = annotationList.iterator(); while (i.hasNext()) { BugAnnotation annotation = i.next(); if (annotation instanceof SourceLineAnnotation) return (SourceLineAnnotation) annotation; } // Second priority: return the source line annotation describing the // primary method MethodAnnotation primaryMethodAnnotation = getPrimaryMethod(); if (primaryMethodAnnotation != null) return primaryMethodAnnotation.getSourceLines(); else return null; } /** * Get an Iterator over all bug annotations. */ public Iterator<BugAnnotation> annotationIterator() { return annotationList.iterator(); } /** * Get the abbreviation of this bug instance's BugPattern. * This is the same abbreviation used by the BugCode which * the BugPattern is a particular species of. */ public String getAbbrev() { BugPattern pattern = I18N.instance().lookupBugPattern(getType()); return pattern != null ? pattern.getAbbrev() : "<unknown bug pattern>"; } /** * Set the user annotation text. * * @param annotationText the user annotation text */ public void setAnnotationText(String annotationText) { this.annotationText = annotationText; } /** * Get the user annotation text. * * @return the user annotation text */ public String getAnnotationText() { return annotationText; } /** * Determine whether or not the annotation text contains * the given word. * * @param word the word * @return true if the annotation text contains the word, false otherwise */ public boolean annotationTextContainsWord(String word) { return getTextAnnotationWords().contains(word); } /** * Get set of words in the text annotation. */ public Set<String> getTextAnnotationWords() { HashSet<String> result = new HashSet<String>(); StringTokenizer tok = new StringTokenizer(annotationText, " \t\r\n\f.,:;-"); while (tok.hasMoreTokens()) { result.add(tok.nextToken()); } return result; } /** * Get the BugInstance's unique id. * * @return the unique id, or null if no unique id has been assigned */ public String getUniqueId() { return uniqueId; } /** * Set the unique id of the BugInstance. * * @param uniqueId the unique id */ public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } /* ---------------------------------------------------------------------- * Property accessors * ---------------------------------------------------------------------- */ private class BugPropertyIterator implements Iterator<BugProperty> { private BugProperty prev, cur; private boolean removed; /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return findNext() != null; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public BugProperty next() { BugProperty next = findNext(); if (next == null) throw new NoSuchElementException(); prev = cur; cur = next; removed = false; return cur; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { if (cur == null || removed) throw new IllegalStateException(); if (prev == null) { propertyListHead = cur.getNext(); } else { prev.setNext(cur.getNext()); } if (cur == propertyListTail) { propertyListTail = prev; } removed = true; } private BugProperty findNext() { return cur == null ? propertyListHead : cur.getNext(); } }; /** * Get value of given property. * * @param name name of the property to get * @return the value of the named property, or null if * the property has not been set */ public String getProperty(String name) { BugProperty prop = lookupProperty(name); return prop != null ? prop.getValue() : null; } /** * Get value of given property, returning given default * value if the property has not been set. * * @param name name of the property to get * @param defaultValue default value to return if propery is not set * @return the value of the named property, or the default * value if the property has not been set */ public String getProperty(String name, String defaultValue) { String value = getProperty(name); return value != null ? value : defaultValue; } /** * Get an Iterator over the properties defined in this BugInstance. * * @return Iterator over properties */ public Iterator<BugProperty> propertyIterator() { return new BugPropertyIterator(); } /** * Set value of given property. * * @param name name of the property to set * @param value the value of the property * @return this object, so calls can be chained */ public BugInstance setProperty(String name, String value) { BugProperty prop = lookupProperty(name); if (prop != null) { prop.setValue(value); } else { prop = new BugProperty(name, value); addProperty(prop); } return this; } /** * Look up a property by name. * * @param name name of the property to look for * @return the BugProperty with the given name, * or null if the property has not been set */ public BugProperty lookupProperty(String name) { BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) break; prop = prop.getNext(); } return prop; } /** * Delete property with given name. * * @param name name of the property to delete * @return true if a property with that name was deleted, * or false if there is no such property */ public boolean deleteProperty(String name) { BugProperty prev = null; BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) break; prev = prop; prop = prop.getNext(); } if (prop != null) { if (prev != null) { // Deleted node in interior or at tail of list prev.setNext(prop.getNext()); } else { // Deleted node at head of list propertyListHead = prop.getNext(); } if (prop.getNext() == null) { // Deleted node at end of list propertyListTail = prev; } return true; } else { // No such property return false; } } private void addProperty(BugProperty prop) { if (propertyListTail != null) { propertyListTail.setNext(prop); propertyListTail = prop; } else { propertyListHead = propertyListTail = prop; } prop.setNext(null); } /* ---------------------------------------------------------------------- * Generic BugAnnotation adders * ---------------------------------------------------------------------- */ /** * Add a Collection of BugAnnotations. * * @param annotationCollection Collection of BugAnnotations */ public void addAnnotations(Collection<BugAnnotation> annotationCollection) { for (BugAnnotation annotation : annotationCollection) { add(annotation); } } /* ---------------------------------------------------------------------- * Combined annotation adders * ---------------------------------------------------------------------- */ /** * Add a class annotation and a method annotation for the class and method * which the given visitor is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addClassAndMethod(PreorderVisitor visitor) { addClass(visitor); addMethod(visitor); return this; } /** * Add class and method annotations for given method. * * @param methodAnnotation the method * @return this object */ public BugInstance addClassAndMethod(MethodAnnotation methodAnnotation) { addClass(methodAnnotation.getClassName()); addMethod(methodAnnotation); return this; } /** * Add class and method annotations for given method. * * @param methodGen the method * @param sourceFile source file the method is defined in * @return this object */ public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) { addClass(methodGen.getClassName()); addMethod(methodGen, sourceFile); return this; } /** * Add class and method annotations for given class and method. * * @param javaClass the class * @param method the method * @return this object */ public BugInstance addClassAndMethod(JavaClass javaClass, Method method) { addClass(javaClass.getClassName()); addMethod(javaClass, method); return this; } /* ---------------------------------------------------------------------- * Class annotation adders * ---------------------------------------------------------------------- */ /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param className the name of the class * @return this object */ public BugInstance addClass(String className) { ClassAnnotation classAnnotation = new ClassAnnotation(className); add(classAnnotation); return this; } /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param jclass the JavaClass object for the class * @return this object */ public BugInstance addClass(JavaClass jclass) { addClass(jclass.getClassName()); return this; } /** * Add a class annotation for the class that the visitor is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addClass(PreorderVisitor visitor) { String className = visitor.getDottedClassName(); addClass(className); return this; } /** * Add a class annotation for the superclass of the class the visitor * is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addSuperclass(PreorderVisitor visitor) { String className = visitor.getSuperclassName(); addClass(className); return this; } /* ---------------------------------------------------------------------- * Field annotation adders * ---------------------------------------------------------------------- */ /** * Add a field annotation. * * @param className name of the class containing the field * @param fieldName the name of the field * @param fieldSig type signature of the field * @param isStatic whether or not the field is static * @return this object */ public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) { addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic)); return this; } /** * Add a field annotation * * @param fieldAnnotation the field annotation * @return this object */ public BugInstance addField(FieldAnnotation fieldAnnotation) { add(fieldAnnotation); return this; } /** * Add a field annotation for a FieldVariable matched in a ByteCodePattern. * * @param field the FieldVariable * @return this object */ public BugInstance addField(FieldVariable field) { return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic()); } /** * Add a field annotation for an XField. * * @param xfield the XField * @return this object */ public BugInstance addField(XField xfield) { return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic()); } /** * Add a field annotation for the field which has just been accessed * by the method currently being visited by given visitor. * Assumes that a getfield/putfield or getstatic/putstatic * has just been seen. * * @param visitor the DismantleBytecode object * @return this object */ public BugInstance addReferencedField(DismantleBytecode visitor) { FieldAnnotation f = FieldAnnotation.fromReferencedField(visitor); addField(f); return this; } /** * Add a field annotation for the field referenced by the FieldAnnotation parameter */ public BugInstance addReferencedField(FieldAnnotation fa) { addField(fa); return this; } /** * Add a field annotation for the field which is being visited by * given visitor. * * @param visitor the visitor * @return this object */ public BugInstance addVisitedField(PreorderVisitor visitor) { FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor); addField(f); return this; } /* ---------------------------------------------------------------------- * Method annotation adders * ---------------------------------------------------------------------- */ /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * * @param className name of the class containing the method * @param methodName name of the method * @param methodSig type signature of the method * @param isStatic true if the method is static, false otherwise * @return this object */ public BugInstance addMethod(String className, String methodName, String methodSig, boolean isStatic) { addMethod(new MethodAnnotation(className, methodName, methodSig, isStatic)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param methodGen the MethodGen object for the method * @param sourceFile source file method is defined in * @return this object */ public BugInstance addMethod(MethodGen methodGen, String sourceFile) { MethodAnnotation methodAnnotation = new MethodAnnotation(methodGen.getClassName(), methodGen.getName(), methodGen.getSignature(), methodGen.isStatic()); addMethod(methodAnnotation); addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(methodGen, sourceFile)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param javaClass the class the method is defined in * @param method the method * @return this object */ public BugInstance addMethod(JavaClass javaClass, Method method) { MethodAnnotation methodAnnotation = new MethodAnnotation(javaClass.getClassName(), method.getName(), method.getSignature(), method.isStatic()); SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod( javaClass, method); methodAnnotation.setSourceLines(methodSourceLines); addMethod(methodAnnotation); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param classAndMethod JavaClassAndMethod identifying the method to add * @return this object */ public BugInstance addMethod(JavaClassAndMethod classAndMethod) { return addMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod()); } /** * Add a method annotation for the method which the given visitor is currently visiting. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addMethod(PreorderVisitor visitor) { MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor); addMethod(methodAnnotation); addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor)); return this; } /** * Add a method annotation for the method which has been called * by the method currently being visited by given visitor. * Assumes that the visitor has just looked at an invoke instruction * of some kind. * * @param visitor the DismantleBytecode object * @return this object */ public BugInstance addCalledMethod(DismantleBytecode visitor) { String className = visitor.getDottedClassConstantOperand(); String methodName = visitor.getNameConstantOperand(); String methodSig = visitor.getDottedSigConstantOperand(); addMethod(className, methodName, methodSig, visitor.getMethod().isStatic()); describe("METHOD_CALLED"); return this; } /** * Add a method annotation. * * @param className name of class containing called method * @param methodName name of called method * @param methodSig signature of called method * @param isStatic true if called method is static, false if not * @return this object */ public BugInstance addCalledMethod(String className, String methodName, String methodSig, boolean isStatic) { addMethod(className, methodName, methodSig, isStatic); describe("METHOD_CALLED"); return this; } /** * Add a method annotation for the method which is called by given * instruction. * * @param methodGen the method containing the call * @param inv the InvokeInstruction * @return this object */ public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) { ConstantPoolGen cpg = methodGen.getConstantPool(); String className = inv.getClassName(cpg); String methodName = inv.getMethodName(cpg); String methodSig = inv.getSignature(cpg); addMethod(className, methodName, methodSig, inv.getOpcode() == Constants.INVOKESTATIC); describe("METHOD_CALLED"); return this; } /** * Add a MethodAnnotation from an XMethod. * * @param xmethod the XMethod * @return this object */ public BugInstance addMethod(XMethod xmethod) { addMethod(MethodAnnotation.fromXMethod(xmethod)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * * @param methodAnnotation the method annotation * @return this object */ public BugInstance addMethod(MethodAnnotation methodAnnotation) { add(methodAnnotation); return this; } /* ---------------------------------------------------------------------- * Integer annotation adders * ---------------------------------------------------------------------- */ /** * Add an integer annotation. * * @param value the integer value * @return this object */ public BugInstance addInt(int value) { add(new IntAnnotation(value)); return this; } /* ---------------------------------------------------------------------- * Source line annotation adders * ---------------------------------------------------------------------- */ /** * Add a source line annotation. * * @param sourceLine the source line annotation * @return this object */ public BugInstance addSourceLine(SourceLineAnnotation sourceLine) { add(sourceLine); return this; } /** * Add a source line annotation for instruction whose PC is given * in the method that the given visitor is currently visiting. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BytecodeScanningDetector that is currently visiting the method * @param pc bytecode offset of the instruction * @return this object */ public BugInstance addSourceLine(BytecodeScanningDetector visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor.getClassContext(), visitor, pc); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for instruction whose PC is given * in the method that the given visitor is currently visiting. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a PreorderVisitor that is currently visiting the method * @param pc bytecode offset of the instruction * @return this object */ public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for the given instruction in the given method. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param methodGen the method being visited * @param sourceFile source file the method is defined in * @param handle the InstructionHandle containing the visited instruction * @return this object */ public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, @NonNull InstructionHandle handle) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing a range of instructions. * * @param classContext the ClassContext * @param methodGen the method * @param sourceFile source file the method is defined in * @param start the start instruction in the range * @param end the end instruction in the range (inclusive) * @return this object */ public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) { // Make sure start and end are really in the right order. if (start.getPosition() > end.getPosition()) { InstructionHandle tmp = start; start = end; end = tmp; } SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen, sourceFile, start, end); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return this object */ public BugInstance addSourceLineRange(BytecodeScanningDetector visitor, int startPC, int endPC) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(visitor.getClassContext(), visitor, startPC, endPC); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return this object */ public BugInstance addSourceLineRange(ClassContext classContext, PreorderVisitor visitor, int startPC, int endPC) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, visitor, startPC, endPC); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for instruction currently being visited * by given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a BytecodeScanningDetector visitor that is currently visiting the instruction * @return this object */ public BugInstance addSourceLine(BytecodeScanningDetector visitor) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a non-specific source line annotation. * This will result in the entire source file being displayed. * * @param className the class name * @param sourceFile the source file name * @return this object */ public BugInstance addUnknownSourceLine(String className, String sourceFile) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /* ---------------------------------------------------------------------- * Formatting support * ---------------------------------------------------------------------- */ /** * Format a string describing this bug instance. * * @return the description */ public String getMessage() { String pattern = I18N.instance().getMessage(type); FindBugsMessageFormat format = new FindBugsMessageFormat(pattern); return format.format((BugAnnotation[]) annotationList.toArray(new BugAnnotation[annotationList.size()])); } /** * Add a description to the most recently added bug annotation. * * @param description the description to add * @return this object */ public BugInstance describe(String description) { annotationList.get(annotationList.size() - 1).setDescription(description); return this; } /** * Convert to String. * This method returns the "short" message describing the bug, * as opposed to the longer format returned by getMessage(). * The short format is appropriate for the tree view in a GUI, * where the annotations are listed separately as part of the overall * bug instance. */ public String toString() { return I18N.instance().getShortMessage(type); } /* ---------------------------------------------------------------------- * XML Conversion support * ---------------------------------------------------------------------- */ public void writeXML(XMLOutput xmlOutput) throws IOException { writeXML(xmlOutput, false); } public void writeXML(XMLOutput xmlOutput, boolean addMessages) throws IOException { XMLAttributeList attributeList = new XMLAttributeList() .addAttribute("type", type) .addAttribute("priority", String.valueOf(priority)); BugPattern pattern = getBugPattern(); if (pattern != null) { // The bug abbreviation and pattern category are // emitted into the XML for informational purposes only. // (The information is redundant, but might be useful // for processing tools that want to make sense of // bug instances without looking at the plugin descriptor.) attributeList.addAttribute("abbrev", pattern.getAbbrev()); attributeList.addAttribute("category", pattern.getCategory()); } // Add a uid attribute, if we have a unique id. if (getUniqueId() != null) { attributeList.addAttribute("uid", getUniqueId()); } if (firstVersion > 0) attributeList.addAttribute("first", Long.toString(firstVersion)); if (lastVersion >= 0) attributeList.addAttribute("last", Long.toString(lastVersion)); if (introducedByChangeOfExistingClass) attributeList.addAttribute("introducedByChange", "true"); if (removedByChangeOfPersistingClass) attributeList.addAttribute("removedByChange", "true"); xmlOutput.openTag(ELEMENT_NAME, attributeList); if (!annotationText.equals("")) { xmlOutput.openTag("UserAnnotation"); xmlOutput.writeCDATA(annotationText); xmlOutput.closeTag("UserAnnotation"); } if (addMessages) { BugPattern bugPattern = getBugPattern(); xmlOutput.openTag("ShortMessage"); xmlOutput.writeText(bugPattern != null ? bugPattern.getShortDescription() : this.toString()); xmlOutput.closeTag("ShortMessage"); xmlOutput.openTag("LongMessage"); xmlOutput.writeText(this.getMessage()); xmlOutput.closeTag("LongMessage"); } for (Iterator<BugAnnotation> i = annotationList.iterator(); i.hasNext();) { BugAnnotation annotation = i.next(); annotation.writeXML(xmlOutput, addMessages); } if (propertyListHead != null) { BugProperty prop = propertyListHead; while (prop != null) { prop.writeXML(xmlOutput); prop = prop.getNext(); } } xmlOutput.closeTag(ELEMENT_NAME); } private static final String ELEMENT_NAME = "BugInstance"; private static final String USER_ANNOTATION_ELEMENT_NAME = "UserAnnotation"; /* ---------------------------------------------------------------------- * Implementation * ---------------------------------------------------------------------- */ void add(BugAnnotation annotation) { if (annotation == null) throw new IllegalStateException("Missing BugAnnotation!"); // Add to list annotationList.add(annotation); // This object is being modified, so the cached hashcode // must be invalidated cachedHashCode = INVALID_HASH_CODE; } private void addSourceLinesForMethod(MethodAnnotation methodAnnotation, SourceLineAnnotation sourceLineAnnotation) { if (sourceLineAnnotation != null) { // Note: we don't add the source line annotation directly to // the bug instance. Instead, we stash it in the MethodAnnotation. // It is much more useful there, and it would just be distracting // if it were displayed in the UI, since it would compete for attention // with the actual bug location source line annotation (which is much // more important and interesting). methodAnnotation.setSourceLines(sourceLineAnnotation); } } public int hashCode() { if (cachedHashCode == INVALID_HASH_CODE) { int hashcode = type.hashCode() + priority; Iterator<BugAnnotation> i = annotationIterator(); while (i.hasNext()) hashcode += i.next().hashCode(); if (hashcode == INVALID_HASH_CODE) hashcode = INVALID_HASH_CODE+1; cachedHashCode = hashcode; } return cachedHashCode; } public boolean equals(Object o) { if (!(o instanceof BugInstance)) return false; BugInstance other = (BugInstance) o; if (!type.equals(other.type) || priority != other.priority) return false; if (annotationList.size() != other.annotationList.size()) return false; int numAnnotations = annotationList.size(); for (int i = 0; i < numAnnotations; ++i) { BugAnnotation lhs = annotationList.get(i); BugAnnotation rhs = other.annotationList.get(i); if (!lhs.equals(rhs)) return false; } return true; } public int compareTo(Object o) { BugInstance other = (BugInstance) o; int cmp; cmp = type.compareTo(other.type); if (cmp != 0) return cmp; cmp = priority - other.priority; if (cmp != 0) return cmp; // Compare BugAnnotations lexicographically int pfxLen = Math.min(annotationList.size(), other.annotationList.size()); for (int i = 0; i < pfxLen; ++i) { BugAnnotation lhs = annotationList.get(i); BugAnnotation rhs = other.annotationList.get(i); cmp = lhs.compareTo(rhs); if (cmp != 0) return cmp; } // All elements in prefix were the same, // so use number of elements to decide return annotationList.size() - other.annotationList.size(); } /** * @param firstVersion The firstVersion to set. */ public void setFirstVersion(long firstVersion) { this.firstVersion = firstVersion; if (lastVersion >= 0 && firstVersion > lastVersion) throw new IllegalArgumentException( firstVersion + ".." + lastVersion); } /** * @return Returns the firstVersion. */ public long getFirstVersion() { return firstVersion; } /** * @param lastVersion The lastVersion to set. */ public void setLastVersion(long lastVersion) { if (lastVersion >= 0 && firstVersion > lastVersion) throw new IllegalArgumentException( firstVersion + ".." + lastVersion); this.lastVersion = lastVersion; } /** * @return Returns the lastVersion. */ public long getLastVersion() { return lastVersion; } /** * @param introducedByChangeOfExistingClass The introducedByChangeOfExistingClass to set. */ public void setIntroducedByChangeOfExistingClass(boolean introducedByChangeOfExistingClass) { this.introducedByChangeOfExistingClass = introducedByChangeOfExistingClass; } /** * @return Returns the introducedByChangeOfExistingClass. */ public boolean isIntroducedByChangeOfExistingClass() { return introducedByChangeOfExistingClass; } /** * @param removedByChangeOfPersistingClass The removedByChangeOfPersistingClass to set. */ public void setRemovedByChangeOfPersistingClass(boolean removedByChangeOfPersistingClass) { this.removedByChangeOfPersistingClass = removedByChangeOfPersistingClass; } /** * @return Returns the removedByChangeOfPersistingClass. */ public boolean isRemovedByChangeOfPersistingClass() { return removedByChangeOfPersistingClass; } } // vim:ts=4
mark some things as being nonnull git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@4767 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/BugInstance.java
mark some things as being nonnull
<ide><path>indbugs/src/java/edu/umd/cs/findbugs/BugInstance.java <ide> private int priority; <ide> private ArrayList<BugAnnotation> annotationList; <ide> private int cachedHashCode; <del> private String annotationText; <add> @NonNull private String annotationText; <ide> private BugProperty propertyListHead, propertyListTail; <ide> private String uniqueId; <ide> <ide> * <ide> * @param annotationText the user annotation text <ide> */ <del> public void setAnnotationText(String annotationText) { <add> public void setAnnotationText(@NonNull String annotationText) { <ide> this.annotationText = annotationText; <ide> } <ide> <ide> * <ide> * @return the user annotation text <ide> */ <del> public String getAnnotationText() { <add> @NonNull public String getAnnotationText() { <ide> return annotationText; <ide> } <ide>
Java
apache-2.0
cf4a9f25a2d5ba3581da093a660b72867480ea15
0
cn-cerc/summer-mis,cn-cerc/summer-mis
package cn.cerc.ui.fields; import cn.cerc.core.Record; import cn.cerc.ui.parts.UIComponent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RadioField extends AbstractField { private final List<String> items = new ArrayList<>(); public RadioField(UIComponent owner, String name, String field, int width) { super(owner, name, width); this.setField(field); } @Override public String getText(Record record) { if (record == null) { return null; } int val = record.getInt(field); if (val < 0 || val > items.size() - 1) { return "" + val; } String result = items.get(val); if (result == null) { return "" + val; } else { return result; } } public RadioField add(String... items) { this.items.addAll(Arrays.asList(items)); return this; } }
summer-mis/src/main/java/cn/cerc/ui/fields/RadioField.java
package cn.cerc.ui.fields; import cn.cerc.core.Record; import cn.cerc.ui.parts.UIComponent; import java.util.ArrayList; import java.util.List; public class RadioField extends AbstractField { private List<String> items = new ArrayList<>(); public RadioField(UIComponent owner, String name, String field, int width) { super(owner, name, width); this.setField(field); } @Override public String getText(Record record) { if (record == null) { return null; } int val = record.getInt(field); if (val < 0 || val > items.size() - 1) { return "" + val; } String result = items.get(val); if (result == null) { return "" + val; } else { return result; } } public RadioField add(String... items) { for (String item : items) { this.items.add(item); } return this; } }
Update RadioField.java
summer-mis/src/main/java/cn/cerc/ui/fields/RadioField.java
Update RadioField.java
<ide><path>ummer-mis/src/main/java/cn/cerc/ui/fields/RadioField.java <ide> import cn.cerc.ui.parts.UIComponent; <ide> <ide> import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.List; <ide> <ide> public class RadioField extends AbstractField { <del> private List<String> items = new ArrayList<>(); <add> <add> private final List<String> items = new ArrayList<>(); <ide> <ide> public RadioField(UIComponent owner, String name, String field, int width) { <ide> super(owner, name, width); <ide> } <ide> <ide> public RadioField add(String... items) { <del> for (String item : items) { <del> this.items.add(item); <del> } <add> this.items.addAll(Arrays.asList(items)); <ide> return this; <ide> } <add> <ide> }
Java
lgpl-2.1
5971a752bf12daaebd40261082985ab2ff4437d8
0
JoeCarlson/intermine,justincc/intermine,justincc/intermine,tomck/intermine,elsiklab/intermine,justincc/intermine,kimrutherford/intermine,joshkh/intermine,zebrafishmine/intermine,drhee/toxoMine,JoeCarlson/intermine,JoeCarlson/intermine,zebrafishmine/intermine,justincc/intermine,zebrafishmine/intermine,elsiklab/intermine,justincc/intermine,drhee/toxoMine,tomck/intermine,elsiklab/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,tomck/intermine,kimrutherford/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,JoeCarlson/intermine,elsiklab/intermine,zebrafishmine/intermine,kimrutherford/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,tomck/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,drhee/toxoMine,justincc/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,kimrutherford/intermine,elsiklab/intermine,JoeCarlson/intermine,justincc/intermine,JoeCarlson/intermine,zebrafishmine/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,kimrutherford/intermine,tomck/intermine,tomck/intermine,joshkh/intermine,joshkh/intermine,JoeCarlson/intermine,joshkh/intermine,justincc/intermine,justincc/intermine,tomck/intermine,elsiklab/intermine,joshkh/intermine,drhee/toxoMine,tomck/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,elsiklab/intermine,kimrutherford/intermine,drhee/toxoMine,drhee/toxoMine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine
package org.intermine.web.logic.results; /* * Copyright (C) 2002-2011 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.lang.StringUtils; import org.intermine.api.InterMineAPI; import org.intermine.api.util.PathUtil; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.CollectionDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.proxy.ProxyReference; import org.intermine.objectstore.query.ClobAccess; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathException; import org.intermine.util.DynamicUtil; import org.intermine.util.StringUtil; import org.intermine.web.displayer.CustomDisplayer; import org.intermine.web.displayer.DisplayerManager; import org.intermine.web.logic.config.FieldConfig; import org.intermine.web.logic.config.HeaderConfig; import org.intermine.web.logic.config.InlineList; import org.intermine.web.logic.config.Type; import org.intermine.web.logic.config.WebConfig; import org.intermine.web.logic.pathqueryresult.PathQueryResultHelper; /** * Object to be displayed on report.do * * @author Radek Stepan * @author Richard Smith */ public class ReportObject { private InterMineObject object; private final WebConfig webConfig; /** unqualified (!!) object type string */ private final String objectType; private Map<String, Object> fieldValues; private InterMineAPI im; /** * @List<ReportObjectField> setup list of summary fields this object has */ private List<ReportObjectField> objectSummaryFields; /** @var List header inline lists set by the WebConfig */ private List<InlineList> inlineListsHeader = null; /** @var List of 'unplaced' normal InlineLists */ private List<InlineList> inlineListsNormal = null; private Map<String, Object> attributes = null; private Map<String, String> longAttributes = null; private Map<String, Object> longAttributesTruncated = null; private Map<String, FieldDescriptor> attributeDescriptors = null; private Map<String, DisplayReference> references = null; private Map<String, DisplayCollection> collections = null; private Map<String, DisplayField> refsAndCollections = null; /** @var ObjectStore so we can use PathQueryResultHelper.queryForTypesInCollection */ private ObjectStore os = null; /** * Setup internal ReportObject * @param object InterMineObject * @param webConfig WebConfig * @param im InterMineAPI * @throws Exception Exception */ public ReportObject(InterMineObject object, WebConfig webConfig, InterMineAPI im) throws Exception { this.object = object; this.webConfig = webConfig; this.im = im; this.os = im.getObjectStore(); // infer dynamic type of IM object this.objectType = DynamicUtil.getSimpleClass(object).getSimpleName(); } /** * * @return Map */ public Map<String, List<CustomDisplayer>> getReportDisplayers() { DisplayerManager displayerManager = DisplayerManager.getInstance(webConfig, im); return displayerManager.getReportDisplayersForType(objectType); } /** * Get the id of this object * @return the id */ public int getId() { return object.getId().intValue(); } /** * Get the attribute fields and values for this object * @return the attributes */ public Map<String, Object> getAttributes() { if (attributes == null) { initialise(); } return attributes; } /** * Get the class descriptor for this object * @return one class descriptor */ public ClassDescriptor getClassDescriptor() { return im.getModel().getClassDescriptorByName(objectType); } /** * Get the collection fields and values for this object * @return the collections */ public Map<String, DisplayCollection> getCollections() { if (collections == null) { initialise(); } return collections; } private String stripTail(String input) { Integer dot = input.indexOf("."); if (dot > 0) { return input.substring(0, dot); } return input; } /** * A listing of object fields as pieced together from the various ReportObject methods * @return <ReportObjectField>s List */ public List<ReportObjectField> getObjectSummaryFields() { // are we setup yet? if (objectSummaryFields == null) { objectSummaryFields = new ArrayList<ReportObjectField>(); List<ReportObjectField> objectOtherSummaryFields = new ArrayList<ReportObjectField>(); // to make sure we do not show fields that are replaced elsewhere Set<String> replacedFields = getReplacedFieldExprs(); // traverse all path expressions for the fields that should be used when // summarising the object for (FieldConfig fc : getFieldConfigs()) { // get fieldName String fieldName = fc.getFieldExpr(); // only non-replaced fields if (!replacedFields.contains(stripTail(fieldName))) { // get fieldValue Object fieldValue = getFieldValue(fieldName); // get displayer //FieldConfig fieldConfig = fieldConfigMap.get(fieldName); String fieldDisplayer = fc.getDisplayer(); // new ReportObjectField ReportObjectField rof = new ReportObjectField( objectType, fieldName, fieldValue, fieldDisplayer, fc.getDoNotTruncate() ); // show in summary... if (fc.getShowInSummary()) { objectSummaryFields.add(rof); } else { // show in summary also, but not right now... objectOtherSummaryFields.add(rof); } } } // append the other fields objectSummaryFields.addAll(objectOtherSummaryFields); } return objectSummaryFields; } /** * Get InterMine object * @return InterMineObject */ public InterMineObject getObject() { return object; } /** * Return a list of field configs * @return Collection<FieldConfig> */ public Collection<FieldConfig> getFieldConfigs() { Map<String, Type> types = webConfig.getTypes(); String qualifiedType = DynamicUtil.getSimpleClass(object).getName(); if (types.containsKey(qualifiedType)) { return types.get(qualifiedType).getFieldConfigs(); } return Collections.emptyList(); } /** * Get field value for a field name (expression) * @param fieldExpression String * @return Object */ protected Object getFieldValue(String fieldExpression) { // if field values as a whole are not set yet... if (fieldValues == null) { setupFieldValues(); } // return a field value for a field expression (name) return fieldValues.get(fieldExpression); } /** * Setup fieldValues HashMap */ protected void setupFieldValues() { // create a new map fieldValues = new HashMap<String, Object>(); // fetch field configs for (FieldConfig fc : getFieldConfigs()) { // crete a path string String pathString = objectType + "." + fc.getFieldExpr(); try { // resolve path Path path = new Path(im.getModel(), pathString); fieldValues.put(fc.getFieldExpr(), PathUtil.resolvePath(path, object)); } catch (PathException e) { throw new Error("There must be a bug", e); } } } public String getType() { return objectType; } /** * Used by JSP * @return the main title of this object, i.e.: "eve FBgn0000606" */ public String getTitleMain() { return getTitles("main"); } /** * Used by JSP * @return the subtitle of this object, i.e.: "D. melanogaster" */ public String getTitleSub() { return getTitles("sub"); } /** * Get a title based on the type key we pass it * @param key: main|sub * @return the titles string as resolved based on the path(s) under key */ private String getTitles(String key) { // fetch the Type Type type = webConfig.getTypes().get(getClassDescriptor().getName()); // retrieve the titles map, HeaderConfig serves as a useless wrapper HeaderConfig hc = type.getHeaderConfig(); if (hc != null) { Map<String, LinkedHashMap<String, Object>> titles = hc.getTitles(); // if we have something saved if (titles != null && titles.containsKey(key)) { String result = ""; // concatenate a space delineated title together as resolved from FieldValues for (String path : titles.get(key).keySet()) { Object stuff = getFieldValue(path); if (stuff != null) { String stringyStuff = stuff.toString(); // String.isEmpty() was introduced in Java release 1.6 if (StringUtils.isNotBlank(stringyStuff)) { result += stringyStuff + " "; } } } // trailing space & return if (!result.isEmpty()) { return result.substring(0, result.length() - 1); } } } return null; } /** * Resolve an InlineList by filling it up with a list of list objects, part of initialise() * @param list retrieved from Type * @param bagOfInlineListNames is a bag of names of lists we have resolved so far so these * fields are not resolved elsewhere and skipped instead * @see setDescriptorOnInlineList() is still needed when traversing FieldDescriptors */ private void initialiseInlineList( InlineList list, HashMap<String, Boolean> bagOfInlineListNames ) { // bags inlineListsHeader = (inlineListsHeader != null) ? inlineListsHeader : new ArrayList<InlineList>(); inlineListsNormal = (inlineListsNormal != null) ? inlineListsNormal : new ArrayList<InlineList>(); // soon to be list of values Set<Object> listOfListObjects = null; String columnToDisplayBy = null; try { // create a new path to the collection of objects Path path = new Path(im.getModel(), DynamicUtil.getSimpleClass(object.getClass()).getSimpleName() + '.' + list.getPath()); try { // save the suffix, the value we will show the list by columnToDisplayBy = path.getLastElement(); // create only a prefix of the path so we have // Objects and not just Strings path = path.getPrefix(); } catch (Error e) { throw new RuntimeException("You need to specify a key to display" + "the list by, not just the root element."); } // resolve path to a collection and save into a list listOfListObjects = PathUtil.resolveCollectionPath(path, object); list.setListOfObjects(listOfListObjects, columnToDisplayBy); } catch (PathException e) { throw new RuntimeException("Your collections of inline lists" + "are failing you", e); } // place the list if (list.getShowInHeader()) { inlineListsHeader.add(list); } else { inlineListsNormal.add(list); } // save name of the collection String path = list.getPath(); bagOfInlineListNames.put(path.substring(0, path.indexOf('.')), true); } /** * Resolve an attribute, part of initialise() * @param fd FieldDescriptor */ private void initialiseAttribute(FieldDescriptor fd) { // bags attributes = (attributes != null) ? attributes : new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER); longAttributes = (longAttributes != null) ? longAttributes : new HashMap<String, String>(); longAttributesTruncated = (longAttributesTruncated != null) ? longAttributesTruncated : new HashMap<String, Object>(); attributeDescriptors = (attributeDescriptors != null) ? attributeDescriptors : new HashMap<String, FieldDescriptor>(); Object fieldValue = null; try { fieldValue = object.getFieldValue(fd.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } if (fieldValue != null) { if (fieldValue instanceof ClobAccess) { ClobAccess fieldClob = (ClobAccess) fieldValue; if (fieldClob.length() > 200) { fieldValue = fieldClob.subSequence(0, 200).toString(); } else { fieldValue = fieldClob.toString(); } } attributes.put(fd.getName(), fieldValue); attributeDescriptors.put(fd.getName(), fd); if (fieldValue instanceof String) { String fieldString = (String) fieldValue; if (fieldString.length() > 30) { StringUtil.LineWrappedString lws = StringUtil.wrapLines( fieldString, 50, 3, 11); longAttributes.put(fd.getName(), lws.getString() .replace("\n", "<BR>")); if (lws.isTruncated()) { longAttributesTruncated.put(fd.getName(), Boolean.TRUE); } } } } } /** * Resolve a Reference, part of initialise() * @param fd FieldDescriptor */ private void initialiseReference(FieldDescriptor fd) { // bag references = (references != null) ? references : new TreeMap<String, DisplayReference>(String.CASE_INSENSITIVE_ORDER); ReferenceDescriptor ref = (ReferenceDescriptor) fd; // check whether reference is null without dereferencing Object proxyObject = null; ProxyReference proxy = null; try { proxyObject = object.getFieldProxy(ref.getName()); } catch (IllegalAccessException e1) { e1.printStackTrace(); } if (proxyObject instanceof org.intermine.objectstore.proxy.ProxyReference) { proxy = (ProxyReference) proxyObject; } else { // no go on objects that are not Proxies, ie Tests } DisplayReference newReference = null; try { newReference = new DisplayReference(proxy, ref, webConfig, im.getClassKeys()); } catch (Exception e) { e.printStackTrace(); } if (newReference != null) { if (newReference.collection.size() > 0) { references.put(fd.getName(), newReference); } } } /** * Resolve a Collection, part of initialise() * @param fd FieldDescriptor */ private void initialiseCollection(FieldDescriptor fd) { // bag collections = (collections != null) ? collections : new TreeMap<String, DisplayCollection>(String.CASE_INSENSITIVE_ORDER); Object fieldValue = null; try { fieldValue = object.getFieldValue(fd.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } // determine the types in the collection List<Class<?>> listOfTypes = PathQueryResultHelper. queryForTypesInCollection(object, fd.getName(), os); DisplayCollection newCollection = null; try { newCollection = new DisplayCollection((Collection<?>) fieldValue, (CollectionDescriptor) fd, webConfig, im.getClassKeys(), listOfTypes); } catch (Exception e) { e.printStackTrace(); } if (newCollection != null) { if (newCollection.getCollection().size() > 0) { collections.put(fd.getName(), newCollection); } } } /** * Create the Maps and Lists returned by the getters in this class. */ private void initialise() { // combined Map of References & Collections refsAndCollections = new TreeMap<String, DisplayField>(String.CASE_INSENSITIVE_ORDER); /** InlineLists **/ Type type = webConfig.getTypes().get(getClassDescriptor().getName()); // init lists from WebConfig Type List<InlineList> inlineListsWebConfig = type.getInlineLists(); // a map of inlineList object names so we do not include them elsewhere HashMap<String, Boolean> bagOfInlineListNames = new HashMap<String, Boolean>(); // fill up for (int i = 0; i < inlineListsWebConfig.size(); i++) { initialiseInlineList(inlineListsWebConfig.get(i), bagOfInlineListNames); } /** Attributes, References, Collections through FieldDescriptors **/ for (FieldDescriptor fd : getClassDescriptor().getAllFieldDescriptors()) { // only continue if we have not included this object in an inline list if (bagOfInlineListNames.get(fd.getName()) == null) { if (fd.isAttribute() && !"id".equals(fd.getName())) { /** Attribute **/ initialiseAttribute(fd); } else if (fd.isReference()) { /** Reference **/ initialiseReference(fd); } else if (fd.isCollection()) { /** Collection **/ initialiseCollection(fd); } } else { /** InlineList (cont...) **/ // assign Descriptor from FieldDescriptors to the InlineList setDescriptorOnInlineList(fd.getName(), fd); } } // make a combined Map if (references != null) refsAndCollections.putAll(references); if (collections != null) refsAndCollections.putAll(collections); } /** * Get all the reference and collection fields and values for this object * @return the collections */ public Map<String, DisplayField> getRefsAndCollections() { if (refsAndCollections == null) { initialise(); } return refsAndCollections; } /** * * @return Set */ public Set<String> getReplacedFieldExprs() { Set<String> replacedFieldExprs = new HashSet<String>(); for (CustomDisplayer reportDisplayer : getAllReportDisplayers()) { replacedFieldExprs.addAll(reportDisplayer.getReplacedFieldExprs()); } return replacedFieldExprs; } /** * * @return Set */ public Set<CustomDisplayer> getAllReportDisplayers() { DisplayerManager displayerManager = DisplayerManager.getInstance(webConfig, im); String clsName = DynamicUtil.getSimpleClass(object).getSimpleName(); return displayerManager.getAllReportDisplayersForType(clsName); } /** * Get attribute descriptors. * @return map of attribute descriptors */ public Map<String, FieldDescriptor> getAttributeDescriptors() { if (attributeDescriptors == null) { initialise(); } return attributeDescriptors; } /** * Set Descriptor (for placement) on an InlineList, only done for normal lists * @param name * @param fd */ private void setDescriptorOnInlineList(String name, FieldDescriptor fd) { done: for (InlineList list : inlineListsNormal) { Object path = list.getPath(); if (((String) path).substring(0, ((String) path).indexOf('.')).equals(name)) { list.setDescriptor(fd); break done; } } } /** * * @return InlineLists that are resolved into their respective placements */ public List<InlineList> getNormalInlineLists() { if (inlineListsNormal == null) { initialise(); } return inlineListsNormal; } /** * * @return InlineLists to be shown in the header */ public List<InlineList> getHeaderInlineLists() { if (inlineListsHeader == null) { initialise(); } return inlineListsHeader; } /** * Used from JSP * @return true if we have inlineListsHeader */ public Boolean getHasHeaderInlineLists() { return (getHeaderInlineLists() != null); } /** * Used from JSP * @return true if we have InlineLists with no placement yet */ public Boolean getHasNormalInlineLists() { return (getNormalInlineLists() != null); } }
intermine/web/main/src/org/intermine/web/logic/results/ReportObject.java
package org.intermine.web.logic.results; /* * Copyright (C) 2002-2011 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.lang.StringUtils; import org.intermine.api.InterMineAPI; import org.intermine.api.util.PathUtil; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.CollectionDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.proxy.ProxyReference; import org.intermine.objectstore.query.ClobAccess; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathException; import org.intermine.util.DynamicUtil; import org.intermine.util.StringUtil; import org.intermine.web.displayer.CustomDisplayer; import org.intermine.web.displayer.DisplayerManager; import org.intermine.web.logic.config.FieldConfig; import org.intermine.web.logic.config.HeaderConfig; import org.intermine.web.logic.config.InlineList; import org.intermine.web.logic.config.Type; import org.intermine.web.logic.config.WebConfig; import org.intermine.web.logic.pathqueryresult.PathQueryResultHelper; /** * Object to be displayed on report.do * * @author Radek Stepan * @author Richard Smith */ public class ReportObject { private InterMineObject object; private final WebConfig webConfig; /** unqualified (!!) object type string */ private final String objectType; private Map<String, Object> fieldValues; private InterMineAPI im; /** * @List<ReportObjectField> setup list of summary fields this object has */ private List<ReportObjectField> objectSummaryFields; /** @var List header inline lists set by the WebConfig */ private List<InlineList> inlineListsHeader = null; /** @var List of 'unplaced' normal InlineLists */ private List<InlineList> inlineListsNormal = null; private Map<String, Object> attributes = null; private Map<String, String> longAttributes = null; private Map<String, Object> longAttributesTruncated = null; private Map<String, FieldDescriptor> attributeDescriptors = null; private Map<String, DisplayReference> references = null; private Map<String, DisplayCollection> collections = null; private Map<String, DisplayField> refsAndCollections = null; /** @var ObjectStore so we can use PathQueryResultHelper.queryForTypesInCollection */ private ObjectStore os = null; /** * Setup internal ReportObject * @param object InterMineObject * @param webConfig WebConfig * @param im InterMineAPI * @throws Exception Exception */ public ReportObject(InterMineObject object, WebConfig webConfig, InterMineAPI im) throws Exception { this.object = object; this.webConfig = webConfig; this.im = im; this.os = im.getObjectStore(); // infer dynamic type of IM object this.objectType = DynamicUtil.getSimpleClass(object).getSimpleName(); } /** * * @return Map */ public Map<String, List<CustomDisplayer>> getReportDisplayers() { DisplayerManager displayerManager = DisplayerManager.getInstance(webConfig, im); return displayerManager.getReportDisplayersForType(objectType); } /** * Get the id of this object * @return the id */ public int getId() { return object.getId().intValue(); } /** * Get the attribute fields and values for this object * @return the attributes */ public Map<String, Object> getAttributes() { if (attributes == null) { initialise(); } return attributes; } /** * Get the class descriptor for this object * @return one class descriptor */ public ClassDescriptor getClassDescriptor() { return im.getModel().getClassDescriptorByName(objectType); } /** * Get the collection fields and values for this object * @return the collections */ public Map<String, DisplayCollection> getCollections() { if (collections == null) { initialise(); } return collections; } /** * A listing of object fields as pieced together from the various ReportObject methods * @return <ReportObjectField>s List */ public List<ReportObjectField> getObjectSummaryFields() { // are we setup yet? if (objectSummaryFields == null) { objectSummaryFields = new ArrayList<ReportObjectField>(); List<ReportObjectField> objectOtherSummaryFields = new ArrayList<ReportObjectField>(); // traverse all path expressions for the fields that should be used when // summarising the object for (FieldConfig fc : getFieldConfigs()) { // get fieldName String fieldName = fc.getFieldExpr(); // get fieldValue Object fieldValue = getFieldValue(fieldName); // get displayer //FieldConfig fieldConfig = fieldConfigMap.get(fieldName); String fieldDisplayer = fc.getDisplayer(); // new ReportObjectField ReportObjectField rof = new ReportObjectField( objectType, fieldName, fieldValue, fieldDisplayer, fc.getDoNotTruncate() ); // show in summary... if (fc.getShowInSummary()) { objectSummaryFields.add(rof); } else { // show in summary also, but not right now... objectOtherSummaryFields.add(rof); } } // append the other fields objectSummaryFields.addAll(objectOtherSummaryFields); } return objectSummaryFields; } /** * Get InterMine object * @return InterMineObject */ public InterMineObject getObject() { return object; } /** * Return a list of field configs * @return Collection<FieldConfig> */ public Collection<FieldConfig> getFieldConfigs() { Map<String, Type> types = webConfig.getTypes(); String qualifiedType = DynamicUtil.getSimpleClass(object).getName(); if (types.containsKey(qualifiedType)) { return types.get(qualifiedType).getFieldConfigs(); } return Collections.emptyList(); } /** * Get field value for a field name (expression) * @param fieldExpression String * @return Object */ protected Object getFieldValue(String fieldExpression) { // if field values as a whole are not set yet... if (fieldValues == null) { setupFieldValues(); } // return a field value for a field expression (name) return fieldValues.get(fieldExpression); } /** * Setup fieldValues HashMap */ protected void setupFieldValues() { // create a new map fieldValues = new HashMap<String, Object>(); // fetch field configs for (FieldConfig fc : getFieldConfigs()) { // crete a path string String pathString = objectType + "." + fc.getFieldExpr(); try { // resolve path Path path = new Path(im.getModel(), pathString); fieldValues.put(fc.getFieldExpr(), PathUtil.resolvePath(path, object)); } catch (PathException e) { throw new Error("There must be a bug", e); } } } public String getType() { return objectType; } /** * Used by JSP * @return the main title of this object, i.e.: "eve FBgn0000606" */ public String getTitleMain() { return getTitles("main"); } /** * Used by JSP * @return the subtitle of this object, i.e.: "D. melanogaster" */ public String getTitleSub() { return getTitles("sub"); } /** * Get a title based on the type key we pass it * @param key: main|sub * @return the titles string as resolved based on the path(s) under key */ private String getTitles(String key) { // fetch the Type Type type = webConfig.getTypes().get(getClassDescriptor().getName()); // retrieve the titles map, HeaderConfig serves as a useless wrapper HeaderConfig hc = type.getHeaderConfig(); if (hc != null) { Map<String, LinkedHashMap<String, Object>> titles = hc.getTitles(); // if we have something saved if (titles != null && titles.containsKey(key)) { String result = ""; // concatenate a space delineated title together as resolved from FieldValues for (String path : titles.get(key).keySet()) { Object stuff = getFieldValue(path); if (stuff != null) { String stringyStuff = stuff.toString(); // String.isEmpty() was introduced in Java release 1.6 if (StringUtils.isNotBlank(stringyStuff)) { result += stringyStuff + " "; } } } // trailing space & return if (!result.isEmpty()) { return result.substring(0, result.length() - 1); } } } return null; } /** * Resolve an InlineList by filling it up with a list of list objects, part of initialise() * @param list retrieved from Type * @param bagOfInlineListNames is a bag of names of lists we have resolved so far so these * fields are not resolved elsewhere and skipped instead * @see setDescriptorOnInlineList() is still needed when traversing FieldDescriptors */ private void initialiseInlineList( InlineList list, HashMap<String, Boolean> bagOfInlineListNames ) { // bags inlineListsHeader = (inlineListsHeader != null) ? inlineListsHeader : new ArrayList<InlineList>(); inlineListsNormal = (inlineListsNormal != null) ? inlineListsNormal : new ArrayList<InlineList>(); // soon to be list of values Set<Object> listOfListObjects = null; String columnToDisplayBy = null; try { // create a new path to the collection of objects Path path = new Path(im.getModel(), DynamicUtil.getSimpleClass(object.getClass()).getSimpleName() + '.' + list.getPath()); try { // save the suffix, the value we will show the list by columnToDisplayBy = path.getLastElement(); // create only a prefix of the path so we have // Objects and not just Strings path = path.getPrefix(); } catch (Error e) { throw new RuntimeException("You need to specify a key to display" + "the list by, not just the root element."); } // resolve path to a collection and save into a list listOfListObjects = PathUtil.resolveCollectionPath(path, object); list.setListOfObjects(listOfListObjects, columnToDisplayBy); } catch (PathException e) { throw new RuntimeException("Your collections of inline lists" + "are failing you", e); } // place the list if (list.getShowInHeader()) { inlineListsHeader.add(list); } else { inlineListsNormal.add(list); } // save name of the collection String path = list.getPath(); bagOfInlineListNames.put(path.substring(0, path.indexOf('.')), true); } /** * Resolve an attribute, part of initialise() * @param fd FieldDescriptor */ private void initialiseAttribute(FieldDescriptor fd) { // bags attributes = (attributes != null) ? attributes : new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER); longAttributes = (longAttributes != null) ? longAttributes : new HashMap<String, String>(); longAttributesTruncated = (longAttributesTruncated != null) ? longAttributesTruncated : new HashMap<String, Object>(); attributeDescriptors = (attributeDescriptors != null) ? attributeDescriptors : new HashMap<String, FieldDescriptor>(); Object fieldValue = null; try { fieldValue = object.getFieldValue(fd.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } if (fieldValue != null) { if (fieldValue instanceof ClobAccess) { ClobAccess fieldClob = (ClobAccess) fieldValue; if (fieldClob.length() > 200) { fieldValue = fieldClob.subSequence(0, 200).toString(); } else { fieldValue = fieldClob.toString(); } } attributes.put(fd.getName(), fieldValue); attributeDescriptors.put(fd.getName(), fd); if (fieldValue instanceof String) { String fieldString = (String) fieldValue; if (fieldString.length() > 30) { StringUtil.LineWrappedString lws = StringUtil.wrapLines( fieldString, 50, 3, 11); longAttributes.put(fd.getName(), lws.getString() .replace("\n", "<BR>")); if (lws.isTruncated()) { longAttributesTruncated.put(fd.getName(), Boolean.TRUE); } } } } } /** * Resolve a Reference, part of initialise() * @param fd FieldDescriptor */ private void initialiseReference(FieldDescriptor fd) { // bag references = (references != null) ? references : new TreeMap<String, DisplayReference>(String.CASE_INSENSITIVE_ORDER); ReferenceDescriptor ref = (ReferenceDescriptor) fd; // check whether reference is null without dereferencing Object proxyObject = null; ProxyReference proxy = null; try { proxyObject = object.getFieldProxy(ref.getName()); } catch (IllegalAccessException e1) { e1.printStackTrace(); } if (proxyObject instanceof org.intermine.objectstore.proxy.ProxyReference) { proxy = (ProxyReference) proxyObject; } else { // no go on objects that are not Proxies, ie Tests } DisplayReference newReference = null; try { newReference = new DisplayReference(proxy, ref, webConfig, im.getClassKeys()); } catch (Exception e) { e.printStackTrace(); } if (newReference != null) { if (newReference.collection.size() > 0) { references.put(fd.getName(), newReference); } } } /** * Resolve a Collection, part of initialise() * @param fd FieldDescriptor */ private void initialiseCollection(FieldDescriptor fd) { // bag collections = (collections != null) ? collections : new TreeMap<String, DisplayCollection>(String.CASE_INSENSITIVE_ORDER); Object fieldValue = null; try { fieldValue = object.getFieldValue(fd.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } // determine the types in the collection List<Class<?>> listOfTypes = PathQueryResultHelper. queryForTypesInCollection(object, fd.getName(), os); DisplayCollection newCollection = null; try { newCollection = new DisplayCollection((Collection<?>) fieldValue, (CollectionDescriptor) fd, webConfig, im.getClassKeys(), listOfTypes); } catch (Exception e) { e.printStackTrace(); } if (newCollection != null) { if (newCollection.getCollection().size() > 0) { collections.put(fd.getName(), newCollection); } } } /** * Create the Maps and Lists returned by the getters in this class. */ private void initialise() { // combined Map of References & Collections refsAndCollections = new TreeMap<String, DisplayField>(String.CASE_INSENSITIVE_ORDER); /** InlineLists **/ Type type = webConfig.getTypes().get(getClassDescriptor().getName()); // init lists from WebConfig Type List<InlineList> inlineListsWebConfig = type.getInlineLists(); // a map of inlineList object names so we do not include them elsewhere HashMap<String, Boolean> bagOfInlineListNames = new HashMap<String, Boolean>(); // fill up for (int i = 0; i < inlineListsWebConfig.size(); i++) { initialiseInlineList(inlineListsWebConfig.get(i), bagOfInlineListNames); } /** Attributes, References, Collections through FieldDescriptors **/ for (FieldDescriptor fd : getClassDescriptor().getAllFieldDescriptors()) { // only continue if we have not included this object in an inline list if (bagOfInlineListNames.get(fd.getName()) == null) { if (fd.isAttribute() && !"id".equals(fd.getName())) { /** Attribute **/ initialiseAttribute(fd); } else if (fd.isReference()) { /** Reference **/ initialiseReference(fd); } else if (fd.isCollection()) { /** Collection **/ initialiseCollection(fd); } } else { /** InlineList (cont...) **/ // assign Descriptor from FieldDescriptors to the InlineList setDescriptorOnInlineList(fd.getName(), fd); } } // make a combined Map if (references != null) refsAndCollections.putAll(references); if (collections != null) refsAndCollections.putAll(collections); } /** * Get all the reference and collection fields and values for this object * @return the collections */ public Map<String, DisplayField> getRefsAndCollections() { if (refsAndCollections == null) { initialise(); } return refsAndCollections; } /** * * @return Set */ public Set<String> getReplacedFieldExprs() { Set<String> replacedFieldExprs = new HashSet<String>(); for (CustomDisplayer reportDisplayer : getAllReportDisplayers()) { replacedFieldExprs.addAll(reportDisplayer.getReplacedFieldExprs()); } return replacedFieldExprs; } /** * * @return Set */ public Set<CustomDisplayer> getAllReportDisplayers() { DisplayerManager displayerManager = DisplayerManager.getInstance(webConfig, im); String clsName = DynamicUtil.getSimpleClass(object).getSimpleName(); return displayerManager.getAllReportDisplayersForType(clsName); } /** * Get attribute descriptors. * @return map of attribute descriptors */ public Map<String, FieldDescriptor> getAttributeDescriptors() { if (attributeDescriptors == null) { initialise(); } return attributeDescriptors; } /** * Set Descriptor (for placement) on an InlineList, only done for normal lists * @param name * @param fd */ private void setDescriptorOnInlineList(String name, FieldDescriptor fd) { done: for (InlineList list : inlineListsNormal) { Object path = list.getPath(); if (((String) path).substring(0, ((String) path).indexOf('.')).equals(name)) { list.setDescriptor(fd); break done; } } } /** * * @return InlineLists that are resolved into their respective placements */ public List<InlineList> getNormalInlineLists() { if (inlineListsNormal == null) { initialise(); } return inlineListsNormal; } /** * * @return InlineLists to be shown in the header */ public List<InlineList> getHeaderInlineLists() { if (inlineListsHeader == null) { initialise(); } return inlineListsHeader; } /** * Used from JSP * @return true if we have inlineListsHeader */ public Boolean getHasHeaderInlineLists() { return (getHeaderInlineLists() != null); } /** * Used from JSP * @return true if we have InlineLists with no placement yet */ public Boolean getHasNormalInlineLists() { return (getNormalInlineLists() != null); } }
Make sure we do not include replaced fields in the header
intermine/web/main/src/org/intermine/web/logic/results/ReportObject.java
Make sure we do not include replaced fields in the header
<ide><path>ntermine/web/main/src/org/intermine/web/logic/results/ReportObject.java <ide> return collections; <ide> } <ide> <add> private String stripTail(String input) { <add> Integer dot = input.indexOf("."); <add> if (dot > 0) { <add> return input.substring(0, dot); <add> } <add> return input; <add> } <add> <ide> /** <ide> * A listing of object fields as pieced together from the various ReportObject methods <ide> * @return <ReportObjectField>s List <ide> objectSummaryFields = new ArrayList<ReportObjectField>(); <ide> List<ReportObjectField> objectOtherSummaryFields = new ArrayList<ReportObjectField>(); <ide> <add> // to make sure we do not show fields that are replaced elsewhere <add> Set<String> replacedFields = getReplacedFieldExprs(); <add> <ide> // traverse all path expressions for the fields that should be used when <ide> // summarising the object <ide> for (FieldConfig fc : getFieldConfigs()) { <ide> // get fieldName <ide> String fieldName = fc.getFieldExpr(); <ide> <del> // get fieldValue <del> Object fieldValue = getFieldValue(fieldName); <del> <del> // get displayer <del> //FieldConfig fieldConfig = fieldConfigMap.get(fieldName); <del> String fieldDisplayer = fc.getDisplayer(); <del> <del> // new ReportObjectField <del> ReportObjectField rof = new ReportObjectField( <del> objectType, <del> fieldName, <del> fieldValue, <del> fieldDisplayer, <del> fc.getDoNotTruncate() <del> ); <del> <del> // show in summary... <del> if (fc.getShowInSummary()) { <del> objectSummaryFields.add(rof); <del> } else { // show in summary also, but not right now... <del> objectOtherSummaryFields.add(rof); <add> // only non-replaced fields <add> if (!replacedFields.contains(stripTail(fieldName))) { <add> // get fieldValue <add> Object fieldValue = getFieldValue(fieldName); <add> <add> // get displayer <add> //FieldConfig fieldConfig = fieldConfigMap.get(fieldName); <add> String fieldDisplayer = fc.getDisplayer(); <add> <add> // new ReportObjectField <add> ReportObjectField rof = new ReportObjectField( <add> objectType, <add> fieldName, <add> fieldValue, <add> fieldDisplayer, <add> fc.getDoNotTruncate() <add> ); <add> <add> // show in summary... <add> if (fc.getShowInSummary()) { <add> objectSummaryFields.add(rof); <add> } else { // show in summary also, but not right now... <add> objectOtherSummaryFields.add(rof); <add> } <ide> } <ide> } <ide> // append the other fields
Java
apache-2.0
3183a389b0213095a6ac9490568dac99a97eb54c
0
pierre/collector,pierre/collector,ning/collector,pierre/collector,ning/collector,pierre/collector,ning/collector,ning/collector,ning/collector,pierre/collector,pierre/collector
/* * Copyright 2010-2011 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.metrics.collector.endpoint.resources; import com.google.inject.Inject; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.Response; import com.ning.metrics.collector.binder.config.CollectorConfig; import com.ning.metrics.collector.endpoint.servers.JettyServer; import com.ning.metrics.collector.hadoop.processing.BufferingEventCollector; import com.ning.metrics.collector.util.Ip; import com.ning.metrics.serialization.event.Event; import com.ning.metrics.serialization.thrift.ThriftEnvelope; import com.ning.metrics.serialization.thrift.ThriftField; import com.ning.metrics.serialization.writer.MockEventWriter; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Guice; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; // This is a great integration test, but it doesn't seem to work reliably // (some weird race condition between Guice and Jersey endpoints, and conflicts with TestBodyResource) @Test(groups = "slow", singleThreaded = true, enabled = false) @Guice(modules = JettyTestModule.class) public class TestCollectorResource extends TestPublicAPI { @Inject CollectorConfig config; @Inject JettyServer server; @Inject BufferingEventCollector incomingQueue; @Inject MockEventWriter hdfsWriter; @BeforeClass public void setup() throws Exception { super.setUp(server); } @AfterClass public void tearDown() throws Exception { super.tearDown(server); } public void testGetSimpleEvent() throws Exception { final Event event = sendGetEvent("/1?v=Hello,sWorld"); Assert.assertEquals(event.getName(), "Hello"); final List<ThriftField> payload = ((ThriftEnvelope) event.getData()).getPayload(); Assert.assertEquals(payload.get(0).getDataItem().getString(), "World"); } public void testGetComplicatedEvent() throws Exception { // TODO datetime? final long dateTimeBeforeSend = System.currentTimeMillis(); final Event event = sendGetEvent("/1?v=ComplicatedEvent,xdate,xhost,xpath,xua,xip,scookie,ssubdomain,sscreename,ssection,b1,b1,b0,81231956164000"); final long dateTimeAfterSend = System.currentTimeMillis(); Assert.assertEquals(event.getName(), "ComplicatedEvent"); final List<ThriftField> payload = ((ThriftEnvelope) event.getData()).getPayload(); final long eventDateTime = payload.get(0).getDataItem().getLong(); Assert.assertTrue(eventDateTime > dateTimeBeforeSend); Assert.assertTrue(eventDateTime < dateTimeAfterSend); Assert.assertEquals(payload.get(1).getDataItem().getString(), AWESOME_REFERRER_HOST); Assert.assertEquals(payload.get(2).getDataItem().getString(), AWESOME_REFERRER_PATH); Assert.assertEquals(payload.get(3).getDataItem().getString(), MEGATRON_2000_USER_AGENT); Assert.assertEquals(payload.get(4).getDataItem().getInteger(), new Integer(Ip.ipToInt("127.0.0.1"))); Assert.assertEquals(payload.get(5).getDataItem().getString(), "cookie"); Assert.assertEquals(payload.get(6).getDataItem().getString(), "subdomain"); Assert.assertEquals(payload.get(7).getDataItem().getString(), "screename"); Assert.assertEquals(payload.get(8).getDataItem().getString(), "section"); Assert.assertEquals(payload.get(9).getDataItem().getBoolean(), Boolean.TRUE); Assert.assertEquals(payload.get(10).getDataItem().getBoolean(), Boolean.TRUE); Assert.assertEquals(payload.get(11).getDataItem().getBoolean(), Boolean.FALSE); Assert.assertEquals(payload.get(12).getDataItem().getLong(), new Long(1231956164000L)); } private Event sendGetEvent(final String path) throws InterruptedException, ExecutionException, IOException { assertCleanQueues(incomingQueue); final AsyncHttpClient.BoundRequestBuilder requestBuilder = client.prepareGet("http://127.0.0.1:" + config.getLocalPort() + path) .addHeader("Referer", "http://" + AWESOME_REFERRER_HOST + AWESOME_REFERRER_PATH); final Response response = requestBuilder.execute().get(); Assert.assertEquals(response.getStatusCode(), 202); return assertEventWasWrittenToHDFS(incomingQueue, hdfsWriter); } }
src/test/java/com/ning/metrics/collector/endpoint/resources/TestCollectorResource.java
/* * Copyright 2010-2011 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.metrics.collector.endpoint.resources; import com.google.inject.Inject; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.Response; import com.ning.metrics.collector.binder.config.CollectorConfig; import com.ning.metrics.collector.endpoint.servers.JettyServer; import com.ning.metrics.collector.hadoop.processing.BufferingEventCollector; import com.ning.metrics.collector.util.Ip; import com.ning.metrics.serialization.event.Event; import com.ning.metrics.serialization.thrift.ThriftEnvelope; import com.ning.metrics.serialization.thrift.ThriftField; import com.ning.metrics.serialization.writer.MockEventWriter; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Guice; import org.testng.annotations.Test; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; @Test(groups = "slow", singleThreaded = true) @Guice(modules = JettyTestModule.class) public class TestCollectorResource extends TestPublicAPI { @Inject CollectorConfig config; @Inject JettyServer server; @Inject BufferingEventCollector incomingQueue; @Inject MockEventWriter hdfsWriter; @BeforeClass public void setup() throws Exception { super.setUp(server); } @AfterClass public void tearDown() throws Exception { super.tearDown(server); } public void testGetSimpleEvent() throws Exception { final Event event = sendGetEvent("/1?v=Hello,sWorld"); Assert.assertEquals(event.getName(), "Hello"); final List<ThriftField> payload = ((ThriftEnvelope) event.getData()).getPayload(); Assert.assertEquals(payload.get(0).getDataItem().getString(), "World"); } public void testGetComplicatedEvent() throws Exception { // TODO datetime? final long dateTimeBeforeSend = System.currentTimeMillis(); final Event event = sendGetEvent("/1?v=ComplicatedEvent,xdate,xhost,xpath,xua,xip,scookie,ssubdomain,sscreename,ssection,b1,b1,b0,81231956164000"); final long dateTimeAfterSend = System.currentTimeMillis(); Assert.assertEquals(event.getName(), "ComplicatedEvent"); final List<ThriftField> payload = ((ThriftEnvelope) event.getData()).getPayload(); final long eventDateTime = payload.get(0).getDataItem().getLong(); Assert.assertTrue(eventDateTime > dateTimeBeforeSend); Assert.assertTrue(eventDateTime < dateTimeAfterSend); Assert.assertEquals(payload.get(1).getDataItem().getString(), AWESOME_REFERRER_HOST); Assert.assertEquals(payload.get(2).getDataItem().getString(), AWESOME_REFERRER_PATH); Assert.assertEquals(payload.get(3).getDataItem().getString(), MEGATRON_2000_USER_AGENT); Assert.assertEquals(payload.get(4).getDataItem().getInteger(), new Integer(Ip.ipToInt("127.0.0.1"))); Assert.assertEquals(payload.get(5).getDataItem().getString(), "cookie"); Assert.assertEquals(payload.get(6).getDataItem().getString(), "subdomain"); Assert.assertEquals(payload.get(7).getDataItem().getString(), "screename"); Assert.assertEquals(payload.get(8).getDataItem().getString(), "section"); Assert.assertEquals(payload.get(9).getDataItem().getBoolean(), Boolean.TRUE); Assert.assertEquals(payload.get(10).getDataItem().getBoolean(), Boolean.TRUE); Assert.assertEquals(payload.get(11).getDataItem().getBoolean(), Boolean.FALSE); Assert.assertEquals(payload.get(12).getDataItem().getLong(), new Long(1231956164000L)); } private Event sendGetEvent(final String path) throws InterruptedException, ExecutionException, IOException { assertCleanQueues(incomingQueue); final AsyncHttpClient.BoundRequestBuilder requestBuilder = client.prepareGet("http://127.0.0.1:" + config.getLocalPort() + path) .addHeader("Referer", "http://" + AWESOME_REFERRER_HOST + AWESOME_REFERRER_PATH); final Response response = requestBuilder.execute().get(); Assert.assertEquals(response.getStatusCode(), 202); return assertEventWasWrittenToHDFS(incomingQueue, hdfsWriter); } }
test: disable TestCollectorResource It never worked reliably with IDEA/surefire. Works great ran in standalone though. Signed-off-by: Pierre-Alexandre Meyer <[email protected]>
src/test/java/com/ning/metrics/collector/endpoint/resources/TestCollectorResource.java
test: disable TestCollectorResource
<ide><path>rc/test/java/com/ning/metrics/collector/endpoint/resources/TestCollectorResource.java <ide> import java.util.List; <ide> import java.util.concurrent.ExecutionException; <ide> <del>@Test(groups = "slow", singleThreaded = true) <add>// This is a great integration test, but it doesn't seem to work reliably <add>// (some weird race condition between Guice and Jersey endpoints, and conflicts with TestBodyResource) <add>@Test(groups = "slow", singleThreaded = true, enabled = false) <ide> @Guice(modules = JettyTestModule.class) <ide> public class TestCollectorResource extends TestPublicAPI <ide> {
Java
lgpl-2.1
b2cc418d306c60379daec889578314cba601ef5c
0
n8han/Databinder-for-Wicket,n8han/Databinder-for-Wicket,n8han/Databinder-for-Wicket,n8han/Databinder-for-Wicket
/* * Databinder: a simple bridge from Wicket to Hibernate * Copyright (C) 2006 Nathan Hamblen [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package net.databinder.auth.components; import net.databinder.auth.IAuthSettings; import net.databinder.components.DataPage; import net.databinder.components.StyleLink; import wicket.Application; import wicket.WicketRuntimeException; import wicket.markup.html.WebMarkupContainer; import wicket.markup.html.WebPage; import wicket.markup.html.link.Link; import wicket.markup.html.panel.Panel; /** * Serves as both a sign in and simple regristration page. To use a differnt sign in page, * override AuthDataApplication's getSignInPageClass() method. * @author Nathan Hamblen */ public class DataSignInPage extends WebPage { /** state of page, sign in or registration */ private boolean register = false; /** Registration panel whose visibility is controlled from this class. */ private Panel registerPanel; /** Sign-in panel whose visibility is controlled from this class. */ private Panel signInPanel; /** * Displays sign in page. Checks that the page being instantiated is of the type returned * by AuthDataApplication.getSignInPageClass(). */ public DataSignInPage() { // make sure nothing funny is going on, since this page has a default // constructor and is bookmarkable if (!((IAuthSettings)Application.get()).getSignInPageClass().equals(getClass())) throw new WicketRuntimeException("The sign in page requested does not match that defined in the AuthDataApplication subclass."); add(new StyleLink("dataStylesheet", DataPage.class)); add(new StyleLink("signinStylesheet", DataSignInPage.class)); add(new WebMarkupContainer("gotoRegister"){ @Override public boolean isVisible() { return !register; } }.add(new Link("register") { @Override public void onClick() { setRegister(true); } })); add(new WebMarkupContainer("gotoSignIn"){ @Override public boolean isVisible() { return register; } }.add(new Link("signIn") { @Override public void onClick() { setRegister(false); } })); add(signInPanel = getSignInPanel("signInPanel")); add(registerPanel = getRegisterPanel("registerPanel")); setRegister(register); } /** * Override to use subclass of DataSignInPanel or some other panel. * @param id use this id for your registration panel * @return panel that appears for signing in */ protected Panel getSignInPanel(String id) { return new DataSignInPanel(id); } /** * Override to use subclass of DataRegisterPanel or some other panel. * @param id use this id for your registration panel * @return panel that appears after user clicks registration link */ protected Panel getRegisterPanel(String id) { return new DataRegisterPanel(id); } /** * @return true if displaying registration page */ protected boolean isRegister() { return register; } /** * @param register true to display the registration version of this page */ protected void setRegister(boolean register) { this.register = register; registerPanel.setVisible(register); signInPanel.setVisible(!register); } }
src/main/java/net/databinder/auth/components/DataSignInPage.java
/* * Databinder: a simple bridge from Wicket to Hibernate * Copyright (C) 2006 Nathan Hamblen [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package net.databinder.auth.components; import net.databinder.auth.IAuthSettings; import net.databinder.components.DataPage; import net.databinder.components.StyleLink; import wicket.Application; import wicket.WicketRuntimeException; import wicket.markup.html.WebMarkupContainer; import wicket.markup.html.WebPage; import wicket.markup.html.link.Link; import wicket.markup.html.panel.Panel; /** * Serves as both a sign in and simple regristration page. To use a differnt sign in page, * override AuthDataApplication's getSignInPageClass() method. * @author Nathan Hamblen */ public class DataSignInPage extends WebPage { /** state of page, sign in or registration */ private boolean register = false; /** Registration panel whose visibility is controlled from this class. */ private Panel registerPanel; /** * Displays sign in page. Checks that the page being instantiated is of the type returned * by AuthDataApplication.getSignInPageClass(). */ public DataSignInPage() { // make sure nothing funny is going on, since this page has a default // constructor and is bookmarkable if (!((IAuthSettings)Application.get()).getSignInPageClass().equals(getClass())) throw new WicketRuntimeException("The sign in page requested does not match that defined in the AuthDataApplication subclass."); add(new StyleLink("dataStylesheet", DataPage.class)); add(new StyleLink("signinStylesheet", DataSignInPage.class)); add(new WebMarkupContainer("gotoRegister"){ @Override public boolean isVisible() { return !register; } }.add(new Link("register") { @Override public void onClick() { setRegister(true); } })); add(new WebMarkupContainer("gotoSignIn"){ @Override public boolean isVisible() { return register; } }.add(new Link("signIn") { @Override public void onClick() { setRegister(false); } })); add(new DataSignInPanel("signInPanel") { @Override public boolean isVisible() { return !register; } }); add(registerPanel = getRegisterPanel("registerPanel")); setRegister(register); } /** * Override to use subclass of DataRegisterPanel or some other panel. * @param id use this id for your registration panel * @return panel that appears after user clicks registration link */ protected Panel getRegisterPanel(String id) { return new DataRegisterPanel(id); } /** * @return true if displaying registration page */ protected boolean isRegister() { return register; } /** * @param register true to display the registration version of this page */ protected void setRegister(boolean register) { this.register = register; registerPanel.setVisible(register); } }
permit overriding sign in panel git-svn-id: a029deac1672d4faad1f67456e5ca11caf16dc5a@1022 c322e9cc-cc08-0410-988e-c197163ad9eb
src/main/java/net/databinder/auth/components/DataSignInPage.java
permit overriding sign in panel
<ide><path>rc/main/java/net/databinder/auth/components/DataSignInPage.java <ide> /** Registration panel whose visibility is controlled from this class. */ <ide> private Panel registerPanel; <ide> <add> /** Sign-in panel whose visibility is controlled from this class. */ <add> private Panel signInPanel; <add> <ide> /** <ide> * Displays sign in page. Checks that the page being instantiated is of the type returned <ide> * by AuthDataApplication.getSignInPageClass(). <ide> } <ide> })); <ide> <del> add(new DataSignInPanel("signInPanel") { <del> @Override <del> public boolean isVisible() { <del> return !register; <del> } <del> }); <del> <add> add(signInPanel = getSignInPanel("signInPanel")); <ide> add(registerPanel = getRegisterPanel("registerPanel")); <ide> setRegister(register); <add> } <add> <add> /** <add> * Override to use subclass of DataSignInPanel or some other panel. <add> * @param id use this id for your registration panel <add> * @return panel that appears for signing in <add> */ <add> protected Panel getSignInPanel(String id) { <add> return new DataSignInPanel(id); <ide> } <ide> <ide> /** <ide> protected void setRegister(boolean register) { <ide> this.register = register; <ide> registerPanel.setVisible(register); <add> signInPanel.setVisible(!register); <ide> } <ide> }
Java
lgpl-2.1
0f49153330f2aebabd8c5aee1f46108e3822d2e3
0
pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.wysiwyg.server.plugin.importer; import java.io.StringReader; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.xwiki.component.annotation.Requirement; import org.xwiki.component.manager.ComponentManager; import org.xwiki.gwt.wysiwyg.client.plugin.importer.ImportService; import org.xwiki.gwt.wysiwyg.client.wiki.Attachment; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.officeimporter.OfficeImporter; import org.xwiki.xml.html.HTMLCleaner; import org.xwiki.xml.html.HTMLCleanerConfiguration; import org.xwiki.xml.html.HTMLUtils; /** * XWiki specific implementation of {@link ImportService}. * * @version $Id$ */ public class XWikiImportService implements ImportService { /** * Default XWiki logger to report errors correctly. */ private static final Log LOG = LogFactory.getLog(XWikiImportService.class); /** * The component used to import office documents. */ @Requirement private OfficeImporter officeImporter; /** * The component used to serialize {@link org.xwiki.model.reference.DocumentReference} instances. This component is * needed only because OfficeImporter component uses String instead of * {@link org.xwiki.model.reference.DocumentReference}. */ @Requirement private EntityReferenceSerializer<String> entityReferenceSerializer; /** * The component manager. We need it because we have to access some components dynamically. */ @Requirement private ComponentManager componentManager; /** * {@inheritDoc} * * @see ImportService#cleanOfficeHTML(String, String, Map) */ public String cleanOfficeHTML(String htmlPaste, String cleanerHint, Map<String, String> cleaningParams) { try { HTMLCleaner cleaner = this.componentManager.lookup(HTMLCleaner.class, cleanerHint); HTMLCleanerConfiguration configuration = cleaner.getDefaultConfiguration(); configuration.setParameters(cleaningParams); Document cleanedDocument = cleaner.clean(new StringReader(htmlPaste), configuration); HTMLUtils.stripHTMLEnvelope(cleanedDocument); return HTMLUtils.toString(cleanedDocument, true, true); } catch (Exception e) { LOG.error("Exception while cleaning office HTML content.", e); throw new RuntimeException(e.getLocalizedMessage()); } } /** * {@inheritDoc} * * @see ImportService#officeToXHTML(Attachment, Map) */ public String officeToXHTML(Attachment attachment, Map<String, String> cleaningParams) { try { DocumentReference parent = new DocumentReference(attachment.getReference().getWikiName(), attachment.getReference().getSpaceName(), attachment.getReference().getPageName()); AttachmentReference attachmentReference = new AttachmentReference(attachment.getReference().getFileName(), parent); // Omit the XML declaration and the document type because the returned XHTML is inserted at the caret // position or replaces the current selection in the rich text area. cleaningParams.put("omitXMLDeclaration", Boolean.TRUE.toString()); cleaningParams.put("omitDocumentType", Boolean.TRUE.toString()); // OfficeImporter should be improved to use DocumentName instead of String. This will remove the need for a // DocumentNameSerializer. return officeImporter.importAttachment(this.entityReferenceSerializer.serialize(attachmentReference .getDocumentReference()), attachmentReference.getName(), cleaningParams); } catch (Exception e) { LOG.error("Exception while importing office document.", e); throw new RuntimeException(e.getLocalizedMessage()); } } }
xwiki-platform-web/xwiki-gwt-wysiwyg-server/src/main/java/com/xpn/xwiki/wysiwyg/server/plugin/importer/XWikiImportService.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.wysiwyg.server.plugin.importer; import java.io.StringReader; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.xwiki.component.annotation.Requirement; import org.xwiki.component.manager.ComponentManager; import org.xwiki.gwt.wysiwyg.client.plugin.importer.ImportService; import org.xwiki.gwt.wysiwyg.client.wiki.Attachment; import org.xwiki.model.reference.AttachmentReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReferenceSerializer; import org.xwiki.officeimporter.OfficeImporter; import org.xwiki.xml.html.HTMLCleaner; import org.xwiki.xml.html.HTMLCleanerConfiguration; import org.xwiki.xml.html.HTMLUtils; /** * XWiki specific implementation of {@link ImportService}. * * @version $Id$ */ public class XWikiImportService implements ImportService { /** * Default XWiki logger to report errors correctly. */ private static final Log LOG = LogFactory.getLog(XWikiImportService.class); /** * The component used to import office documents. */ @Requirement private OfficeImporter officeImporter; /** * The component used to serialize {@link org.xwiki.model.reference.DocumentReference} instances. This component is * needed only because OfficeImporter component uses String instead of * {@link org.xwiki.model.reference.DocumentReference}. */ @Requirement private EntityReferenceSerializer<String> entityReferenceSerializer; /** * The component manager. We need it because we have to access some components dynamically. */ @Requirement private ComponentManager componentManager; /** * {@inheritDoc} * * @see ImportService#cleanOfficeHTML(String, String, Map) */ public String cleanOfficeHTML(String htmlPaste, String cleanerHint, Map<String, String> cleaningParams) { try { HTMLCleaner cleaner = this.componentManager.lookup(HTMLCleaner.class, cleanerHint); HTMLCleanerConfiguration configuration = cleaner.getDefaultConfiguration(); configuration.setParameters(cleaningParams); Document cleanedDocument = cleaner.clean(new StringReader(htmlPaste), configuration); HTMLUtils.stripHTMLEnvelope(cleanedDocument); return HTMLUtils.toString(cleanedDocument, true, true); } catch (Exception e) { LOG.error("Exception while cleaning office HTML content.", e); throw new RuntimeException(e.getLocalizedMessage()); } } /** * {@inheritDoc} * * @see ImportService#officeToXHTML(Attachment, Map) */ public String officeToXHTML(Attachment attachment, Map<String, String> cleaningParams) { try { DocumentReference parent = new DocumentReference(attachment.getReference().getWikiName(), attachment.getReference().getSpaceName(), attachment.getReference().getPageName()); AttachmentReference attachmentReference = new AttachmentReference(attachment.getReference().getFileName(), parent); // OfficeImporter should be improved to use DocumentName instead of String. This will remove the need for a // DocumentNameSerializer. return officeImporter.importAttachment(this.entityReferenceSerializer.serialize(attachmentReference .getDocumentReference()), attachmentReference.getName(), cleaningParams); } catch (Exception e) { LOG.error("Exception while importing office document.", e); throw new RuntimeException(e.getLocalizedMessage()); } } }
XWIKI-5249: Omit XML declaration and document type when importing office file git-svn-id: 04343649e741710b2e0f622af6defd1ac33e5ca5@29318 f329d543-caf0-0310-9063-dda96c69346f
xwiki-platform-web/xwiki-gwt-wysiwyg-server/src/main/java/com/xpn/xwiki/wysiwyg/server/plugin/importer/XWikiImportService.java
XWIKI-5249: Omit XML declaration and document type when importing office file
<ide><path>wiki-platform-web/xwiki-gwt-wysiwyg-server/src/main/java/com/xpn/xwiki/wysiwyg/server/plugin/importer/XWikiImportService.java <ide> attachment.getReference().getSpaceName(), attachment.getReference().getPageName()); <ide> AttachmentReference attachmentReference = <ide> new AttachmentReference(attachment.getReference().getFileName(), parent); <add> // Omit the XML declaration and the document type because the returned XHTML is inserted at the caret <add> // position or replaces the current selection in the rich text area. <add> cleaningParams.put("omitXMLDeclaration", Boolean.TRUE.toString()); <add> cleaningParams.put("omitDocumentType", Boolean.TRUE.toString()); <ide> // OfficeImporter should be improved to use DocumentName instead of String. This will remove the need for a <ide> // DocumentNameSerializer. <ide> return officeImporter.importAttachment(this.entityReferenceSerializer.serialize(attachmentReference
JavaScript
apache-2.0
33c372227420154621ed4c187d5f9d479857b51a
0
WPO-Foundation/webpagetest-docs,WPO-Foundation/webpagetest-docs
const observer = new IntersectionObserver(entries => { const intersectingEntries = entries.filter(e => e.isIntersecting); for (const entry of intersectingEntries) { const previouslyActive = document.querySelector('.pageNav a.is-active'); if (previouslyActive) { previouslyActive.classList.remove('is-active'); } const id = entry.target.getAttribute('id') const newActive = document.querySelector(`.pageNav a[href="#${id}"]`); newActive.classList.add('is-active'); } }, { rootMargin: `0% 0% -90% 0%` } ); //track headings with an id if (document.querySelector('.pageNav')) { for (const heading of document.querySelectorAll(':is(h2,h3,h4)[id]')) { observer.observe(heading) } }
src/_includes/scripts/in-page-nav.js
const observer = new IntersectionObserver(entries => { const intersectingEntries = entries.filter(e => e.isIntersecting); for (const entry of intersectingEntries) { const previouslyActive = document.querySelector('.pageNav a.is-active'); if (previouslyActive) { previouslyActive.classList.remove('is-active'); } const id = entry.target.getAttribute('id') const newActive = document.querySelector(`.pageNav a[href="#${id}"]`); newActive.classList.add('is-active'); newActive.scrollIntoView({ block: 'nearest' }); } }, { rootMargin: `0% 0% -90% 0%` } ); //track headings with an id if (document.querySelector('.pageNav')) { for (const heading of document.querySelectorAll(':is(h2,h3,h4)[id]')) { observer.observe(heading) } }
Remove scrollIntoView() to fix scroll jank preventing users from scrolling
src/_includes/scripts/in-page-nav.js
Remove scrollIntoView() to fix scroll jank preventing users from scrolling
<ide><path>rc/_includes/scripts/in-page-nav.js <ide> const id = entry.target.getAttribute('id') <ide> const newActive = document.querySelector(`.pageNav a[href="#${id}"]`); <ide> newActive.classList.add('is-active'); <del> newActive.scrollIntoView({ block: 'nearest' }); <ide> } <ide> }, { rootMargin: `0% 0% -90% 0%` } <ide> );
JavaScript
mit
67131203dfdf7de188d7bf2f95b52da9c71ea104
0
petrickow/video-quality-project,petrickow/video-quality-project
app.controller('StreamController', [ 'Socket', function (Socket) { "use strict"; this.message = "No data received!"; this.latitude = "No data received!"; this.longitude = "No data received!"; this.speed = "No data received!"; this.accuracy = "No data received!"; this.altitude = "No data received!"; this.force = "No data received!"; this.azimuth = "No data received!"; this.pitch = "No data received!"; this.roll = "No data received!"; this.averageAzimuth = "No data received!"; this.averagePitch = "No data received!"; this.averageRoll = "No data received!"; this.ids = []; this.getStreams = function () { this.ids = Object.keys(Socket.stream); return this.ids; }; this.getLatitude = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.latitude = currentValue.latitude; } catch (e) { } return this.latitude; }; this.getLongitude = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.longitude = currentValue.longitude; } catch (e) { } return this.longitude; }; this.getSpeed = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.speed = currentValue.speed; } catch (e) { } return this.speed; }; this.getAccuracy = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.accuracy = currentValue.accuracy; } catch (e) { } return this.accuracy; }; this.getAltitude = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.altitude = currentValue.altitude; } catch (e) { } return this.accuracy; }; this.getForce = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Acceleration; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.force = currentValue.force; } catch (e) { } return this.force; }; this.getAzimuth = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.azimuth = currentValue.azimuth; } catch (e) { } return this.azimuth; }; this.getPitch = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.pitch = currentValue.pitch; } catch (e) { } return this.pitch; }; this.getRoll = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.roll = currentValue.roll; } catch (e) { } return this.roll; }; // TODO Calculate all Values at once to improve performance this.getAverageAzimuth = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; var sum = 0.0; for (var i = 0; i < parameter.data.length - 1; i++){ sum += parseFloat(parameter.data[i].azimuth); } this.averageAzimuth = sum / (parameter.data.length -1); } catch (e) { } return this.averageAzimuth; }; this.getAveragePitch = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; var sum = 0.0; for (var i = 0; i < parameter.data.length - 1; i++){ sum += parseFloat(parameter.data[i].pitch); } this.averagePitch = sum / (parameter.data.length -1); } catch (e) { } return this.averagePitch; }; this.getAverageRoll = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; var sum = 0.0; for(var i = 0; i < parameter.data.length - 1; i++){ sum += parseFloat(parameter.data[i].roll); } this.averageRoll = sum / (parameter.data.length -1); } catch (e) { } return this.averageRoll; }; }]);
src/main/resources/static/js/stream-controller.js
app.controller('StreamController', [ 'Socket', function (Socket) { "use strict"; this.message = "No data received!"; this.latitude = "No data received!"; this.longitude = "No data received!"; this.speed = "No data received!"; this.accuracy = "No data received!"; this.altitude = "No data received!"; this.force = "No data received!"; this.azimuth = "No data received!"; this.pitch = "No data received!"; this.roll = "No data received!"; this.averageAzimuth = "No data received!"; this.averagePitch = "No data received!"; this.averageRoll = "No data received!"; this.ids = []; this.getStreams = function () { this.ids = Object.keys(Socket.stream); return this.ids; }; this.getLatitude = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.latitude = currentValue.latitude; } catch (e) { } return this.latitude; }; this.getLongitude = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.longitude = currentValue.longitude; } catch (e) { } return this.longitude; }; this.getSpeed = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.speed = currentValue.speed; } catch (e) { } return this.speed; }; this.getAccuracy = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.accuracy = currentValue.accuracy; } catch (e) { } return this.accuracy; }; this.getAltitude = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Location; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.altitude = currentValue.altitude; } catch (e) { } return this.accuracy; }; this.getForce = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Acceleration; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.force = currentValue.force; } catch (e) { } return this.force; }; this.getAzimuth = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.azimuth = currentValue.azimuth; } catch (e) { } return this.azimuth; }; this.getPitch = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.pitch = currentValue.pitch; } catch (e) { } return this.pitch; }; this.getRoll = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; if (parameter.index != 0) var currentValue = parameter.data[parameter.index - 1]; else var currentValue = parameter.data[Socket.maxCachedItems - 1]; this.roll = currentValue.roll; } catch (e) { } return this.roll; }; // TODO Calculate all Values at once to improve performance this.getAverageAzimuth = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; var sum = 0.0; for (var i = 0; i < parameter.data.length - 1; i++){ sum += parseFloat(parameter.data[i].azimuth); } this.averageAzimuth = sum / parameter.data.length; } catch (e) { } return this.averageAzimuth; }; this.getAveragePitch = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; var sum = 0.0; for (var i = 0; i < parameter.data.length - 1; i++){ sum += parseFloat(parameter.data[i].pitch); } this.averagePitch = sum / parameter.data.length; } catch (e) { } return this.averagePitch; }; this.getAverageRoll = function (id) { try { var currentStream = Socket.stream[id]; var parameter = currentStream.Rotation; var sum = 0.0; for(var i = 0; i < parameter.data.length - 1; i++){ sum += parseFloat(parameter.data[i].roll); } this.averageRoll = sum / parameter.data.length; } catch (e) { } return this.averageRoll; }; }]);
fixed average values
src/main/resources/static/js/stream-controller.js
fixed average values
<ide><path>rc/main/resources/static/js/stream-controller.js <ide> for (var i = 0; i < parameter.data.length - 1; i++){ <ide> sum += parseFloat(parameter.data[i].azimuth); <ide> } <del> this.averageAzimuth = sum / parameter.data.length; <add> this.averageAzimuth = sum / (parameter.data.length -1); <ide> } catch (e) { <ide> } <ide> return this.averageAzimuth; <ide> for (var i = 0; i < parameter.data.length - 1; i++){ <ide> sum += parseFloat(parameter.data[i].pitch); <ide> } <del> this.averagePitch = sum / parameter.data.length; <add> this.averagePitch = sum / (parameter.data.length -1); <ide> } catch (e) { <ide> } <ide> return this.averagePitch; <ide> for(var i = 0; i < parameter.data.length - 1; i++){ <ide> sum += parseFloat(parameter.data[i].roll); <ide> } <del> this.averageRoll = sum / parameter.data.length; <add> this.averageRoll = sum / (parameter.data.length -1); <ide> } catch (e) { <ide> } <ide> return this.averageRoll;
Java
apache-2.0
45d2906671ed533dc523110f8b0b0dd3ce36dc09
0
mohanaraosv/commons-email,apache/commons-email,apache/commons-email,mohanaraosv/commons-email,apache/commons-email,mohanaraosv/commons-email
/* * 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.commons.mail.resolver; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.apache.commons.mail.DataSourceResolver; import javax.activation.DataSource; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; /** * JUnit test case for DataSourceUrlResolver. * * @since 1.3 */ public class DataSourceUrlResolverTest extends TestCase { private final int IMG_SIZE = 5866; public DataSourceUrlResolverTest(String name) { super(name); } /** * Shows how the DataSourceUrlResolver can resolve files as well but this should * be done using a DataSourceFileResolver. * * @throws Exception the test failed */ public void testResolvingFilesLenient() throws Exception { DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new File("./src/test").toURI().toURL(), true); assertTrue(toByteArray(dataSourceResolver.resolve("images/asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("./images/asf_logo_wide.gif")).length == IMG_SIZE); assertNull(dataSourceResolver.resolve("./images/does-not-exist.gif")); assertNull(dataSourceResolver.resolve("/images/asf_logo_wide.gif")); } /** * Tests resolving resources over HTTP. * * @throws Exception the test failed */ public void testResolvingHttpLenient() throws Exception { DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new URL("http://www.apache.org"), true); assertTrue(toByteArray(dataSourceResolver.resolve("http://www.apache.org/images/feather-small.gif")).length > 1); assertTrue(toByteArray(dataSourceResolver.resolve("images/feather-small.gif")).length > 1); assertTrue(toByteArray(dataSourceResolver.resolve("./images/feather-small.gif")).length > 1); assertTrue(toByteArray(dataSourceResolver.resolve("/images/feather-small.gif")).length > 1); assertNull(toByteArray(dataSourceResolver.resolve("/images/does-not-exist.gif"))); } /** * Tests resolving resources over HTTP. * * @throws Exception the test failed */ public void testResolvingHttpNonLenient() throws Exception { DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new URL("http://www.apache.org"), false); assertNotNull(dataSourceResolver.resolve("images/asf_logo_wide.gif")); try { dataSourceResolver.resolve("images/does-not-exist.gif"); fail("Expecting an IOException"); } catch(IOException e) { // expected return; } } private byte[] toByteArray(DataSource dataSource) throws IOException { if(dataSource != null) { InputStream is = dataSource.getInputStream(); return IOUtils.toByteArray(is); } else { return null; } } }
src/test/org/apache/commons/mail/resolver/DataSourceUrlResolverTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.mail.resolver; import junit.framework.TestCase; import org.apache.commons.io.IOUtils; import org.apache.commons.mail.DataSourceResolver; import javax.activation.DataSource; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; /** * JUnit test case for DateSourceResolver. * * @since 1.3 */ public class DataSourceUrlResolverTest extends TestCase { private final int IMG_SIZE = 5866; public DataSourceUrlResolverTest(String name) { super(name); } public void testResolvingFilesLenient() throws Exception { DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new File("./src/test").toURI().toURL(), true); assertTrue(toByteArray(dataSourceResolver.resolve("images/asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("/images/asf_logo_wide.gif")).length == IMG_SIZE); assertTrue(toByteArray(dataSourceResolver.resolve("./images/asf_logo_wide.gif")).length == IMG_SIZE); assertNull(dataSourceResolver.resolve("./images/does-not-exist.gif")); } public void testResolvingHttpLenient() throws Exception { DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new URL("http://www.apache.org"), true); assertTrue(toByteArray(dataSourceResolver.resolve("http://www.apache.org/images/feather-small.gif")).length > 1); assertTrue(toByteArray(dataSourceResolver.resolve("images/feather-small.gif")).length > 1); assertTrue(toByteArray(dataSourceResolver.resolve("./images/feather-small.gif")).length > 1); assertTrue(toByteArray(dataSourceResolver.resolve("/images/feather-small.gif")).length > 1); assertNull(toByteArray(dataSourceResolver.resolve("/images/does-not-exist.gif"))); } public void testResolvingClassPathNonLenient() throws Exception { DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new File("./src/test").toURI().toURL()); assertNotNull(dataSourceResolver.resolve("images/asf_logo_wide.gif")); try { dataSourceResolver.resolve("asf_logo_wide.gif"); fail("Expecting an IOException"); } catch(IOException e) { // expected return; } } public void testResolvingHttpNonLenient() throws Exception { DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new URL("http://www.apache.org"), false); assertNotNull(dataSourceResolver.resolve("images/asf_logo_wide.gif")); try { dataSourceResolver.resolve("images/does-not-exist.gif"); fail("Expecting an IOException"); } catch(IOException e) { // expected return; } } private byte[] toByteArray(DataSource dataSource) throws IOException { if(dataSource != null) { InputStream is = dataSource.getInputStream(); return IOUtils.toByteArray(is); } else { return null; } } }
[EMAIL-108] Cleaned up the test git-svn-id: 89dde08772e8bf23e1f06e036eef0c1fe886f791@1200561 13f79535-47bb-0310-9956-ffa450edef68
src/test/org/apache/commons/mail/resolver/DataSourceUrlResolverTest.java
[EMAIL-108] Cleaned up the test
<ide><path>rc/test/org/apache/commons/mail/resolver/DataSourceUrlResolverTest.java <ide> import java.net.URL; <ide> <ide> /** <del> * JUnit test case for DateSourceResolver. <add> * JUnit test case for DataSourceUrlResolver. <ide> * <ide> * @since 1.3 <ide> */ <ide> super(name); <ide> } <ide> <add> /** <add> * Shows how the DataSourceUrlResolver can resolve files as well but this should <add> * be done using a DataSourceFileResolver. <add> * <add> * @throws Exception the test failed <add> */ <ide> public void testResolvingFilesLenient() throws Exception <ide> { <ide> DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new File("./src/test").toURI().toURL(), true); <ide> assertTrue(toByteArray(dataSourceResolver.resolve("images/asf_logo_wide.gif")).length == IMG_SIZE); <del> assertTrue(toByteArray(dataSourceResolver.resolve("/images/asf_logo_wide.gif")).length == IMG_SIZE); <ide> assertTrue(toByteArray(dataSourceResolver.resolve("./images/asf_logo_wide.gif")).length == IMG_SIZE); <ide> assertNull(dataSourceResolver.resolve("./images/does-not-exist.gif")); <add> assertNull(dataSourceResolver.resolve("/images/asf_logo_wide.gif")); <ide> } <ide> <add> /** <add> * Tests resolving resources over HTTP. <add> * <add> * @throws Exception the test failed <add> */ <ide> public void testResolvingHttpLenient() throws Exception <ide> { <ide> DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new URL("http://www.apache.org"), true); <ide> assertNull(toByteArray(dataSourceResolver.resolve("/images/does-not-exist.gif"))); <ide> } <ide> <del> <del> public void testResolvingClassPathNonLenient() throws Exception <del> { <del> DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new File("./src/test").toURI().toURL()); <del> assertNotNull(dataSourceResolver.resolve("images/asf_logo_wide.gif")); <del> <del> try <del> { <del> dataSourceResolver.resolve("asf_logo_wide.gif"); <del> fail("Expecting an IOException"); <del> } <del> catch(IOException e) <del> { <del> // expected <del> return; <del> } <del> } <del> <add> /** <add> * Tests resolving resources over HTTP. <add> * <add> * @throws Exception the test failed <add> */ <ide> public void testResolvingHttpNonLenient() throws Exception <ide> { <ide> DataSourceResolver dataSourceResolver = new DataSourceUrlResolver(new URL("http://www.apache.org"), false);
JavaScript
mit
095dddcffed3f137054f07eddea46b76bead5727
0
developit/preact-cli,developit/preact-cli
const common = { 'polyfills.*.js': 4620, 'polyfills.*.js.map': 31760, 'favicon.ico': 15086, }; exports.default = exports.full = Object.assign({}, common, { 'assets/favicon.ico': 15086, 'assets/icons/android-chrome-192x192.png': 14058, 'assets/icons/android-chrome-512x512.png': 51484, 'assets/icons/apple-touch-icon.png': 12746, 'assets/icons/favicon-16x16.png': 626, 'assets/icons/favicon-32x32.png': 1487, 'assets/icons/mstile-150x150.png': 9050, 'push-manifest.json': 327, 'manifest.json': 426, 'sw.js': 3850, 'bundle.*.js': 19300, 'bundle.*.js.map': 105590, 'route-home.chunk.*.js': 1000, 'route-home.chunk.*.js.map': 4981, 'route-profile.chunk.*.js': 1650, 'route-profile.chunk.*.js.map': 8609, 'index.html': 850, 'style.*.css': 1065, 'style.*.css.map': 2345, 'ssr-build/ssr-bundle.js': 41715, 'ssr-build/ssr-bundle.js.map': 66661, 'ssr-build/style.*.css': 1065, 'ssr-build/style.*.css.map': 2345, }); exports.sass = ` <body> <div class="background__16qjh"> <h1>Header on background</h1> <p>Paragraph on background</p> </div> {{ ... }} </body> `; exports.prerender = {}; exports.prerender.heads = {}; exports.prerender.heads.home = ` <head> <meta charset="utf-8"> <title>Home<\\/title> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="manifest" href="\\/manifest\\.json"> <link rel="preload" href="\\/bundle\\.\\w{5}\\.js" as="script"> <link rel="preload" href="\\/route-home\\.chunk\\.\\w{5}\\.js" as="script"> <link rel="preload" href="\\/route-home\\.chunk\\.\\w{5}\\.css" as="style"> <link rel="shortcut icon" href="\\/favicon\\.ico"> <style>html{padding:0}</style> <link href=\\"/bundle.\\w{5}.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this.rel='stylesheet'\\"> <noscript> <link rel=\\"stylesheet\\" href=\\"/bundle.\\w{5}.css"> </noscript> </head> `; exports.prerender.heads.route66 = ` <head> <meta charset="utf-8"> <title>Route66<\\/title> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="manifest" href="\\/manifest\\.json"> <link rel="preload" href="\\/bundle\\.\\w{5}\\.js" as="script"> <link rel="preload" href="\\/route-route66\\.chunk\\.\\w{5}\\.js" as="script"> <link rel="preload" href="\\/route-route66\\.chunk\\.\\w{5}\\.css" as="style"> <link rel="shortcut icon" href="\\/favicon\\.ico"> <link href=\\"/bundle.\\w{5}.css\\" rel="stylesheet"> </head> `; exports.preload = {}; exports.preload.head = ` <head> <meta charset=\\"utf-8\\"> <title>preact-prerender<\\/title> <meta name=\\"viewport\\" content=\\"width=device-width,initial-scale=1\\"> <meta name=\\"mobile-web-app-capable\\" content=\\"yes\\"> <meta name=\\"apple-mobile-web-app-capable\\" content=\\"yes\\"> <link rel=\\"manifest\\" href=\\"\\/manifest\\.json\\"> <link rel=\\"preload\\" href=\\"\\/bundle\\.\\w{5}\\.js\\" as=\\"script\\"> <link rel=\\"preload\\" href=\\"\\/route-home\\.chunk\\.\\w{5}\\.js\\" as=\\"script\\"> <link rel=\\"preload\\" href=\\"\\/route-home\\~route-route66\\~route-route89\\.chunk\\.\\w{5}\\.js\\" as=\\"script\\"> <link rel=\\"preload\\" href=\\"\\/route-home\\.chunk\\.\\w{5}\\.css\\" as=\\"style\\"> <link rel=\\"shortcut icon\\" href=\\"\\/favicon\\.ico\\"> <style>html{padding:0}</style> <link href=\\"\\/bundle\\.\\w{5}\\.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this\\.rel='stylesheet'\\"> <noscript> <link rel=\\"stylesheet\\" href=\\"\\/bundle\\.\\w{5}\\.css\\"> </noscript> </head> `; exports.prerender.home = ` <body> <div id="app"> <div>Home</div> </div> {{ ... }} </body> `; exports.prerender.route = ` <body> <div id="app"> <div>Route66</div> </div> {{ ... }} </body> `; exports.webpack = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>preact-webpack</title> <link rel="shortcut icon" href="/favicon.ico"></link> </head> <body> <h1>Guess what</h1> <h2>This is an app with custom template</h2> {{ ... }} </body> </html> `;
packages/cli/tests/images/build.js
const common = { 'polyfills.*.js': 4620, 'polyfills.*.js.map': 31760, 'favicon.ico': 15086, }; exports.default = exports.full = Object.assign({}, common, { 'assets/favicon.ico': 15086, 'assets/icons/android-chrome-192x192.png': 14058, 'assets/icons/android-chrome-512x512.png': 51484, 'assets/icons/apple-touch-icon.png': 12746, 'assets/icons/favicon-16x16.png': 626, 'assets/icons/favicon-32x32.png': 1487, 'assets/icons/mstile-150x150.png': 9050, 'push-manifest.json': 327, 'manifest.json': 426, 'sw.js': 3850, 'bundle.*.js': 19300, 'bundle.*.js.map': 105590, 'route-home.chunk.*.js': 1000, 'route-home.chunk.*.js.map': 4981, 'route-profile.chunk.*.js': 1650, 'route-profile.chunk.*.js.map': 8609, 'index.html': 850, 'style.*.css': 1065, 'style.*.css.map': 2345, 'ssr-build/ssr-bundle.js': 41715, 'ssr-build/ssr-bundle.js.map': 66661, 'ssr-build/style.*.css': 1065, 'ssr-build/style.*.css.map': 2345, }); exports.sass = ` <body> <div class="background__21gOq"> <h1>Header on background</h1> <p>Paragraph on background</p> </div> {{ ... }} </body> `; exports.prerender = {}; exports.prerender.heads = {}; exports.prerender.heads.home = ` <head> <meta charset="utf-8"> <title>Home<\\/title> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="manifest" href="\\/manifest\\.json"> <link rel="preload" href="\\/bundle\\.\\w{5}\\.js" as="script"> <link rel="preload" href="\\/route-home\\.chunk\\.\\w{5}\\.js" as="script"> <link rel="preload" href="\\/route-home\\.chunk\\.\\w{5}\\.css" as="style"> <link rel="shortcut icon" href="\\/favicon\\.ico"> <link href=\\"/bundle.\\w{5}.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this.rel='stylesheet'\\"><noscript> <link rel=\\"stylesheet\\" href="\\/bundle.\\w{5}.css"><\\/noscript> <style>html{padding:0;}<\\/style> <\\/head> `; exports.prerender.heads.route66 = ` <head> <meta charset="utf-8"> <title>Route66<\\/title> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-capable" content="yes"> <link rel="manifest" href="\\/manifest\\.json"> <link rel="preload" href="\\/bundle\\.\\w{5}\\.js" as="script"> <link rel="preload" href="\\/route-route66\\.chunk\\.\\w{5}\\.js" as="script"> <link rel="preload" href="\\/route-route66\\.chunk\\.\\w{5}\\.css" as="style"> <link rel="shortcut icon" href="\\/favicon\\.ico"> <link href=\\"/bundle.\\w{5}.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this.rel='stylesheet'\\"><noscript> <link rel=\\"stylesheet\\" href=\\"\\/bundle.\\w{5}.css\\"><\\/noscript> <style>html{padding:0;}<\\/style> <\\/head> `; exports.preload = {}; exports.preload.head = ` <head> <meta charset=\\"utf-8\\"> <title>preact-prerender<\\/title> <meta name=\\"viewport\\" content=\\"width=device-width,initial-scale=1\\"> <meta name=\\"mobile-web-app-capable\\" content=\\"yes\\"> <meta name=\\"apple-mobile-web-app-capable\\" content=\\"yes\\"> <link rel=\\"manifest\\" href=\\"\\/manifest\\.json\\"> <link rel=\\"preload\\" href=\\"\\/bundle\\.\\w{5}\\.js\\" as=\\"script\\"> <link rel=\\"preload\\" href=\\"\\/route-home\\.chunk\\.\\w{5}\\.js\\" as=\\"script\\"> <link rel=\\"preload\\" href=\\"\\/route-home\\~route-route66\\~route-route89\\.chunk\\.\\w{5}\\.js\\" as=\\"script\\"> <link rel=\\"preload\\" href=\\"\\/route-home\\.chunk\\.\\w{5}\\.css\\" as=\\"style\\"> <link rel=\\"shortcut icon\\" href=\\"\\/favicon\\.ico\\"> <link href=\\"\\/bundle\\.\\w{5}\\.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this\\.rel='stylesheet'\\"> <noscript> <link rel=\\"stylesheet\\" href=\\"\\/bundle\\.\\w{5}\\.css\\"><\\/noscript> <style>html{padding:0;}<\\/style> </head> `; exports.prerender.home = ` <body> <div id="app"> <div>Home</div> </div> {{ ... }} </body> `; exports.prerender.route = ` <body> <div id="app"> <div>Route66</div> </div> {{ ... }} </body> `; exports.webpack = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>preact-webpack</title> <link rel="shortcut icon" href="/favicon.ico"></link> </head> <body> <h1>Guess what</h1> <h2>This is an app with custom template</h2> {{ ... }} </body> </html> `;
fix tests
packages/cli/tests/images/build.js
fix tests
<ide><path>ackages/cli/tests/images/build.js <ide> <ide> exports.sass = ` <ide> <body> <del> <div class="background__21gOq"> <add> <div class="background__16qjh"> <ide> <h1>Header on background</h1> <ide> <p>Paragraph on background</p> <ide> </div> <ide> <link rel="preload" href="\\/route-home\\.chunk\\.\\w{5}\\.js" as="script"> <ide> <link rel="preload" href="\\/route-home\\.chunk\\.\\w{5}\\.css" as="style"> <ide> <link rel="shortcut icon" href="\\/favicon\\.ico"> <del> <link href=\\"/bundle.\\w{5}.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this.rel='stylesheet'\\"><noscript> <del> <link rel=\\"stylesheet\\" href="\\/bundle.\\w{5}.css"><\\/noscript> <del> <style>html{padding:0;}<\\/style> <del><\\/head> <add> <style>html{padding:0}</style> <add> <link href=\\"/bundle.\\w{5}.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this.rel='stylesheet'\\"> <add> <noscript> <add> <link rel=\\"stylesheet\\" href=\\"/bundle.\\w{5}.css"> <add> </noscript> <add></head> <ide> `; <ide> <ide> exports.prerender.heads.route66 = ` <ide> <link rel="preload" href="\\/route-route66\\.chunk\\.\\w{5}\\.js" as="script"> <ide> <link rel="preload" href="\\/route-route66\\.chunk\\.\\w{5}\\.css" as="style"> <ide> <link rel="shortcut icon" href="\\/favicon\\.ico"> <del> <link href=\\"/bundle.\\w{5}.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this.rel='stylesheet'\\"><noscript> <del> <link rel=\\"stylesheet\\" href=\\"\\/bundle.\\w{5}.css\\"><\\/noscript> <del> <style>html{padding:0;}<\\/style> <del><\\/head> <add> <link href=\\"/bundle.\\w{5}.css\\" rel="stylesheet"> <add></head> <ide> `; <ide> <ide> exports.preload = {}; <ide> <link rel=\\"preload\\" href=\\"\\/route-home\\~route-route66\\~route-route89\\.chunk\\.\\w{5}\\.js\\" as=\\"script\\"> <ide> <link rel=\\"preload\\" href=\\"\\/route-home\\.chunk\\.\\w{5}\\.css\\" as=\\"style\\"> <ide> <link rel=\\"shortcut icon\\" href=\\"\\/favicon\\.ico\\"> <add> <style>html{padding:0}</style> <ide> <link href=\\"\\/bundle\\.\\w{5}\\.css\\" rel=\\"preload\\" as=\\"style\\" onload=\\"this\\.rel='stylesheet'\\"> <ide> <noscript> <del> <link rel=\\"stylesheet\\" href=\\"\\/bundle\\.\\w{5}\\.css\\"><\\/noscript> <del> <style>html{padding:0;}<\\/style> <add> <link rel=\\"stylesheet\\" href=\\"\\/bundle\\.\\w{5}\\.css\\"> <add> </noscript> <ide> </head> <ide> `; <ide>
Java
apache-2.0
689074d578ca803979efcb56695cb314b13424f8
0
cuba-platform/cuba,dimone-kun/cuba,dimone-kun/cuba,cuba-platform/cuba,dimone-kun/cuba,cuba-platform/cuba
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.haulmont.cuba.gui.data.impl; import com.google.common.collect.Iterables; import com.haulmont.bali.util.ParamsMap; import com.haulmont.bali.util.Preconditions; import com.haulmont.chile.core.model.*; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.core.global.filter.QueryFilter; import com.haulmont.cuba.gui.components.AggregationInfo; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.data.CollectionDatasourceListener; import com.haulmont.cuba.gui.data.Datasource; import com.haulmont.cuba.gui.data.DatasourceListener; import com.haulmont.cuba.gui.data.impl.compatibility.CompatibleDatasourceListenerWrapper; import com.haulmont.cuba.security.entity.EntityAttrAccess; import com.haulmont.cuba.security.entity.EntityOp; import com.haulmont.cuba.security.entity.PermissionType; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.ManyToMany; import java.util.*; import static com.haulmont.bali.util.Preconditions.checkNotNullArgument; public class CollectionPropertyDatasourceImpl<T extends Entity<K>, K> extends PropertyDatasourceImpl<T> implements CollectionDatasource<T, K>, CollectionDatasource.Indexed<T, K>, CollectionDatasource.Sortable<T, K>, CollectionDatasource.Aggregatable<T, K> { private static final Logger log = LoggerFactory.getLogger(CollectionPropertyDatasourceImpl.class); protected T item; protected boolean cascadeProperty; protected SortInfo<MetaPropertyPath>[] sortInfos; protected boolean listenersSuspended; protected Operation lastCollectionChangeOperation; protected List<T> lastCollectionChangeItems; protected boolean doNotModify; protected List<CollectionChangeListener<T, K>> collectionChangeListeners; protected AggregatableDelegate<K> aggregatableDelegate = new AggregatableDelegate<K>() { @Override public Object getItem(K itemId) { return CollectionPropertyDatasourceImpl.this.getItem(itemId); } @Override public Object getItemValue(MetaPropertyPath property, K itemId) { return CollectionPropertyDatasourceImpl.this.getItemValue(property, itemId); } }; @Override public void setup(String id, Datasource masterDs, String property) { super.setup(id, masterDs, property); cascadeProperty = metadata.getTools().isCascade(metaProperty); } @SuppressWarnings("unchecked") @Override protected void initParentDsListeners() { masterDs.addItemChangeListener(e -> { log.trace("itemChanged: prevItem={}, item={}", e.getPrevItem(), e.getItem()); Collection prevColl = e.getPrevItem() == null ? null : (Collection) e.getPrevItem().getValue(metaProperty.getName()); Collection coll = e.getItem() == null ? null : (Collection) e.getItem().getValue(metaProperty.getName()); reattachListeners(prevColl, coll); if (coll != null && metadata.getTools().isPersistent(metaProperty)) { for (Object collItem : coll) { if (PersistenceHelper.isNew(collItem)) { itemsToCreate.remove(collItem); itemsToCreate.add((T) collItem); modified = true; } } } if (item != null && (coll == null || !coll.contains(item))) { T prevItem = item; item = null; fireItemChanged(prevItem); } fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); }); masterDs.addStateChangeListener(e -> { fireStateChanged(e.getPrevState()); fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); }); masterDs.addItemPropertyChangeListener(e -> { if (e.getProperty().equals(metaProperty.getName()) && !ObjectUtils.equals(e.getPrevValue(), e.getValue())) { log.trace("master valueChanged: prop={}, prevValue={}, value={}", e.getProperty(), e.getPrevValue(), e.getValue()); reattachListeners((Collection) e.getPrevValue(), (Collection) e.getValue()); fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); } }); } protected void reattachListeners(Collection prevColl, Collection coll) { if (prevColl != null) for (Object entity : prevColl) { if (entity instanceof Instance) detachListener((Instance) entity); } if (coll != null) for (Object entity : coll) { if (entity instanceof Instance) attachListener((Instance) entity); } } @Override public T getItem(K id) { backgroundWorker.checkUIAccess(); Collection<T> collection = getCollection(); if (collection != null) { for (T t : collection) { if (t.getId().equals(id)) { return t; } } } return null; } @Override public T getItemNN(K id) { backgroundWorker.checkUIAccess(); T it = getItem(id); if (it != null) { return it; } else { throw new IllegalStateException("Item with id=" + id + " is not found in datasource " + this.id); } } @Override public Collection<K> getItemIds() { backgroundWorker.checkUIAccess(); if (masterDs.getState() == State.NOT_INITIALIZED) { return Collections.emptyList(); } else { Collection<T> items = getCollection(); if (items == null) return Collections.emptyList(); else { List<K> ids = new ArrayList<>(items.size()); for (T item : items) { ids.add(item.getId()); } return ids; } } } @Override public Collection<T> getItems() { backgroundWorker.checkUIAccess(); if (masterDs.getState() == State.NOT_INITIALIZED) { return Collections.emptyList(); } else { Collection<T> items = getCollection(); if (items == null) { return Collections.emptyList(); } if (items.isEmpty()) { return Collections.emptyList(); } return Collections.unmodifiableCollection(items); } } @Override public T getItem() { backgroundWorker.checkUIAccess(); return getState() == State.VALID ? item : null; } @Override public void setItem(T item) { backgroundWorker.checkUIAccess(); if (getState() == State.VALID) { Object prevItem = this.item; if (prevItem != item) { if (item != null) { final MetaClass aClass = item.getMetaClass(); MetaClass metaClass = getMetaClass(); if (!aClass.equals(metaClass) && !metaClass.getDescendants().contains(aClass)) { throw new DevelopmentException(String.format("Invalid item metaClass '%s'", aClass), ParamsMap.of("datasource", getId(), "metaClass", aClass)); } } this.item = item; //noinspection unchecked fireItemChanged((T) prevItem); } } } @Override public void refresh() { backgroundWorker.checkUIAccess(); fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); } @Override public int size() { backgroundWorker.checkUIAccess(); if (masterDs.getState() == State.NOT_INITIALIZED) { return 0; } else { final Collection<T> collection = getCollection(); return collection == null ? 0 : collection.size(); } } protected Collection<T> getCollection() { Security security = AppBeans.get(Security.NAME); MetaClass parentMetaClass = masterDs.getMetaClass(); MetaClass propertyMetaClass = metaProperty.getRange().asClass(); if (!security.isEntityOpPermitted(propertyMetaClass, EntityOp.READ) || !security.isEntityAttrPermitted(parentMetaClass, metaProperty.getName(), EntityAttrAccess.VIEW)) { return new ArrayList<>(); // Don't use Collections.emptyList() to avoid confusing UnsupportedOperationExceptions } else { final Instance master = masterDs.getItem(); //noinspection unchecked return master == null ? null : (Collection<T>) master.getValue(metaProperty.getName()); } } protected void checkState() { State state = getState(); if (state != State.VALID) { throw new IllegalStateException("Invalid datasource state: " + state); } } protected void checkPermission() { Security security = AppBeans.get(Security.NAME); MetaClass parentMetaClass = masterDs.getMetaClass(); if (!security.isEntityAttrPermitted(parentMetaClass, metaProperty.getName(), EntityAttrAccess.MODIFY)) { throw new AccessDeniedException(PermissionType.ENTITY_ATTR, parentMetaClass + "." + metaProperty.getName()); } } @Override public void addItem(T item) { checkNotNullArgument(item, "item is null"); internalAddItem(item, () -> { getCollection().add(item); }); } @SuppressWarnings("unchecked") @Override public void addItemFirst(T item) { checkNotNullArgument(item, "item is null"); internalAddItem(item, () -> { addToCollectionFirst(item); }); } @SuppressWarnings("unchecked") protected void internalAddItem(T item, Runnable addToCollection) { backgroundWorker.checkUIAccess(); checkState(); checkPermission(); if (getCollection() == null) { if (masterDs.getItem() == null) { // Last chance to find and set a master item MetaProperty inverseProp = metaProperty.getInverse(); if (inverseProp != null) { Entity probableMasterItem = item.getValue(inverseProp.getName()); if (probableMasterItem != null) { Collection<Entity> masterCollection = ((CollectionPropertyDatasourceImpl) masterDs).getCollection(); for (Entity masterCollectionItem : masterCollection) { if (masterCollectionItem.equals(probableMasterItem)) { masterDs.setItem(masterCollectionItem); break; } } } } if (masterDs.getItem() == null) { throw new IllegalStateException("Master datasource item is null"); } } else { initCollection(); } } // Don't add the same object instance twice (this is possible when committing nested datasources) if (!containsObjectInstance(item)) addToCollection.run(); attachListener(item); if (ObjectUtils.equals(this.item, item)) { this.item = item; } modified = true; if (cascadeProperty) { final Entity parentItem = masterDs.getItem(); ((DatasourceImplementation) masterDs).modified(parentItem); } if (metaProperty != null && metaProperty.getRange() != null && metaProperty.getRange().getCardinality() != null && metaProperty.getRange().getCardinality() == Range.Cardinality.MANY_TO_MANY && !PersistenceHelper.isNew(item)) { // do not mark for update existing many-to-many item; // item is not updated here, but many-to-many table entry is added } else { modified(item); } fireCollectionChanged(Operation.ADD, Collections.singletonList(item)); } @SuppressWarnings("unchecked") protected void addToCollectionFirst(T item) { Collection<T> collection = getCollection(); if (collection instanceof List) { ((List) collection).add(0, item); } else if (collection instanceof LinkedHashSet) { LinkedHashSet tmpSet = (LinkedHashSet) ((LinkedHashSet) collection).clone(); collection.clear(); ((LinkedHashSet) collection).add(item); ((LinkedHashSet) collection).addAll(tmpSet); } else { collection.add(item); } } /** * Search the collection using object identity. * @return true if the collection already contains the instance */ protected boolean containsObjectInstance(T instance) { Collection<T> collection = getCollection(); if (collection != null) { for (T item : collection) { if (instance == item) return true; } } return false; } protected void initCollection() { Instance item = masterDs.getItem(); if (item == null) throw new IllegalStateException("Item is null"); Class<?> type = metaProperty.getJavaType(); if (List.class.isAssignableFrom(type)) { item.setValue(metaProperty.getName(), new ArrayList()); } else if (Set.class.isAssignableFrom(type)) { item.setValue(metaProperty.getName(), new LinkedHashSet()); } else { throw new UnsupportedOperationException("Type " + type + " not supported, should implement List or Set"); } if (item.getValue(metaProperty.getName()) == null) { throw new RuntimeException("Cannot set collection property " + metaProperty.getName() + ". Probably not contained in view."); } } @Override public void removeItem(T item) { checkNotNullArgument(item, "item is null"); checkState(); checkPermission(); Collection<T> collection = getCollection(); if (collection != null) { if (this.item != null && this.item.equals(item)) { setItem(null); } collection.remove(item); detachListener(item); modified = true; if (cascadeProperty) { final Entity parentItem = masterDs.getItem(); //noinspection unchecked ((DatasourceImplementation) masterDs).modified(parentItem); } else { deleted(item); } fireCollectionChanged(Operation.REMOVE, Collections.singletonList(item)); } } @Override public void excludeItem(T item) { checkNotNullArgument(item, "item is null"); backgroundWorker.checkUIAccess(); checkState(); checkPermission(); Collection<T> collection = getCollection(); if (collection != null) { if (this.item != null && this.item.equals(item)) { setItem(null); } doNotModify = true; try { collection.remove(item); MetaProperty inverseProperty = metaProperty.getInverse(); if (inverseProperty != null) item.setValue(inverseProperty.getName(), null); // detach listener only after setting value to the link property detachListener(item); fireCollectionChanged(Operation.REMOVE, Collections.singletonList(item)); } finally { doNotModify = false; } } } @Override public void includeItem(T item) { checkNotNullArgument(item, "item is null"); internalIncludeItem(item, () -> { getCollection().add(item); }); } @Override public void includeItemFirst(T item) { checkNotNullArgument(item, "item is null"); internalIncludeItem(item, () -> { addToCollectionFirst(item); }); } protected void internalIncludeItem(T item, Runnable addToCollection) { backgroundWorker.checkUIAccess(); checkState(); checkPermission(); if (getCollection() == null) { initCollection(); } doNotModify = true; try { // Don't add the same object instance twice if (!containsObjectInstance(item)) addToCollection.run(); MetaProperty inverseProperty = metaProperty.getInverse(); if (inverseProperty != null) item.setValue(inverseProperty.getName(), masterDs.getItem()); // attach listener only after setting value to the link property attachListener(item); fireCollectionChanged(Operation.ADD, Collections.singletonList(item)); } finally { doNotModify = false; } } @Override public void clear() { backgroundWorker.checkUIAccess(); checkState(); Collection<T> collection = getCollection(); if (collection != null) { Collection<T> collectionItems = new ArrayList<>(collection); doNotModify = true; try { // Clear collection collection.clear(); // Notify listeners for (T item : collectionItems) { if (metaProperty.getRange().getCardinality() == Range.Cardinality.ONE_TO_MANY) { MetaProperty inverseProperty = metaProperty.getInverse(); if (inverseProperty == null) { throw new UnsupportedOperationException("No inverse property for " + metaProperty); } item.setValue(inverseProperty.getName(), null); } // detach listener only after setting value to the link property detachListener(item); } setItem(null); fireCollectionChanged(Operation.CLEAR, Collections.emptyList()); } finally { doNotModify = false; } } } @Override public void revert() { refresh(); } @Override public void modifyItem(T item) { checkNotNullArgument(item, "item is null"); Collection<T> collection = getCollection(); if (collection != null) { for (T t : collection) { if (t.equals(item)) { EntityCopyUtils.copyCompositionsBack(item, t); modified = true; if (cascadeProperty) { final Entity parentItem = masterDs.getItem(); //noinspection unchecked ((DatasourceImplementation) masterDs).modified(parentItem); } else { modified(t); } } } fireCollectionChanged(Operation.UPDATE, Collections.singletonList(item)); } } @Override public void updateItem(T item) { checkNotNullArgument(item, "item is null"); backgroundWorker.checkUIAccess(); Collection<T> collection = getCollection(); if (collection != null) { // this method must not change the "modified" state by contract boolean saveModified = modified; for (T t : collection) { if (t.equals(item)) { metadata.getTools().copy(item, t); } } modified = saveModified; fireCollectionChanged(Operation.UPDATE, Collections.singletonList(item)); } } @Override public void modified(T item) { checkNotNullArgument(item, "item is null"); if (doNotModify) return; // Never modify not new objects linked as ManyToMany. CollectionPropertyDatasource should only handle adding // and removing of ManyToMany items. if (!PersistenceHelper.isNew(item) && metaProperty.getAnnotatedElement().getAnnotation(ManyToMany.class) != null) return; super.modified(item); } @SuppressWarnings("unchecked") public void replaceItem(T item) { checkNotNullArgument(item, "item is null"); Collection<T> collection = getCollection(); if (collection != null) { for (T t : collection) { if (t.equals(item)) { detachListener(t); if (collection instanceof List) { List list = (List) collection; int itemIdx = list.indexOf(t); list.set(itemIdx, item); } else if (collection instanceof LinkedHashSet) { LinkedHashSet set = (LinkedHashSet) collection; List list = new ArrayList(set); int itemIdx = list.indexOf(t); list.set(itemIdx, item); set.clear(); set.addAll(list); } else { collection.remove(t); collection.add(item); } attachListener(item); if (item.equals(this.item)) { this.item = item; } break; } } if (sortInfos != null) doSort(); fireCollectionChanged(Operation.UPDATE, Collections.singletonList(item)); } } @Override public boolean containsItem(K itemId) { Collection<T> collection = getCollection(); if (collection == null) { return false; } for (T item : collection) { if (item.getId().equals(itemId)) { return true; } } return false; } @Override public String getQuery() { return null; } @Override public LoadContext getCompiledLoadContext() { return null; } @Override public QueryFilter getQueryFilter() { return null; } @Override public void setQuery(String query) { throw new UnsupportedOperationException(); } @Override public void setQuery(String query, QueryFilter filter) { throw new UnsupportedOperationException(); } @Override public void setQueryFilter(QueryFilter filter) { throw new UnsupportedOperationException(); } @Override public int getMaxResults() { return 0; } @Override public void setMaxResults(int maxResults) { } @Override public void refresh(Map<String, Object> parameters) { throw new UnsupportedOperationException(); } @Override public Map<String, Object> getLastRefreshParameters() { return Collections.emptyMap(); } @Override public boolean getRefreshOnComponentValueChange() { return false; } @Override public void setRefreshOnComponentValueChange(boolean refresh) { } @Override public void addCollectionChangeListener(CollectionChangeListener<T, K> listener) { Preconditions.checkNotNullArgument(listener, "listener cannot be null"); if (collectionChangeListeners == null) { collectionChangeListeners = new ArrayList<>(); } if (!collectionChangeListeners.contains(listener)) { collectionChangeListeners.add(listener); } } @Override public void removeCollectionChangeListener(CollectionChangeListener<T, K> listener) { if (collectionChangeListeners != null) { collectionChangeListeners.remove(listener); } } @Override public void addListener(DatasourceListener<T> listener) { super.addListener(listener); if (listener instanceof CollectionDatasourceListener) { addCollectionChangeListener(new CompatibleDatasourceListenerWrapper(listener)); } } @Override public void removeListener(DatasourceListener<T> listener) { super.removeListener(listener); if (listener instanceof CollectionDatasourceListener) { removeCollectionChangeListener(new CompatibleDatasourceListenerWrapper(listener)); } } @SuppressWarnings("unchecked") @Override public void committed(Set<Entity> entities) { if (!State.VALID.equals(masterDs.getState())) return; Collection<T> collection = getCollection(); if (collection != null) { for (T item : new ArrayList<>(collection)) { for (Entity entity : entities) { if (entity.equals(item)) { if (collection instanceof List) { List list = (List) collection; list.set(list.indexOf(item), entity); } else if (collection instanceof Set) { Set set = (Set) collection; set.remove(item); set.add(entity); } attachListener(entity); fireCollectionChanged(Operation.UPDATE, Collections.singletonList(item)); } } detachListener(item); // to avoid duplication in any case attachListener(item); } } for (Entity entity : entities) { if (entity.equals(item)) { item = (T) entity; } } modified = false; clearCommitLists(); } protected void fireCollectionChanged(Operation operation, List<T> items) { if (listenersSuspended) { lastCollectionChangeOperation = operation; lastCollectionChangeItems = items; return; } if (collectionChangeListeners != null && !collectionChangeListeners.isEmpty()) { CollectionChangeEvent<T, K> event = new CollectionChangeEvent<>(this, operation, items); for (CollectionChangeListener<T, K> listener : new ArrayList<>(collectionChangeListeners)) { listener.collectionChanged(event); } } } @Override public void suspendListeners() { listenersSuspended = true; } @Override public void resumeListeners() { listenersSuspended = false; if (lastCollectionChangeOperation != null) { fireCollectionChanged(lastCollectionChangeOperation, lastCollectionChangeItems != null ? lastCollectionChangeItems : Collections.emptyList()); } lastCollectionChangeOperation = null; lastCollectionChangeItems = null; } @Override public boolean isSoftDeletion() { return false; } @Override public void setSoftDeletion(boolean softDeletion) { } @Override public boolean isCacheable() { return false; } @Override public void setCacheable(boolean cacheable) { } //Implementation of CollectionDatasource.Sortable<T, K> interface @Override public void sort(SortInfo[] sortInfos) { if (sortInfos.length != 1) { throw new UnsupportedOperationException("Supporting sort by one field only"); } //noinspection unchecked this.sortInfos = sortInfos; doSort(); fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); } @Override public void resetSortOrder() { this.sortInfos = null; } protected void doSort() { Collection<T> collection = getCollection(); if (collection == null) return; List<T> list = new LinkedList<>(collection); list.sort(createEntityComparator()); collection.clear(); collection.addAll(list); } protected EntityComparator<T> createEntityComparator() { MetaPropertyPath propertyPath = sortInfos[0].getPropertyPath(); boolean asc = Order.ASC.equals(sortInfos[0].getOrder()); return new EntityComparator<>(propertyPath, asc); } @Override public int indexOfId(K itemId) { if (itemId == null) return -1; Collection<T> collection = getCollection(); if (CollectionUtils.isNotEmpty(collection)) { List<T> list = new ArrayList<>(collection); T currentItem = getItem(itemId); return list.indexOf(currentItem); } return -1; } @Override public K getIdByIndex(int index) { Collection<T> collection = getCollection(); if (CollectionUtils.isNotEmpty(collection)) { return Iterables.get(collection, index).getId(); } return null; } @Override public List<K> getItemIds(int startIndex, int numberOfItems) { return ((List<K>) getItemIds()).subList(startIndex, startIndex + numberOfItems); } @Override public K firstItemId() { Collection<T> collection = getCollection(); if (collection != null && !collection.isEmpty()) { T first = Iterables.getFirst(collection, null); return first == null ? null : first.getId(); } return null; } @Override public K lastItemId() { Collection<T> collection = getCollection(); if (collection != null && !collection.isEmpty()) { return Iterables.getLast(collection).getId(); } return null; } @Override public K nextItemId(K itemId) { if (itemId == null) return null; Collection<T> collection = getCollection(); if ((collection != null) && !collection.isEmpty() && !itemId.equals(lastItemId())) { List<T> list = new ArrayList<>(collection); T currentItem = getItem(itemId); return list.get(list.indexOf(currentItem) + 1).getId(); } return null; } @Override public K prevItemId(K itemId) { if (itemId == null) return null; Collection<T> collection = getCollection(); if ((collection != null) && !collection.isEmpty() && !itemId.equals(firstItemId())) { List<T> list = new ArrayList<>(collection); T currentItem = getItem(itemId); return list.get(list.indexOf(currentItem) - 1).getId(); } return null; } @Override public boolean isFirstId(K itemId) { return itemId != null && itemId.equals(firstItemId()); } @Override public boolean isLastId(K itemId) { return itemId != null && itemId.equals(lastItemId()); } @Override public Map<AggregationInfo, String> aggregate(AggregationInfo[] aggregationInfos, Collection<K> itemIds) { return aggregatableDelegate.aggregate(aggregationInfos, itemIds); } protected Object getItemValue(MetaPropertyPath property, K itemId) { Instance instance = getItemNN(itemId); if (property.getMetaProperties().length == 1) { return instance.getValue(property.getMetaProperty().getName()); } else { return instance.getValueEx(property.toString()); } } }
modules/gui/src/com/haulmont/cuba/gui/data/impl/CollectionPropertyDatasourceImpl.java
/* * Copyright (c) 2008-2016 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.haulmont.cuba.gui.data.impl; import com.google.common.collect.Iterables; import com.haulmont.bali.util.ParamsMap; import com.haulmont.bali.util.Preconditions; import com.haulmont.chile.core.model.*; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.core.global.filter.QueryFilter; import com.haulmont.cuba.gui.components.AggregationInfo; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.data.CollectionDatasourceListener; import com.haulmont.cuba.gui.data.Datasource; import com.haulmont.cuba.gui.data.DatasourceListener; import com.haulmont.cuba.gui.data.impl.compatibility.CompatibleDatasourceListenerWrapper; import com.haulmont.cuba.security.entity.EntityAttrAccess; import com.haulmont.cuba.security.entity.EntityOp; import com.haulmont.cuba.security.entity.PermissionType; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.ObjectUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.ManyToMany; import java.util.*; import static com.haulmont.bali.util.Preconditions.checkNotNullArgument; public class CollectionPropertyDatasourceImpl<T extends Entity<K>, K> extends PropertyDatasourceImpl<T> implements CollectionDatasource<T, K>, CollectionDatasource.Indexed<T, K>, CollectionDatasource.Sortable<T, K>, CollectionDatasource.Aggregatable<T, K> { private static final Logger log = LoggerFactory.getLogger(CollectionPropertyDatasourceImpl.class); protected T item; protected boolean cascadeProperty; protected SortInfo<MetaPropertyPath>[] sortInfos; protected boolean listenersSuspended; protected Operation lastCollectionChangeOperation; protected List<T> lastCollectionChangeItems; protected boolean doNotModify; protected List<CollectionChangeListener<T, K>> collectionChangeListeners; protected AggregatableDelegate<K> aggregatableDelegate = new AggregatableDelegate<K>() { @Override public Object getItem(K itemId) { return CollectionPropertyDatasourceImpl.this.getItem(itemId); } @Override public Object getItemValue(MetaPropertyPath property, K itemId) { return CollectionPropertyDatasourceImpl.this.getItemValue(property, itemId); } }; @Override public void setup(String id, Datasource masterDs, String property) { super.setup(id, masterDs, property); cascadeProperty = metadata.getTools().isCascade(metaProperty); } @SuppressWarnings("unchecked") @Override protected void initParentDsListeners() { masterDs.addItemChangeListener(e -> { log.trace("itemChanged: prevItem={}, item={}", e.getPrevItem(), e.getItem()); Collection prevColl = e.getPrevItem() == null ? null : (Collection) e.getPrevItem().getValue(metaProperty.getName()); Collection coll = e.getItem() == null ? null : (Collection) e.getItem().getValue(metaProperty.getName()); reattachListeners(prevColl, coll); if (coll != null && metadata.getTools().isPersistent(metaProperty)) { for (Object collItem : coll) { if (PersistenceHelper.isNew(collItem)) { itemsToCreate.remove(collItem); itemsToCreate.add((T) collItem); modified = true; } } } if (item != null) { T prevItem = item; item = null; fireItemChanged(prevItem); } fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); }); masterDs.addStateChangeListener(e -> { fireStateChanged(e.getPrevState()); fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); }); masterDs.addItemPropertyChangeListener(e -> { if (e.getProperty().equals(metaProperty.getName()) && !ObjectUtils.equals(e.getPrevValue(), e.getValue())) { log.trace("master valueChanged: prop={}, prevValue={}, value={}", e.getProperty(), e.getPrevValue(), e.getValue()); reattachListeners((Collection) e.getPrevValue(), (Collection) e.getValue()); fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); } }); } protected void reattachListeners(Collection prevColl, Collection coll) { if (prevColl != null) for (Object entity : prevColl) { if (entity instanceof Instance) detachListener((Instance) entity); } if (coll != null) for (Object entity : coll) { if (entity instanceof Instance) attachListener((Instance) entity); } } @Override public T getItem(K id) { backgroundWorker.checkUIAccess(); Collection<T> collection = getCollection(); if (collection != null) { for (T t : collection) { if (t.getId().equals(id)) { return t; } } } return null; } @Override public T getItemNN(K id) { backgroundWorker.checkUIAccess(); T it = getItem(id); if (it != null) { return it; } else { throw new IllegalStateException("Item with id=" + id + " is not found in datasource " + this.id); } } @Override public Collection<K> getItemIds() { backgroundWorker.checkUIAccess(); if (masterDs.getState() == State.NOT_INITIALIZED) { return Collections.emptyList(); } else { Collection<T> items = getCollection(); if (items == null) return Collections.emptyList(); else { List<K> ids = new ArrayList<>(items.size()); for (T item : items) { ids.add(item.getId()); } return ids; } } } @Override public Collection<T> getItems() { backgroundWorker.checkUIAccess(); if (masterDs.getState() == State.NOT_INITIALIZED) { return Collections.emptyList(); } else { Collection<T> items = getCollection(); if (items == null) { return Collections.emptyList(); } if (items.isEmpty()) { return Collections.emptyList(); } return Collections.unmodifiableCollection(items); } } @Override public T getItem() { backgroundWorker.checkUIAccess(); return getState() == State.VALID ? item : null; } @Override public void setItem(T item) { backgroundWorker.checkUIAccess(); if (getState() == State.VALID) { Object prevItem = this.item; if (prevItem != item) { if (item != null) { final MetaClass aClass = item.getMetaClass(); MetaClass metaClass = getMetaClass(); if (!aClass.equals(metaClass) && !metaClass.getDescendants().contains(aClass)) { throw new DevelopmentException(String.format("Invalid item metaClass '%s'", aClass), ParamsMap.of("datasource", getId(), "metaClass", aClass)); } } this.item = item; //noinspection unchecked fireItemChanged((T) prevItem); } } } @Override public void refresh() { backgroundWorker.checkUIAccess(); fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); } @Override public int size() { backgroundWorker.checkUIAccess(); if (masterDs.getState() == State.NOT_INITIALIZED) { return 0; } else { final Collection<T> collection = getCollection(); return collection == null ? 0 : collection.size(); } } protected Collection<T> getCollection() { Security security = AppBeans.get(Security.NAME); MetaClass parentMetaClass = masterDs.getMetaClass(); MetaClass propertyMetaClass = metaProperty.getRange().asClass(); if (!security.isEntityOpPermitted(propertyMetaClass, EntityOp.READ) || !security.isEntityAttrPermitted(parentMetaClass, metaProperty.getName(), EntityAttrAccess.VIEW)) { return new ArrayList<>(); // Don't use Collections.emptyList() to avoid confusing UnsupportedOperationExceptions } else { final Instance master = masterDs.getItem(); //noinspection unchecked return master == null ? null : (Collection<T>) master.getValue(metaProperty.getName()); } } protected void checkState() { State state = getState(); if (state != State.VALID) { throw new IllegalStateException("Invalid datasource state: " + state); } } protected void checkPermission() { Security security = AppBeans.get(Security.NAME); MetaClass parentMetaClass = masterDs.getMetaClass(); if (!security.isEntityAttrPermitted(parentMetaClass, metaProperty.getName(), EntityAttrAccess.MODIFY)) { throw new AccessDeniedException(PermissionType.ENTITY_ATTR, parentMetaClass + "." + metaProperty.getName()); } } @Override public void addItem(T item) { checkNotNullArgument(item, "item is null"); internalAddItem(item, () -> { getCollection().add(item); }); } @SuppressWarnings("unchecked") @Override public void addItemFirst(T item) { checkNotNullArgument(item, "item is null"); internalAddItem(item, () -> { addToCollectionFirst(item); }); } @SuppressWarnings("unchecked") protected void internalAddItem(T item, Runnable addToCollection) { backgroundWorker.checkUIAccess(); checkState(); checkPermission(); if (getCollection() == null) { if (masterDs.getItem() == null) { // Last chance to find and set a master item MetaProperty inverseProp = metaProperty.getInverse(); if (inverseProp != null) { Entity probableMasterItem = item.getValue(inverseProp.getName()); if (probableMasterItem != null) { Collection<Entity> masterCollection = ((CollectionPropertyDatasourceImpl) masterDs).getCollection(); for (Entity masterCollectionItem : masterCollection) { if (masterCollectionItem.equals(probableMasterItem)) { masterDs.setItem(masterCollectionItem); break; } } } } if (masterDs.getItem() == null) { throw new IllegalStateException("Master datasource item is null"); } } else { initCollection(); } } // Don't add the same object instance twice (this is possible when committing nested datasources) if (!containsObjectInstance(item)) addToCollection.run(); attachListener(item); if (ObjectUtils.equals(this.item, item)) { this.item = item; } modified = true; if (cascadeProperty) { final Entity parentItem = masterDs.getItem(); ((DatasourceImplementation) masterDs).modified(parentItem); } if (metaProperty != null && metaProperty.getRange() != null && metaProperty.getRange().getCardinality() != null && metaProperty.getRange().getCardinality() == Range.Cardinality.MANY_TO_MANY && !PersistenceHelper.isNew(item)) { // do not mark for update existing many-to-many item; // item is not updated here, but many-to-many table entry is added } else { modified(item); } fireCollectionChanged(Operation.ADD, Collections.singletonList(item)); } @SuppressWarnings("unchecked") protected void addToCollectionFirst(T item) { Collection<T> collection = getCollection(); if (collection instanceof List) { ((List) collection).add(0, item); } else if (collection instanceof LinkedHashSet) { LinkedHashSet tmpSet = (LinkedHashSet) ((LinkedHashSet) collection).clone(); collection.clear(); ((LinkedHashSet) collection).add(item); ((LinkedHashSet) collection).addAll(tmpSet); } else { collection.add(item); } } /** * Search the collection using object identity. * @return true if the collection already contains the instance */ protected boolean containsObjectInstance(T instance) { Collection<T> collection = getCollection(); if (collection != null) { for (T item : collection) { if (instance == item) return true; } } return false; } protected void initCollection() { Instance item = masterDs.getItem(); if (item == null) throw new IllegalStateException("Item is null"); Class<?> type = metaProperty.getJavaType(); if (List.class.isAssignableFrom(type)) { item.setValue(metaProperty.getName(), new ArrayList()); } else if (Set.class.isAssignableFrom(type)) { item.setValue(metaProperty.getName(), new LinkedHashSet()); } else { throw new UnsupportedOperationException("Type " + type + " not supported, should implement List or Set"); } if (item.getValue(metaProperty.getName()) == null) { throw new RuntimeException("Cannot set collection property " + metaProperty.getName() + ". Probably not contained in view."); } } @Override public void removeItem(T item) { checkNotNullArgument(item, "item is null"); checkState(); checkPermission(); Collection<T> collection = getCollection(); if (collection != null) { if (this.item != null && this.item.equals(item)) { setItem(null); } collection.remove(item); detachListener(item); modified = true; if (cascadeProperty) { final Entity parentItem = masterDs.getItem(); //noinspection unchecked ((DatasourceImplementation) masterDs).modified(parentItem); } else { deleted(item); } fireCollectionChanged(Operation.REMOVE, Collections.singletonList(item)); } } @Override public void excludeItem(T item) { checkNotNullArgument(item, "item is null"); backgroundWorker.checkUIAccess(); checkState(); checkPermission(); Collection<T> collection = getCollection(); if (collection != null) { if (this.item != null && this.item.equals(item)) { setItem(null); } doNotModify = true; try { collection.remove(item); MetaProperty inverseProperty = metaProperty.getInverse(); if (inverseProperty != null) item.setValue(inverseProperty.getName(), null); // detach listener only after setting value to the link property detachListener(item); fireCollectionChanged(Operation.REMOVE, Collections.singletonList(item)); } finally { doNotModify = false; } } } @Override public void includeItem(T item) { checkNotNullArgument(item, "item is null"); internalIncludeItem(item, () -> { getCollection().add(item); }); } @Override public void includeItemFirst(T item) { checkNotNullArgument(item, "item is null"); internalIncludeItem(item, () -> { addToCollectionFirst(item); }); } protected void internalIncludeItem(T item, Runnable addToCollection) { backgroundWorker.checkUIAccess(); checkState(); checkPermission(); if (getCollection() == null) { initCollection(); } doNotModify = true; try { // Don't add the same object instance twice if (!containsObjectInstance(item)) addToCollection.run(); MetaProperty inverseProperty = metaProperty.getInverse(); if (inverseProperty != null) item.setValue(inverseProperty.getName(), masterDs.getItem()); // attach listener only after setting value to the link property attachListener(item); fireCollectionChanged(Operation.ADD, Collections.singletonList(item)); } finally { doNotModify = false; } } @Override public void clear() { backgroundWorker.checkUIAccess(); checkState(); Collection<T> collection = getCollection(); if (collection != null) { Collection<T> collectionItems = new ArrayList<>(collection); doNotModify = true; try { // Clear collection collection.clear(); // Notify listeners for (T item : collectionItems) { if (metaProperty.getRange().getCardinality() == Range.Cardinality.ONE_TO_MANY) { MetaProperty inverseProperty = metaProperty.getInverse(); if (inverseProperty == null) { throw new UnsupportedOperationException("No inverse property for " + metaProperty); } item.setValue(inverseProperty.getName(), null); } // detach listener only after setting value to the link property detachListener(item); } setItem(null); fireCollectionChanged(Operation.CLEAR, Collections.emptyList()); } finally { doNotModify = false; } } } @Override public void revert() { refresh(); } @Override public void modifyItem(T item) { checkNotNullArgument(item, "item is null"); Collection<T> collection = getCollection(); if (collection != null) { for (T t : collection) { if (t.equals(item)) { EntityCopyUtils.copyCompositionsBack(item, t); modified = true; if (cascadeProperty) { final Entity parentItem = masterDs.getItem(); //noinspection unchecked ((DatasourceImplementation) masterDs).modified(parentItem); } else { modified(t); } } } fireCollectionChanged(Operation.UPDATE, Collections.singletonList(item)); } } @Override public void updateItem(T item) { checkNotNullArgument(item, "item is null"); backgroundWorker.checkUIAccess(); Collection<T> collection = getCollection(); if (collection != null) { // this method must not change the "modified" state by contract boolean saveModified = modified; for (T t : collection) { if (t.equals(item)) { metadata.getTools().copy(item, t); } } modified = saveModified; fireCollectionChanged(Operation.UPDATE, Collections.singletonList(item)); } } @Override public void modified(T item) { checkNotNullArgument(item, "item is null"); if (doNotModify) return; // Never modify not new objects linked as ManyToMany. CollectionPropertyDatasource should only handle adding // and removing of ManyToMany items. if (!PersistenceHelper.isNew(item) && metaProperty.getAnnotatedElement().getAnnotation(ManyToMany.class) != null) return; super.modified(item); } @SuppressWarnings("unchecked") public void replaceItem(T item) { checkNotNullArgument(item, "item is null"); Collection<T> collection = getCollection(); if (collection != null) { for (T t : collection) { if (t.equals(item)) { detachListener(t); if (collection instanceof List) { List list = (List) collection; int itemIdx = list.indexOf(t); list.set(itemIdx, item); } else if (collection instanceof LinkedHashSet) { LinkedHashSet set = (LinkedHashSet) collection; List list = new ArrayList(set); int itemIdx = list.indexOf(t); list.set(itemIdx, item); set.clear(); set.addAll(list); } else { collection.remove(t); collection.add(item); } attachListener(item); if (item.equals(this.item)) { this.item = item; } break; } } if (sortInfos != null) doSort(); fireCollectionChanged(Operation.UPDATE, Collections.singletonList(item)); } } @Override public boolean containsItem(K itemId) { Collection<T> collection = getCollection(); if (collection == null) { return false; } for (T item : collection) { if (item.getId().equals(itemId)) { return true; } } return false; } @Override public String getQuery() { return null; } @Override public LoadContext getCompiledLoadContext() { return null; } @Override public QueryFilter getQueryFilter() { return null; } @Override public void setQuery(String query) { throw new UnsupportedOperationException(); } @Override public void setQuery(String query, QueryFilter filter) { throw new UnsupportedOperationException(); } @Override public void setQueryFilter(QueryFilter filter) { throw new UnsupportedOperationException(); } @Override public int getMaxResults() { return 0; } @Override public void setMaxResults(int maxResults) { } @Override public void refresh(Map<String, Object> parameters) { throw new UnsupportedOperationException(); } @Override public Map<String, Object> getLastRefreshParameters() { return Collections.emptyMap(); } @Override public boolean getRefreshOnComponentValueChange() { return false; } @Override public void setRefreshOnComponentValueChange(boolean refresh) { } @Override public void addCollectionChangeListener(CollectionChangeListener<T, K> listener) { Preconditions.checkNotNullArgument(listener, "listener cannot be null"); if (collectionChangeListeners == null) { collectionChangeListeners = new ArrayList<>(); } if (!collectionChangeListeners.contains(listener)) { collectionChangeListeners.add(listener); } } @Override public void removeCollectionChangeListener(CollectionChangeListener<T, K> listener) { if (collectionChangeListeners != null) { collectionChangeListeners.remove(listener); } } @Override public void addListener(DatasourceListener<T> listener) { super.addListener(listener); if (listener instanceof CollectionDatasourceListener) { addCollectionChangeListener(new CompatibleDatasourceListenerWrapper(listener)); } } @Override public void removeListener(DatasourceListener<T> listener) { super.removeListener(listener); if (listener instanceof CollectionDatasourceListener) { removeCollectionChangeListener(new CompatibleDatasourceListenerWrapper(listener)); } } @SuppressWarnings("unchecked") @Override public void committed(Set<Entity> entities) { if (!State.VALID.equals(masterDs.getState())) return; Collection<T> collection = getCollection(); if (collection != null) { for (T item : new ArrayList<>(collection)) { for (Entity entity : entities) { if (entity.equals(item)) { if (collection instanceof List) { List list = (List) collection; list.set(list.indexOf(item), entity); } else if (collection instanceof Set) { Set set = (Set) collection; set.remove(item); set.add(entity); } attachListener(entity); fireCollectionChanged(Operation.UPDATE, Collections.singletonList(item)); } } detachListener(item); // to avoid duplication in any case attachListener(item); } } for (Entity entity : entities) { if (entity.equals(item)) { item = (T) entity; } } modified = false; clearCommitLists(); } protected void fireCollectionChanged(Operation operation, List<T> items) { if (listenersSuspended) { lastCollectionChangeOperation = operation; lastCollectionChangeItems = items; return; } if (collectionChangeListeners != null && !collectionChangeListeners.isEmpty()) { CollectionChangeEvent<T, K> event = new CollectionChangeEvent<>(this, operation, items); for (CollectionChangeListener<T, K> listener : new ArrayList<>(collectionChangeListeners)) { listener.collectionChanged(event); } } } @Override public void suspendListeners() { listenersSuspended = true; } @Override public void resumeListeners() { listenersSuspended = false; if (lastCollectionChangeOperation != null) { fireCollectionChanged(lastCollectionChangeOperation, lastCollectionChangeItems != null ? lastCollectionChangeItems : Collections.emptyList()); } lastCollectionChangeOperation = null; lastCollectionChangeItems = null; } @Override public boolean isSoftDeletion() { return false; } @Override public void setSoftDeletion(boolean softDeletion) { } @Override public boolean isCacheable() { return false; } @Override public void setCacheable(boolean cacheable) { } //Implementation of CollectionDatasource.Sortable<T, K> interface @Override public void sort(SortInfo[] sortInfos) { if (sortInfos.length != 1) { throw new UnsupportedOperationException("Supporting sort by one field only"); } //noinspection unchecked this.sortInfos = sortInfos; doSort(); fireCollectionChanged(Operation.REFRESH, Collections.emptyList()); } @Override public void resetSortOrder() { this.sortInfos = null; } protected void doSort() { Collection<T> collection = getCollection(); if (collection == null) return; List<T> list = new LinkedList<>(collection); list.sort(createEntityComparator()); collection.clear(); collection.addAll(list); } protected EntityComparator<T> createEntityComparator() { MetaPropertyPath propertyPath = sortInfos[0].getPropertyPath(); boolean asc = Order.ASC.equals(sortInfos[0].getOrder()); return new EntityComparator<>(propertyPath, asc); } @Override public int indexOfId(K itemId) { if (itemId == null) return -1; Collection<T> collection = getCollection(); if (CollectionUtils.isNotEmpty(collection)) { List<T> list = new ArrayList<>(collection); T currentItem = getItem(itemId); return list.indexOf(currentItem); } return -1; } @Override public K getIdByIndex(int index) { Collection<T> collection = getCollection(); if (CollectionUtils.isNotEmpty(collection)) { return Iterables.get(collection, index).getId(); } return null; } @Override public List<K> getItemIds(int startIndex, int numberOfItems) { return ((List<K>) getItemIds()).subList(startIndex, startIndex + numberOfItems); } @Override public K firstItemId() { Collection<T> collection = getCollection(); if (collection != null && !collection.isEmpty()) { T first = Iterables.getFirst(collection, null); return first == null ? null : first.getId(); } return null; } @Override public K lastItemId() { Collection<T> collection = getCollection(); if (collection != null && !collection.isEmpty()) { return Iterables.getLast(collection).getId(); } return null; } @Override public K nextItemId(K itemId) { if (itemId == null) return null; Collection<T> collection = getCollection(); if ((collection != null) && !collection.isEmpty() && !itemId.equals(lastItemId())) { List<T> list = new ArrayList<>(collection); T currentItem = getItem(itemId); return list.get(list.indexOf(currentItem) + 1).getId(); } return null; } @Override public K prevItemId(K itemId) { if (itemId == null) return null; Collection<T> collection = getCollection(); if ((collection != null) && !collection.isEmpty() && !itemId.equals(firstItemId())) { List<T> list = new ArrayList<>(collection); T currentItem = getItem(itemId); return list.get(list.indexOf(currentItem) - 1).getId(); } return null; } @Override public boolean isFirstId(K itemId) { return itemId != null && itemId.equals(firstItemId()); } @Override public boolean isLastId(K itemId) { return itemId != null && itemId.equals(lastItemId()); } @Override public Map<AggregationInfo, String> aggregate(AggregationInfo[] aggregationInfos, Collection<K> itemIds) { return aggregatableDelegate.aggregate(aggregationInfos, itemIds); } protected Object getItemValue(MetaPropertyPath property, K itemId) { Instance instance = getItemNN(itemId); if (property.getMetaProperties().length == 1) { return instance.getValue(property.getMetaProperty().getName()); } else { return instance.getValueEx(property.toString()); } } }
PL-9524 Selected item in nested datasource isn't cleared when master datasource is refreshed (clear only when the item does not exist in the collection anymore)
modules/gui/src/com/haulmont/cuba/gui/data/impl/CollectionPropertyDatasourceImpl.java
PL-9524 Selected item in nested datasource isn't cleared when master datasource is refreshed (clear only when the item does not exist in the collection anymore)
<ide><path>odules/gui/src/com/haulmont/cuba/gui/data/impl/CollectionPropertyDatasourceImpl.java <ide> } <ide> } <ide> <del> if (item != null) { <add> if (item != null && (coll == null || !coll.contains(item))) { <ide> T prevItem = item; <ide> item = null; <ide> fireItemChanged(prevItem);
Java
mit
7e73d33e41db7dad65a60e2da1b6edbb1d0262bd
0
Dbof/bitstring
/** * @author Dbof */ package com.davidebove.bitstring; /* * This file is part of com.davidebove.bitstring. * * The MIT License (MIT). * Permission is hereby granted, free of charge, to any * person obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the following * conditions: The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. THE SOFTWARE * IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * Copyright (c) 2015. * * @author Dbof <[email protected]> */ import java.util.ArrayList; import java.util.List; /** * A mutable bit string class with easy-to-use methods for creating, * manipulating and analysis of binary data. * * @author Dbof * */ public class BitString { private static String REGEX_PATTERN = "^(0|1)+$"; private String bits; /** * Copy constructor * * @param bitstring */ public BitString(final BitString bitstring) { bits = bitstring.bits; } /** * Constructs a new bit string from a byte array */ public BitString(final byte[] data) { bits = byteArrayToString(data); } /** * Constructs a new bit string from a string */ public BitString(final String data) { if (!data.matches(REGEX_PATTERN)) throw new IllegalArgumentException("String is not a bit string!"); bits = pad(data); } /** * Appends a new bit string from a byte array to the current bitstring * * @param data */ public void append(final byte[] data) { bits = bits.concat(byteArrayToString(data)); } /** * Appends a new bit string from a byte array to the current bitstring * * @param data */ public void append(final String data) { if (!data.matches(REGEX_PATTERN)) throw new IllegalArgumentException("String is not a bit string!"); bits = bits.concat(pad(data)); } /** * Returns the index within this bit string of the first occurrence of the * specified data. * * @param sequence * @return index */ public int find(final byte[] sequence) { return find(byteArrayToString(sequence)); } /** * Returns the index within this bit string of the first occurrence of the * specified data. * * @param bitstring * @return index */ public int find(final String bitstring) { return bits.indexOf(bitstring); } /** * Returns all occurrences of the specified bit string contained in the * current bit string. * * @param bitstring * the bitstring to find * @return a list of indices */ public List<Integer> findAll(final String bitstring) { ArrayList<Integer> result = new ArrayList<>(); int index = bits.indexOf(bitstring); while (index != -1) { result.add(index); index = bits.indexOf(bitstring, index + 1); } return result; } /** * Returns a string that is a substring of this string. The substring begins * at the specified beginIndex and extends to the character at index * endIndex - 1. Thus the length of the substring is endIndex-beginIndex. * * @param beginIndex * - the beginning index, inclusive. * @param endIndex * - the ending index, exclusive. * @return the specified substring. */ public BitString substring(final int beginIndex, final int endIndex) { return new BitString(bits.substring(beginIndex, endIndex)); } /** * Returns a bit string that is a substring of this bit string. The * substring begins with the character at the specified index and extends to * the end of this string. * * @param beginIndex * - the beginning index, inclusive. * @return the specified substring. */ public BitString substring(final int beginIndex) { return new BitString(bits.substring(beginIndex)); } /** * Returns the state of the bit at the specified index * * @param index * the index * @return true for 1 and false for 0 */ public boolean bitSet(final int index) { return bits.charAt(index) == '1'; } /** * Sets a bit to true (1). * * @param index * the index */ public void setBit(final int index) { this.setBit(index, true); } /** * Sets a bit to the specified value. * * @param index * the index * @param value * the value (0 or 1) to set the bit to */ public void setBit(final int index, final boolean value) { if (index < 0 || index >= bits.length()) throw new IndexOutOfBoundsException(); char[] tmp = bits.toCharArray(); tmp[index] = (value) ? '1' : '0'; bits = String.valueOf(tmp); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return bits; } /** * Returns a byte array representing this bit string. * * @return the bit string data as byte sequence */ public byte[] toByteArray() { byte[] result = new byte[bits.length() / 8]; int b_index = 0; // parse every 8 bits for (int i = 0; i < bits.length(); i += 8) { short b = (short) (Short.parseShort(bits.substring(i, i + 8), 2)); result[b_index++] = (byte) b; } return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj instanceof BitString) { BitString b = (BitString) obj; return (bits.equals(b.bits)); } return false; } /** * Converts a byte array to a (binary) string. * * @param data * the byte data to convert * @return the binary string */ private String byteArrayToString(final byte[] data) { StringBuilder builder = new StringBuilder(); StringBuilder inner = new StringBuilder(); for (int i = 0; i < data.length; i++) { inner.append(Integer.toBinaryString(data[i] & 0xFF)); // add padding while (inner.length() < 8) { inner.insert(0, '0'); } builder.append(inner.toString()); inner.setLength(0); } return builder.toString(); } /** * Adds padding to the string so it corresponds to a byte (8-bit) sequence. * * @param binary * bit sequence to add padding to * @return the string with padding */ private String pad(final String binary) { StringBuilder b = new StringBuilder(binary); while (b.length() % 8 != 0) b.insert(0, '0'); return b.toString(); } /** * Returns the length of this string. The length is equal to the number of * bits in the string * * @return the length of the sequence of bits represented by this object. */ public int length() { return bits.length(); } }
src/com/davidebove/bitstring/BitString.java
/** * @author Dbof */ package com.davidebove.bitstring; /* * This file is part of com.davidebove.bitstring. * * The MIT License (MIT). * Permission is hereby granted, free of charge, to any * person obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the following * conditions: The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. THE SOFTWARE * IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * Copyright (c) 2015. * * @author Dbof <[email protected]> */ import java.util.ArrayList; import java.util.List; /** * A mutable bit string class with easy-to-use methods for creating, * manipulating and analysis of binary data. * * @author Dbof * */ public class BitString { private static String REGEX_PATTERN = "^(0|1)+$"; private String bits; /** * Copy constructor * * @param bitstring */ public BitString(final BitString bitstring) { bits = bitstring.bits; } /** * Constructs a new bit string from a byte array */ public BitString(final byte[] data) { bits = byteArrayToString(data); } /** * Constructs a new bit string from a string */ public BitString(final String data) { if (!data.matches(REGEX_PATTERN)) throw new IllegalArgumentException("String is not a bit string!"); bits = pad(data); } /** * Appends a new bit string from a byte array to the current bitstring * * @param data */ public void append(final byte[] data) { bits = bits.concat(byteArrayToString(data)); } /** * Appends a new bit string from a byte array to the current bitstring * * @param data */ public void append(final String data) { if (!data.matches(REGEX_PATTERN)) throw new IllegalArgumentException("String is not a bit string!"); bits = bits.concat(pad(data)); } /** * Returns the index within this bit string of the first occurrence of the * specified data. * * @param sequence * @return index */ public int find(final byte[] sequence) { return find(byteArrayToString(sequence)); } /** * Returns the index within this bit string of the first occurrence of the * specified data. * * @param bitstring * @return index */ public int find(final String bitstring) { return bits.indexOf(bitstring); } public List<Integer> findAll(final String bitstring) { ArrayList<Integer> result = new ArrayList<>(); int index = bits.indexOf(bitstring); while (index != -1) { result.add(index); index = bits.indexOf(bitstring, index + 1); } return result; } /** * Returns a string that is a substring of this string. The substring begins * at the specified beginIndex and extends to the character at index * endIndex - 1. Thus the length of the substring is endIndex-beginIndex. * * @param beginIndex * - the beginning index, inclusive. * @param endIndex * - the ending index, exclusive. * @return the specified substring. */ public BitString substring(final int beginIndex, final int endIndex) { return new BitString(bits.substring(beginIndex, endIndex)); } /** * Returns a bit string that is a substring of this bit string. The substring begins * with the character at the specified index and extends to the end of this * string. * * @param beginIndex * - the beginning index, inclusive. * @return the specified substring. */ public BitString substring(final int beginIndex) { return new BitString(bits.substring(beginIndex)); } public boolean bitSet(final int index) { return bits.charAt(index) == '1'; } /** * Sets a bit to true (1) * * @param index */ public void setBit(final int index) { this.setBit(index, true); } /** * Sets a bit to the specified value * * @param index * @param value * is true (1) or false (0) */ public void setBit(final int index, final boolean value) { if (index < 0 || index >= bits.length()) throw new IndexOutOfBoundsException(); char[] tmp = bits.toCharArray(); tmp[index] = (value) ? '1' : '0'; bits = String.valueOf(tmp); } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return bits; } public byte[] toByteArray() { byte[] result = new byte[bits.length() / 8]; int b_index = 0; // parse every 8 bits for (int i = 0; i < bits.length(); i += 8) { short b = (short) (Short.parseShort(bits.substring(i, i + 8), 2)); result[b_index++] = (byte) b; } return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj instanceof BitString) { BitString b = (BitString) obj; return (bits.equals(b.bits)); } return false; } private String byteArrayToString(final byte[] data) { StringBuilder builder = new StringBuilder(); StringBuilder inner = new StringBuilder(); for (int i = 0; i < data.length; i++) { inner.append(Integer.toBinaryString(data[i] & 0xFF)); // add padding while (inner.length() < 8) { inner.insert(0, '0'); } builder.append(inner.toString()); inner.setLength(0); } return builder.toString(); } private String pad(final String binary) { StringBuilder b = new StringBuilder(binary); while (b.length() % 8 != 0) b.insert(0, '0'); return b.toString(); } /** * @return */ public int length() { return bits.length(); } }
Changed and added a few javadoc comments
src/com/davidebove/bitstring/BitString.java
Changed and added a few javadoc comments
<ide><path>rc/com/davidebove/bitstring/BitString.java <ide> return bits.indexOf(bitstring); <ide> } <ide> <add> /** <add> * Returns all occurrences of the specified bit string contained in the <add> * current bit string. <add> * <add> * @param bitstring <add> * the bitstring to find <add> * @return a list of indices <add> */ <ide> public List<Integer> findAll(final String bitstring) { <ide> ArrayList<Integer> result = new ArrayList<>(); <ide> int index = bits.indexOf(bitstring); <ide> } <ide> <ide> /** <del> * Returns a bit string that is a substring of this bit string. The substring begins <del> * with the character at the specified index and extends to the end of this <del> * string. <add> * Returns a bit string that is a substring of this bit string. The <add> * substring begins with the character at the specified index and extends to <add> * the end of this string. <ide> * <ide> * @param beginIndex <ide> * - the beginning index, inclusive. <ide> return new BitString(bits.substring(beginIndex)); <ide> } <ide> <add> /** <add> * Returns the state of the bit at the specified index <add> * <add> * @param index <add> * the index <add> * @return true for 1 and false for 0 <add> */ <ide> public boolean bitSet(final int index) { <ide> return bits.charAt(index) == '1'; <ide> } <ide> <ide> /** <del> * Sets a bit to true (1) <del> * <add> * Sets a bit to true (1). <add> * <ide> * @param index <add> * the index <ide> */ <ide> public void setBit(final int index) { <ide> this.setBit(index, true); <ide> } <ide> <ide> /** <del> * Sets a bit to the specified value <del> * <add> * Sets a bit to the specified value. <add> * <ide> * @param index <add> * the index <ide> * @param value <del> * is true (1) or false (0) <add> * the value (0 or 1) to set the bit to <ide> */ <ide> public void setBit(final int index, final boolean value) { <ide> if (index < 0 || index >= bits.length()) <ide> return bits; <ide> } <ide> <add> /** <add> * Returns a byte array representing this bit string. <add> * <add> * @return the bit string data as byte sequence <add> */ <ide> public byte[] toByteArray() { <ide> byte[] result = new byte[bits.length() / 8]; <ide> int b_index = 0; <ide> return false; <ide> } <ide> <add> /** <add> * Converts a byte array to a (binary) string. <add> * <add> * @param data <add> * the byte data to convert <add> * @return the binary string <add> */ <ide> private String byteArrayToString(final byte[] data) { <ide> StringBuilder builder = new StringBuilder(); <ide> StringBuilder inner = new StringBuilder(); <ide> return builder.toString(); <ide> } <ide> <add> /** <add> * Adds padding to the string so it corresponds to a byte (8-bit) sequence. <add> * <add> * @param binary <add> * bit sequence to add padding to <add> * @return the string with padding <add> */ <ide> private String pad(final String binary) { <ide> StringBuilder b = new StringBuilder(binary); <ide> while (b.length() % 8 != 0) <ide> } <ide> <ide> /** <del> * @return <add> * Returns the length of this string. The length is equal to the number of <add> * bits in the string <add> * <add> * @return the length of the sequence of bits represented by this object. <ide> */ <ide> public int length() { <ide> return bits.length();
Java
apache-2.0
bb15e4d9b3f473d108249716f399ed4a96eab53f
0
apache/httpcomponents-client,UlrichColby/httpcomponents-client,cmbntr/httpclient,cstamas/httpclient,cstamas/httpclient,atlassian/httpclient,cmbntr/httpclient,ok2c/httpclient,atlassian/httpclient
/* * $HeadURL$ * $Revision$ * $Date$ * * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.conn.ssl; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.HostNameResolver; import org.apache.http.conn.scheme.LayeredSocketFactory; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; /** * Layered socket factory for TLS/SSL connections, based on JSSE. *. * <p> * SSLSocketFactory can be used to validate the identity of the HTTPS * server against a list of trusted certificates and to authenticate to * the HTTPS server using a private key. * </p> * * <p> * SSLSocketFactory will enable server authentication when supplied with * a {@link KeyStore truststore} file containg one or several trusted * certificates. The client secure socket will reject the connection during * the SSL session handshake if the target HTTPS server attempts to * authenticate itself with a non-trusted certificate. * </p> * * <p> * Use JDK keytool utility to import a trusted certificate and generate a truststore file: * <pre> * keytool -import -alias "my server cert" -file server.crt -keystore my.truststore * </pre> * </p> * * <p> * SSLSocketFactory will enable client authentication when supplied with * a {@link KeyStore keystore} file containg a private key/public certificate * pair. The client secure socket will use the private key to authenticate * itself to the target HTTPS server during the SSL session handshake if * requested to do so by the server. * The target HTTPS server will in its turn verify the certificate presented * by the client in order to establish client's authenticity * </p> * * <p> * Use the following sequence of actions to generate a keystore file * </p> * <ul> * <li> * <p> * Use JDK keytool utility to generate a new key * <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre> * For simplicity use the same password for the key as that of the keystore * </p> * </li> * <li> * <p> * Issue a certificate signing request (CSR) * <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre> * </p> * </li> * <li> * <p> * Send the certificate request to the trusted Certificate Authority for signature. * One may choose to act as her own CA and sign the certificate request using a PKI * tool, such as OpenSSL. * </p> * </li> * <li> * <p> * Import the trusted CA root certificate * <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre> * </p> * </li> * <li> * <p> * Import the PKCS#7 file containg the complete certificate chain * <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre> * </p> * </li> * <li> * <p> * Verify the content the resultant keystore file * <pre>keytool -list -v -keystore my.keystore</pre> * </p> * </li> * </ul> * * @since 4.0 */ public class SSLSocketFactory implements LayeredSocketFactory { public static final String TLS = "TLS"; public static final String SSL = "SSL"; public static final String SSLV2 = "SSLv2"; public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = new AllowAllHostnameVerifier(); public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER = new BrowserCompatHostnameVerifier(); public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER = new StrictHostnameVerifier(); /** * The default factory using the default JVM settings for secure connections. */ private static final SSLSocketFactory DEFAULT_FACTORY = new SSLSocketFactory(); /** * Gets the default factory, which uses the default JVM settings for secure * connections. * * @return the default factory */ public static SSLSocketFactory getSocketFactory() { return DEFAULT_FACTORY; } private final SSLContext sslcontext; private final javax.net.ssl.SSLSocketFactory socketfactory; private final HostNameResolver nameResolver; private X509HostnameVerifier hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; public SSLSocketFactory( String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(); if (algorithm == null) { algorithm = TLS; } KeyManager[] keymanagers = null; if (keystore != null) { keymanagers = createKeyManagers(keystore, keystorePassword); } TrustManager[] trustmanagers = null; if (truststore != null) { trustmanagers = createTrustManagers(truststore); } this.sslcontext = SSLContext.getInstance(algorithm); this.sslcontext.init(keymanagers, trustmanagers, random); this.socketfactory = this.sslcontext.getSocketFactory(); this.nameResolver = nameResolver; } public SSLSocketFactory( final KeyStore keystore, final String keystorePassword, final KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, keystore, keystorePassword, truststore, null, null); } public SSLSocketFactory(final KeyStore keystore, final String keystorePassword) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, keystore, keystorePassword, null, null, null); } public SSLSocketFactory(final KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, null, null, truststore, null, null); } public SSLSocketFactory( final SSLContext sslContext, final HostNameResolver nameResolver) { this.sslcontext = sslContext; this.socketfactory = this.sslcontext.getSocketFactory(); this.nameResolver = nameResolver; } public SSLSocketFactory(final SSLContext sslContext) { this(sslContext, null); } /** * Creates the default SSL socket factory. * This constructor is used exclusively to instantiate the factory for * {@link #getSocketFactory getSocketFactory}. */ private SSLSocketFactory() { super(); this.sslcontext = null; this.socketfactory = HttpsURLConnection.getDefaultSSLSocketFactory(); this.nameResolver = null; } private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { if (keystore == null) { throw new IllegalArgumentException("Keystore may not be null"); } KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, password != null ? password.toCharArray(): null); return kmfactory.getKeyManagers(); } private static TrustManager[] createTrustManagers(final KeyStore keystore) throws KeyStoreException, NoSuchAlgorithmException { if (keystore == null) { throw new IllegalArgumentException("Keystore may not be null"); } TrustManagerFactory tmfactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(keystore); return tmfactory.getTrustManagers(); } // non-javadoc, see interface org.apache.http.conn.SocketFactory @SuppressWarnings("cast") public Socket createSocket() throws IOException { // the cast makes sure that the factory is working as expected return (SSLSocket) this.socketfactory.createSocket(); } // non-javadoc, see interface org.apache.http.conn.SocketFactory public Socket connectSocket( final Socket sock, final String host, final int port, final InetAddress localAddress, int localPort, final HttpParams params ) throws IOException { if (host == null) { throw new IllegalArgumentException("Target host may not be null."); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) localPort = 0; // indicates "any" InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress; if (this.nameResolver != null) { remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port); } else { remoteAddress = new InetSocketAddress(host, port); } try { sslsock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } sslsock.setSoTimeout(soTimeout); try { hostnameVerifier.verify(host, sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } return sslsock; } /** * Checks whether a socket connection is secure. * This factory creates TLS/SSL socket connections * which, by default, are considered secure. * <br/> * Derived classes may override this method to perform * runtime checks, for example based on the cypher suite. * * @param sock the connected socket * * @return <code>true</code> * * @throws IllegalArgumentException if the argument is invalid */ public boolean isSecure(Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null."); } // This instanceof check is in line with createSocket() above. if (!(sock instanceof SSLSocket)) { throw new IllegalArgumentException ("Socket not created by this factory."); } // This check is performed last since it calls the argument object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed."); } return true; } // isSecure // non-javadoc, see interface LayeredSocketFactory public Socket createSocket( final Socket socket, final String host, final int port, final boolean autoClose ) throws IOException, UnknownHostException { SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket( socket, host, port, autoClose ); hostnameVerifier.verify(host, sslSocket); // verifyHostName() didn't blowup - good! return sslSocket; } public void setHostnameVerifier(X509HostnameVerifier hostnameVerifier) { if ( hostnameVerifier == null ) { throw new IllegalArgumentException("Hostname verifier may not be null"); } this.hostnameVerifier = hostnameVerifier; } public X509HostnameVerifier getHostnameVerifier() { return hostnameVerifier; } }
httpclient/src/main/java/org/apache/http/conn/ssl/SSLSocketFactory.java
/* * $HeadURL$ * $Revision$ * $Date$ * * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.conn.ssl; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.HostNameResolver; import org.apache.http.conn.scheme.LayeredSocketFactory; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; /** * Layered socket factory for TLS/SSL connections, based on JSSE. *. * <p> * SSLSocketFactory can be used to validate the identity of the HTTPS * server against a list of trusted certificates and to authenticate to * the HTTPS server using a private key. * </p> * * <p> * SSLSocketFactory will enable server authentication when supplied with * a {@link KeyStore truststore} file containg one or several trusted * certificates. The client secure socket will reject the connection during * the SSL session handshake if the target HTTPS server attempts to * authenticate itself with a non-trusted certificate. * </p> * * <p> * Use JDK keytool utility to import a trusted certificate and generate a truststore file: * <pre> * keytool -import -alias "my server cert" -file server.crt -keystore my.truststore * </pre> * </p> * * <p> * SSLSocketFactory will enable client authentication when supplied with * a {@link KeyStore keystore} file containg a private key/public certificate * pair. The client secure socket will use the private key to authenticate * itself to the target HTTPS server during the SSL session handshake if * requested to do so by the server. * The target HTTPS server will in its turn verify the certificate presented * by the client in order to establish client's authenticity * </p> * * <p> * Use the following sequence of actions to generate a keystore file * </p> * <ul> * <li> * <p> * Use JDK keytool utility to generate a new key * <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre> * For simplicity use the same password for the key as that of the keystore * </p> * </li> * <li> * <p> * Issue a certificate signing request (CSR) * <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre> * </p> * </li> * <li> * <p> * Send the certificate request to the trusted Certificate Authority for signature. * One may choose to act as her own CA and sign the certificate request using a PKI * tool, such as OpenSSL. * </p> * </li> * <li> * <p> * Import the trusted CA root certificate * <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre> * </p> * </li> * <li> * <p> * Import the PKCS#7 file containg the complete certificate chain * <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre> * </p> * </li> * <li> * <p> * Verify the content the resultant keystore file * <pre>keytool -list -v -keystore my.keystore</pre> * </p> * </li> * </ul> * * @since 4.0 */ public class SSLSocketFactory implements LayeredSocketFactory { public static final String TLS = "TLS"; public static final String SSL = "SSL"; public static final String SSLV2 = "SSLv2"; public static final X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER = new AllowAllHostnameVerifier(); public static final X509HostnameVerifier BROWSER_COMPATIBLE_HOSTNAME_VERIFIER = new BrowserCompatHostnameVerifier(); public static final X509HostnameVerifier STRICT_HOSTNAME_VERIFIER = new StrictHostnameVerifier(); /** * The default factory using the default JVM settings for secure connections. */ private static final SSLSocketFactory DEFAULT_FACTORY = new SSLSocketFactory(); /** * Gets the default factory, which uses the default JVM settings for secure * connections. * * @return the default factory */ public static SSLSocketFactory getSocketFactory() { return DEFAULT_FACTORY; } private final SSLContext sslcontext; private final javax.net.ssl.SSLSocketFactory socketfactory; private final HostNameResolver nameResolver; private X509HostnameVerifier hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER; public SSLSocketFactory( String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(); if (algorithm == null) { algorithm = TLS; } KeyManager[] keymanagers = null; if (keystore != null) { keymanagers = createKeyManagers(keystore, keystorePassword); } TrustManager[] trustmanagers = null; if (truststore != null) { trustmanagers = createTrustManagers(truststore); } this.sslcontext = SSLContext.getInstance(algorithm); this.sslcontext.init(keymanagers, trustmanagers, random); this.socketfactory = this.sslcontext.getSocketFactory(); this.nameResolver = nameResolver; } public SSLSocketFactory( final KeyStore keystore, final String keystorePassword, final KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, keystore, keystorePassword, truststore, null, null); } public SSLSocketFactory(final KeyStore keystore, final String keystorePassword) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, keystore, keystorePassword, null, null, null); } public SSLSocketFactory(final KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { this(TLS, null, null, truststore, null, null); } public SSLSocketFactory( final SSLContext sslContext, final HostNameResolver nameResolver) { this.sslcontext = sslContext; this.socketfactory = this.sslcontext.getSocketFactory(); this.nameResolver = nameResolver; } public SSLSocketFactory(final SSLContext sslContext) { this(sslContext, null); } /** * Creates the default SSL socket factory. * This constructor is used exclusively to instantiate the factory for * {@link #getSocketFactory getSocketFactory}. */ private SSLSocketFactory() { super(); this.sslcontext = null; this.socketfactory = HttpsURLConnection.getDefaultSSLSocketFactory(); this.nameResolver = null; } private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { if (keystore == null) { throw new IllegalArgumentException("Keystore may not be null"); } KeyManagerFactory kmfactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, password != null ? password.toCharArray(): null); return kmfactory.getKeyManagers(); } private static TrustManager[] createTrustManagers(final KeyStore keystore) throws KeyStoreException, NoSuchAlgorithmException { if (keystore == null) { throw new IllegalArgumentException("Keystore may not be null"); } TrustManagerFactory tmfactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(keystore); return tmfactory.getTrustManagers(); } // non-javadoc, see interface org.apache.http.conn.SocketFactory @SuppressWarnings("cast") public Socket createSocket() throws IOException { // the cast makes sure that the factory is working as expected return (SSLSocket) this.socketfactory.createSocket(); } // non-javadoc, see interface org.apache.http.conn.SocketFactory public Socket connectSocket( final Socket sock, final String host, final int port, final InetAddress localAddress, int localPort, final HttpParams params ) throws IOException { if (host == null) { throw new IllegalArgumentException("Target host may not be null."); } if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) localPort = 0; // indicates "any" InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress; if (this.nameResolver != null) { remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port); } else { remoteAddress = new InetSocketAddress(host, port); } try { sock.connect(remoteAddress, connTimeout); } catch (SocketTimeoutException ex) { throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); } sslsock.setSoTimeout(soTimeout); try { hostnameVerifier.verify(host, sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } return sslsock; } /** * Checks whether a socket connection is secure. * This factory creates TLS/SSL socket connections * which, by default, are considered secure. * <br/> * Derived classes may override this method to perform * runtime checks, for example based on the cypher suite. * * @param sock the connected socket * * @return <code>true</code> * * @throws IllegalArgumentException if the argument is invalid */ public boolean isSecure(Socket sock) throws IllegalArgumentException { if (sock == null) { throw new IllegalArgumentException("Socket may not be null."); } // This instanceof check is in line with createSocket() above. if (!(sock instanceof SSLSocket)) { throw new IllegalArgumentException ("Socket not created by this factory."); } // This check is performed last since it calls the argument object. if (sock.isClosed()) { throw new IllegalArgumentException("Socket is closed."); } return true; } // isSecure // non-javadoc, see interface LayeredSocketFactory public Socket createSocket( final Socket socket, final String host, final int port, final boolean autoClose ) throws IOException, UnknownHostException { SSLSocket sslSocket = (SSLSocket) this.socketfactory.createSocket( socket, host, port, autoClose ); hostnameVerifier.verify(host, sslSocket); // verifyHostName() didn't blowup - good! return sslSocket; } public void setHostnameVerifier(X509HostnameVerifier hostnameVerifier) { if ( hostnameVerifier == null ) { throw new IllegalArgumentException("Hostname verifier may not be null"); } this.hostnameVerifier = hostnameVerifier; } public X509HostnameVerifier getHostnameVerifier() { return hostnameVerifier; } }
HTTPCLIENT-833: fixed possible NPE git-svn-id: 897293da6115b9493049ecf64199cf2f9a0ac287@754998 13f79535-47bb-0310-9956-ffa450edef68
httpclient/src/main/java/org/apache/http/conn/ssl/SSLSocketFactory.java
HTTPCLIENT-833: fixed possible NPE
<ide><path>ttpclient/src/main/java/org/apache/http/conn/ssl/SSLSocketFactory.java <ide> remoteAddress = new InetSocketAddress(host, port); <ide> } <ide> try { <del> sock.connect(remoteAddress, connTimeout); <add> sslsock.connect(remoteAddress, connTimeout); <ide> } catch (SocketTimeoutException ex) { <ide> throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out"); <ide> }
Java
mit
98617bf6b48be406f6fe1ae0e2149719f4a23022
0
ychaim/sparkbit,coinspark/sparkbit,coinspark/sparkbit,ychaim/sparkbit,ychaim/sparkbit,coinspark/sparkbit
/* * SparkBit * * Copyright 2014 Coin Sciences Ltd * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sparkbit.jsonrpc; import com.bitmechanic.barrister.RpcException; import org.multibit.controller.bitcoin.BitcoinController; import org.sparkbit.jsonrpc.autogen.*; import java.util.List; import java.util.ArrayList; import org.multibit.model.bitcoin.WalletData; import org.multibit.viewsystem.swing.MultiBitFrame; import org.multibit.model.core.StatusEnum; import org.multibit.network.ReplayManager; import com.google.bitcoin.core.*; //import java.util.HashMap; import java.util.Iterator; //import org.apache.commons.codec.digest.DigestUtils; import org.coinspark.protocol.CoinSparkAddress; import org.coinspark.protocol.CoinSparkAssetRef; import org.coinspark.wallet.CSAsset; import org.coinspark.wallet.CSAssetDatabase; import org.coinspark.wallet.CSEventBus; import org.coinspark.wallet.CSEventType; import org.multibit.utils.CSMiscUtils; import org.coinspark.protocol.CoinSparkAssetRef; import org.multibit.model.bitcoin.BitcoinModel; import org.multibit.model.bitcoin.WalletAddressBookData; import org.multibit.model.bitcoin.WalletInfoData; import com.google.bitcoin.crypto.KeyCrypter; import org.multibit.file.FileHandler; import java.io.*; import org.multibit.file.BackupManager; import com.google.bitcoin.crypto.KeyCrypterException; import com.google.bitcoin.script.Script; import com.google.bitcoin.wallet.DefaultCoinSelector; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.coinspark.protocol.CoinSparkGenesis; import org.joda.time.DateTime; import org.joda.time.LocalDateTime; import org.multibit.exchange.CurrencyConverter; import org.sparkbit.SBEvent; import org.sparkbit.SBEventType; import org.multibit.network.MultiBitService; import org.multibit.store.MultiBitWalletVersion; import java.util.Date; import org.multibit.file.WalletSaveException; import static org.multibit.model.bitcoin.WalletAssetComboBoxModel.NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD; import java.util.concurrent.ConcurrentHashMap; import org.coinspark.core.CSUtils; import java.text.SimpleDateFormat; import static org.multibit.network.MultiBitService.WALLET_SUFFIX; import static org.multibit.network.MultiBitService.getFilePrefix; import org.sparkbit.utils.FileNameCleaner; import org.apache.commons.io.FilenameUtils; import java.util.TimeZone; import org.multibit.viewsystem.swing.action.ExitAction; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import org.sparkbit.SparkBitMapDB; import org.apache.commons.io.FileDeleteStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.Arrays; import java.util.Set; import org.coinspark.wallet.CSBalance; import org.coinspark.wallet.CSTransactionOutput; import java.util.HashSet; /** * For now, synchronized access to commands which mutate */ public class SparkBitJSONRPCServiceImpl implements sparkbit { private static final Logger log = LoggerFactory.getLogger(SparkBitJSONRPCServiceImpl.class); // Limit on the number of addresses you can create in one call public static final int CREATE_ADDRESSES_LIMIT = 100; // How many milliseconds before we shutdown via ExitAction public static final int SHUTDOWN_DELAY = JettyEmbeddedServer.GRACEFUL_SHUTDOWN_PERIOD + 1000; private BitcoinController controller; // private MultiBitFrame mainFrame; // private ConcurrentHashMap<String,String> walletFilenameMap; private Timer stopTimer; public SparkBitJSONRPCServiceImpl() { this.controller = JSONRPCController.INSTANCE.getBitcoinController(); // this.mainFrame = JSONRPCController.INSTANCE.getMultiBitFrame(); // walletFilenameMap = new ConcurrentHashMap<>(); // updateWalletFilenameMap(); } // Quit after a delay so we can return true to JSON-RPC client. @Override public Boolean stop() throws com.bitmechanic.barrister.RpcException { log.info("STOP"); log.info("Shutting down JSON-RPC server, will wait " + SHUTDOWN_DELAY + " milliseconds before instructing SparkBit to exit."); final BitcoinController myController = this.controller; stopTimer = new Timer(); stopTimer.schedule(new TimerTask() { @Override public void run() { ExitAction exitAction = new ExitAction(myController, null); exitAction.setBitcoinController(myController); exitAction.actionPerformed(null); } }, SHUTDOWN_DELAY); // Signal the server to stop Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { JSONRPCController.INSTANCE.stopServer(); } }); return true; } /* Get status on a per wallet basis. */ @Override public JSONRPCStatusResponse getstatus() throws com.bitmechanic.barrister.RpcException { log.info("GET STATUS"); // boolean replayTaskRunning = ReplayManager.INSTANCE.getCurrentReplayTask()!=null ; // boolean regularDownloadRunning = ReplayManager.isRegularDownloadRunning(); // boolean synced = !regularDownloadRunning && !replayTaskRunning; // A regular download can be running in the background, because there is a new block, // and thus we are behind by one block, but the UI will still show that we synced. // We will consider ourselves to be out of sync if we are two or more blocks behind our peers. // PeerGroup pg = controller.getMultiBitService().getPeerGroup(); // if (pg!=null) { // Peer peer = pg.getDownloadPeer(); // if (peer != null) { // int n = peer.getPeerBlockHeightDifference(); // if (synced && n>=2) { // synced = false; // } // } // } int mostCommonChainHeight = controller.getMultiBitService().getPeerGroup().getMostCommonChainHeight(); //int bestChainHeight = controller.getMultiBitService().getChain().getBestChainHeight(); List<WalletData> perWalletModelDataList = controller.getModel().getPerWalletModelDataList(); List<JSONRPCWalletStatus> wallets = new ArrayList<JSONRPCWalletStatus>(); if (perWalletModelDataList != null) { for (WalletData wd : perWalletModelDataList) { Wallet w = wd.getWallet(); long lastSeenBlock = w.getLastBlockSeenHeight(); // getLastBlockSeenHeight() returns -1 if the wallet doesn't have this data yet if (lastSeenBlock==-1) lastSeenBlock = mostCommonChainHeight; boolean synced = (lastSeenBlock == mostCommonChainHeight); log.debug(">>>> *** description = " + wd.getWalletDescription()); log.debug(">>>> last block = " + lastSeenBlock); log.debug(">>>> mostCommonChainHeight = " + mostCommonChainHeight); log.debug(">>>> replay UUID = " + wd.getReplayTaskUUID()); log.debug(">>>> busy key = " + wd.getBusyTaskKey()); if (wd.getReplayTaskUUID() != null) { synced = false; } else if (wd.isBusy()) { String key = wd.getBusyTaskKey(); if (key.equals("multiBitDownloadListener.downloadingText") || key.equals("singleWalletPanel.waiting.text")) { synced = false; } } String filename = wd.getWalletFilename(); String base = FilenameUtils.getBaseName(filename); JSONRPCWalletStatus ws = new JSONRPCWalletStatus(base, synced, lastSeenBlock); wallets.add(ws); } } String versionNumber = controller.getLocaliser().getVersionNumber(); int numConnectedPeers = controller.getMultiBitService().getPeerGroup().numConnectedPeers(); boolean isTestNet = controller.getMultiBitService().isTestNet3(); JSONRPCStatusResponse resp = new JSONRPCStatusResponse(); resp.setVersion(versionNumber); resp.setConnections((long)numConnectedPeers); resp.setTestnet(isTestNet); JSONRPCWalletStatus[] x = wallets.toArray(new JSONRPCWalletStatus[0]); resp.setWallets( x ); return resp; } @Override public String[] listwallets() throws com.bitmechanic.barrister.RpcException { log.info("LIST WALLETS"); List<WalletData> perWalletModelDataList = controller.getModel().getPerWalletModelDataList(); List<String> names = new ArrayList<String>(); if (perWalletModelDataList != null) { for (WalletData loopPerWalletModelData : perWalletModelDataList) { String filename = loopPerWalletModelData.getWalletFilename(); String base = FilenameUtils.getBaseName(filename); names.add(base); // store/update local cache //walletFilenameMap.put(digest, filename); } } String[] resultArray = names.toArray(new String[0]); return resultArray; } @Override public synchronized Boolean createwallet(String name) throws com.bitmechanic.barrister.RpcException { log.info("CREATE WALLET"); log.info("wallet name = " + name); boolean isNameSane = sanityCheckName(name); if (!isNameSane) { JSONRPCError.WALLET_NAME_BAD_CHARS.raiseRpcException(); } if (name.startsWith(".") || name.endsWith(".")) { JSONRPCError.WALLET_NAME_PERIOD_START_END.raiseRpcException(); } String newWalletFilename = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory() + File.separator + name + MultiBitService.WALLET_SUFFIX; File newWalletFile = new File(newWalletFilename); if (newWalletFile.exists()) { JSONRPCError.WALLET_ID_ALREADY_EXISTS.raiseRpcException(); } LocalDateTime dt = new DateTime().toLocalDateTime(); String description = name + " (jsonrpc " + dt.toString("YYYY-MM-DD HH:mm" + ")"); //.SSS"); // Create a new wallet - protobuf.2 initially for backwards compatibility. try { Wallet newWallet = new Wallet(this.controller.getModel().getNetworkParameters()); ECKey newKey = new ECKey(); newWallet.addKey(newKey); WalletData perWalletModelData = new WalletData(); /* CoinSpark START */ // set default address label for first key WalletInfoData walletInfo = new WalletInfoData(newWalletFilename, newWallet, MultiBitWalletVersion.PROTOBUF); NetworkParameters networkParams = this.controller.getModel().getNetworkParameters(); Address defaultReceivingAddress = newKey.toAddress(networkParams); walletInfo.getReceivingAddresses().add(new WalletAddressBookData("Default Address", defaultReceivingAddress.toString())); perWalletModelData.setWalletInfo(walletInfo); /* CoinSpark END */ perWalletModelData.setWallet(newWallet); perWalletModelData.setWalletFilename(newWalletFilename); perWalletModelData.setWalletDescription(description); this.controller.getFileHandler().savePerWalletModelData(perWalletModelData, true); // Start using the new file as the wallet. this.controller.addWalletFromFilename(newWalletFile.getAbsolutePath()); // We could select the new wallet if we wanted to. //this.controller.getModel().setActiveWalletByFilename(newWalletFilename); //controller.getModel().setUserPreference(BitcoinModel.GRAB_FOCUS_FOR_ACTIVE_WALLET, "true"); // Save the user properties to disk. FileHandler.writeUserPreferences(this.controller); //log.debug("User preferences with new wallet written successfully"); // Backup the wallet and wallet info. BackupManager.INSTANCE.backupPerWalletModelData(controller.getFileHandler(), perWalletModelData); controller.fireRecreateAllViews(true); controller.fireDataChangedUpdateNow(); } catch (Exception e) { JSONRPCError.CREATE_WALLET_FAILED.raiseRpcException(); //JSONRPCError.throwAsRpcException("Could not create wallet", e); } // updateWalletFilenameMap(); return true; } @Override public synchronized Boolean deletewallet(String walletID) throws com.bitmechanic.barrister.RpcException { log.info("DELETE WALLET"); log.info("wallet name = " + walletID); Wallet w = getWalletForWalletName(walletID); if (w == null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } // Are there any asset or btc balances? Do not allow deleting wallet if any balance exists? Map<Integer, Wallet.CoinSpark.AssetBalance> map = w.CS.getAllAssetBalances(); for (Wallet.CoinSpark.AssetBalance ab : map.values()) { if (ab.total.compareTo(BigInteger.ZERO)>0) { JSONRPCError.DELETE_WALLET_NOT_EMPTY.raiseRpcException(); } } String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); WalletInfoData winfo = wd.getWalletInfo(); if (wd.isBusy()) { JSONRPCError.WALLEY_IS_BUSY.raiseRpcException(); } // Deleting a wallet even if not currently active, causes list of wallets to be unselected // so we need to keep track of what was active befor eremoval String activeFilename = this.controller.getModel().getActiveWalletFilename(); if (wd.getWalletFilename().equals(activeFilename)) { activeFilename = null; } // Unhook it from the PeerGroup. this.controller.getMultiBitService().getPeerGroup().removeWallet(w); // Remove it from the model. this.controller.getModel().remove(wd); // Perform delete if possible etc. FileHandler fileHandler = this.controller.getFileHandler(); try { fileHandler.deleteWalletAndWalletInfo(wd); // Delete .cs String csassets = filename + ".csassets"; String csbalances = filename + ".csbalances"; File f = new File(csassets); if (f.exists()) { if (!f.delete()) { //log.error(">>>> Asset DB: Cannot delete"); } } f = new File(csbalances); if (f.exists()) { if (!f.delete()) { //log.error(">>>> Balances DB: Cannot delete"); } } String cslog = filename + ".cslog"; f = new File(cslog); if (f.exists()) { if (!f.delete()) { // log.error(">>>> CS Log File: Cannot delete"); } } // Delete cached contracts String csfiles = filename + ".csfiles"; f = new File(csfiles); if (f.exists()) { FileDeleteStrategy.FORCE.delete(f); } // Delete the backup folder and cached contracts String backupFolderPath = BackupManager.INSTANCE.calculateTopLevelBackupDirectoryName(new File(filename)); f = new File(backupFolderPath); if (f.exists()) { FileDeleteStrategy.FORCE.delete(f); } } catch (Exception e) { JSONRPCError.throwAsRpcException("Error deleting wallet files", e); } if (!winfo.isDeleted()) { JSONRPCError.throwAsRpcException("Wallet was not deleted. Reason unknown."); } // Set the new Wallet to be the old active wallet, or the first wallet if (activeFilename!=null) { this.controller.getModel().setActiveWalletByFilename(activeFilename); } else if (!this.controller.getModel().getPerWalletModelDataList().isEmpty()) { WalletData firstPerWalletModelData = this.controller.getModel().getPerWalletModelDataList().get(0); this.controller.getModel().setActiveWalletByFilename(firstPerWalletModelData.getWalletFilename()); } controller.fireRecreateAllViews(true); // updateWalletFilenameMap(); return true; } /* Synchronized access: clear and recreate the wallet filename map. */ // private synchronized void updateWalletFilenameMap() { // walletFilenameMap.clear(); // List<WalletData> perWalletModelDataList = controller.getModel().getPerWalletModelDataList(); // if (perWalletModelDataList != null) { // for (WalletData loopPerWalletModelData : perWalletModelDataList) { // String filename = loopPerWalletModelData.getWalletFilename(); // String id = loopPerWalletModelData.getWalletDescription(); // walletFilenameMap. put(id, filename); //// //// String filename = loopPerWalletModelData.getWalletFilename(); //// String digest = DigestUtils.md5Hex(filename); //// walletFilenameMap. put(digest, filename); // } // } // // } /* Get full path for wallet given it's name */ private String getFullPathForWalletName(String name) { String filename = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory() + File.separator + name + WALLET_SUFFIX; return filename; } /* Check to see if a name gets cleaned or not because it contains characters bad for a filename */ private boolean sanityCheckName(String name) { String cleaned = FileNameCleaner.cleanFileName(name); return (cleaned.equals(name)); } private Wallet getWalletForWalletName(String walletID) { Wallet w = null; String filename = getFullPathForWalletName(walletID); if (filename != null) { WalletData wd = controller.getModel().getPerWalletModelDataByWalletFilename(filename); if (wd!=null) { w = wd.getWallet(); } } return w; } // Helper function private boolean isAssetRefValid(String s) { if (s!=null) { s = s.trim(); CoinSparkAssetRef assetRef = new CoinSparkAssetRef(); if (assetRef.decode(s)) { return true; } } return false; } private CSAsset getAssetForAssetRefString(Wallet w, String assetRef) { CSAssetDatabase db = w.CS.getAssetDB(); int[] assetIDs = w.CS.getAssetIDs(); if (assetIDs != null) { for (int id : assetIDs) { CSAsset asset = db.getAsset(id); if (asset != null) { //CoinSparkAssetRef ref = asset.getAssetReference(); String s = CSMiscUtils.getHumanReadableAssetRef(asset); if (s.equals(assetRef)) { return asset; } } } } return null; } @Override public synchronized Boolean setassetvisible(String walletID, String assetRef, Boolean visibility) throws com.bitmechanic.barrister.RpcException { log.info("SET ASSET VISIBILITY"); log.info("wallet name = " + walletID); log.info("asset ref = " + assetRef); log.info("visibility = " + visibility); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } CSAsset asset = getAssetForAssetRefString(w, assetRef); if (asset == null) { if (isAssetRefValid(assetRef)) { JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException(); } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } else { asset.setVisibility(visibility); CSEventBus.INSTANCE.postAsyncEvent(CSEventType.ASSET_VISIBILITY_CHANGED, asset.getAssetID()); } return true; } @Override public synchronized Boolean addasset(String walletID, String assetRefString) throws com.bitmechanic.barrister.RpcException { log.info("ADD ASSET"); log.info("wallet name = " + walletID); log.info("asset ref = " + assetRefString); Wallet w = getWalletForWalletName(walletID); if (w == null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } String s = assetRefString; if ((s != null) && (s.length() > 0)) { s = s.trim(); // Does the asset already exist? If so, return true. if (getAssetForAssetRefString(w, s) != null) { return true; } //System.out.println("asset ref detected! " + s); CoinSparkAssetRef assetRef = new CoinSparkAssetRef(); if (assetRef.decode(s)) { // Wallet wallet = this.controller.getModel().getActiveWallet(); CSAssetDatabase assetDB = w.CS.getAssetDB(); if (assetDB != null) { CSAsset asset = new CSAsset(assetRef, CSAsset.CSAssetSource.MANUAL); if (assetDB.insertAsset(asset) != null) { //System.out.println("Inserted new asset manually: " + asset); } else { JSONRPCError.throwAsRpcException("Internal error, assetDB.insertAsset() failed for an unknown reason"); } } } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } return true; } @Override public Boolean deleteasset(String walletname, String assetRef) throws com.bitmechanic.barrister.RpcException { log.info("DELETE ASSET"); log.info("wallet name = " + walletname); log.info("asset ref = " + assetRef); Wallet w = getWalletForWalletName(walletname); boolean success = false; CSAsset asset = getAssetForAssetRefString(w, assetRef); if (asset != null) { int assetID = asset.getAssetID(); BigInteger x = w.CS.getAssetBalance(assetID).total; boolean canDelete = x.equals(BigInteger.ZERO); // Delete invalid asset if property allows String s = controller.getModel().getUserPreference(BitcoinModel.CAN_DELETE_INVALID_ASSETS); boolean isAssetInvalid = asset.getAssetState() != CSAsset.CSAssetState.VALID; boolean deleteInvalidAsset = false; if (Boolean.TRUE.toString().equals(s) && isAssetInvalid) { deleteInvalidAsset = true; } if (canDelete || deleteInvalidAsset) { success = w.CS.deleteAsset(asset); if (success) { // Note: the event can be fired, but the listener can do nothing if in headless mode. // We want main asset panel to refresh, since there isn't an event fired on manual reset. CSEventBus.INSTANCE.postAsyncEvent(CSEventType.ASSET_DELETED, assetID); } else { JSONRPCError.DELETE_ASSET_FAILED.raiseRpcException(); } } else { if (isAssetInvalid) { JSONRPCError.DELETE_INVALID_ASSET_FAILED.raiseRpcException(); } else { JSONRPCError.DELETE_ASSET_NONZERO_BALANCE.raiseRpcException(); } } } else { if (isAssetRefValid(assetRef)) { JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException(); } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } return success; } @Override public synchronized Boolean refreshasset(String walletID, String assetRef) throws com.bitmechanic.barrister.RpcException { log.info("REFRESH ASSET"); log.info("wallet name = " + walletID); log.info("asset ref = " + assetRef); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } CSAsset asset = getAssetForAssetRefString(w, assetRef); if (asset != null) { asset.setRefreshState(); // Note: the event can be fired, but the listener can do nothing if in headless mode. // We want main asset panel to refresh, since there isn't an event fired on manual reset. CSEventBus.INSTANCE.postAsyncEvent(CSEventType.ASSET_UPDATED, asset.getAssetID()); } else { if (isAssetRefValid(assetRef)) { JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException(); } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } return true; } @Override public JSONRPCAddressBookEntry[] listaddresses(String walletID) throws com.bitmechanic.barrister.RpcException { log.info("LIST ADDRESSES"); log.info("wallet name = " + walletID); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } List<JSONRPCAddressBookEntry> addresses = new ArrayList<JSONRPCAddressBookEntry>(); String address, sparkAddress, label; String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); final WalletInfoData addressBook = wd.getWalletInfo(); if (addressBook != null) { ArrayList<WalletAddressBookData> receivingAddresses = addressBook.getReceivingAddresses(); if (receivingAddresses != null) { Iterator<WalletAddressBookData> iter = receivingAddresses.iterator(); while (iter.hasNext()) { WalletAddressBookData addressBookData = iter.next(); if (addressBookData != null) { address = addressBookData.getAddress(); label = addressBookData.getLabel(); sparkAddress = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(address); if (sparkAddress != null) { JSONRPCAddressBookEntry entry = new JSONRPCAddressBookEntry(label, address, sparkAddress); addresses.add(entry); } } } } } JSONRPCAddressBookEntry[] resultArray = addresses.toArray(new JSONRPCAddressBookEntry[0]); return resultArray; } // TODO: Should we remove limit of 100 addresses? @Override public synchronized JSONRPCAddressBookEntry[] createaddresses(String walletID, Long quantity) throws com.bitmechanic.barrister.RpcException { log.info("CREATE ADDRESSES"); log.info("wallet name = " + walletID); log.info("quantity = " + quantity); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } int qty = quantity.intValue(); if (qty <= 0) { JSONRPCError.CREATE_ADDRESS_TOO_FEW.raiseRpcException(); } if (qty > CREATE_ADDRESSES_LIMIT) { JSONRPCError.CREATE_ADDRESS_TOO_MANY.raiseRpcException(); } String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); if (wd.isBusy()) { JSONRPCError.WALLEY_IS_BUSY.raiseRpcException(); } else { wd.setBusy(true); wd.setBusyTaskKey("jsonrpc.busy.createaddress"); this.controller.fireWalletBusyChange(true); } List<JSONRPCAddressBookEntry> addresses = new ArrayList<JSONRPCAddressBookEntry>(); try { List<ECKey> newKeys = new ArrayList<ECKey>(); for (int i = 0; i < qty; i++) { ECKey newKey = new ECKey(); newKeys.add(newKey); } FileHandler fileHandler = this.controller.getFileHandler(); synchronized (wd.getWallet()) { wd.getWallet().addKeys(newKeys); } // Recalculate the bloom filter. if (this.controller.getMultiBitService() != null) { this.controller.getMultiBitService().recalculateFastCatchupAndFilter(); } // Add keys to address book. int n = 1, count = newKeys.size(); for (ECKey newKey : newKeys) { String lastAddressString = newKey.toAddress(this.controller.getModel().getNetworkParameters()).toString(); LocalDateTime dt = new DateTime().toLocalDateTime(); String label = "Created on " + dt.toString("d MMM y, HH:mm:ss z") + " (" + n++ + " of " + count + ")"; // unlikely address is already present, we don't want to update the label wd.getWalletInfo().addReceivingAddress(new WalletAddressBookData(label, lastAddressString), false); // Create structure for JSON response String sparkAddress = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(lastAddressString); if (sparkAddress == null) sparkAddress = "Internal error creating CoinSparkAddress from this Bitcoin address"; JSONRPCAddressBookEntry entry = new JSONRPCAddressBookEntry(label, lastAddressString, sparkAddress); addresses.add(entry); } // Backup the wallet and wallet info. BackupManager.INSTANCE.backupPerWalletModelData(fileHandler, wd); } catch (KeyCrypterException e) { JSONRPCError.throwAsRpcException("Create addresses failed with KeyCrypterException", e); } catch (Exception e) { JSONRPCError.throwAsRpcException("Create addresses failed", e); } finally { // Declare that wallet is no longer busy with the task. wd.setBusyTaskKey(null); wd.setBusy(false); this.controller.fireWalletBusyChange(false); } CSEventBus.INSTANCE.postAsync(new SBEvent(SBEventType.ADDRESS_CREATED)); wd.setDirty(true); JSONRPCAddressBookEntry[] resultArray = addresses.toArray(new JSONRPCAddressBookEntry[0]); return resultArray; } @Override public synchronized Boolean setaddresslabel(String walletID, String address, String label) throws com.bitmechanic.barrister.RpcException { log.info("SET ADDRESS LABEL"); log.info("wallet name = " + walletID); log.info("address = " + address); log.info("label = " + label); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } if (address.startsWith("s")) { address = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address); if (address==null) { JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(); } } if (label==null) label=""; // this shouldn't happen when invoked via barrister boolean success = false; String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); final WalletInfoData addressBook = wd.getWalletInfo(); if (addressBook != null) { ArrayList<WalletAddressBookData> receivingAddresses = addressBook.getReceivingAddresses(); if (receivingAddresses != null) { Iterator<WalletAddressBookData> iter = receivingAddresses.iterator(); while (iter.hasNext()) { WalletAddressBookData addressBookData = iter.next(); if (addressBookData != null) { String btcAddress = addressBookData.getAddress(); if (btcAddress.equals(address)) { addressBookData.setLabel(label); success = true; break; } } } } } if (success) { CSEventBus.INSTANCE.postAsync(new SBEvent(SBEventType.ADDRESS_UPDATED)); wd.setDirty(true); } else { JSONRPCError.ADDRESS_NOT_FOUND.raiseRpcException(); } return success; } @Override public JSONRPCTransaction[] listtransactions(String walletID, Long limit) throws com.bitmechanic.barrister.RpcException { log.info("LIST TRANSACTIONS"); log.info("wallet name = " + walletID); log.info("limit # = " + limit); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } // if (limit>100) { // JSONRPCError.LIST_TRANSACTIONS_TOO_MANY.raiseRpcException(); // } else if (limit<0) { JSONRPCError.LIST_TRANSACTIONS_TOO_FEW.raiseRpcException(); } // if limit is 0 get them all List<JSONRPCTransaction> resultList = new ArrayList<JSONRPCTransaction>(); int lastSeenBlock = controller.getMultiBitService().getChain().getBestChainHeight(); List<Transaction> transactions = null; if (limit > 0) { transactions = w.getRecentTransactions(limit.intValue(), false); } else { transactions = w.getTransactionsByTime(); } for (Transaction tx : transactions) { Date txDate = controller.getModel().getDateOfTransaction(controller, tx); long unixtime = txDate.getTime()/1000L; // unix epoch in seconds long confirmations = 0; try { confirmations = lastSeenBlock - tx.getConfidence().getAppearedAtChainHeight(); } catch (IllegalStateException e) { } boolean incoming = !tx.sent(w); BigInteger feeSatoshis = tx.calculateFee(w); Double fee = null; if (!incoming) { BigDecimal feeBTC = new BigDecimal(feeSatoshis).divide(new BigDecimal(Utils.COIN)); fee = -1.0 * feeBTC.doubleValue(); } String txid = tx.getHashAsString(); ArrayList<JSONRPCTransactionAmount> amounts = getAssetTransactionAmounts(w, tx, true, false); JSONRPCTransactionAmount[] amountsArray = amounts.toArray(new JSONRPCTransactionAmount[0]); // int size = amounts.size(); // AssetTransactionAmountEntry[] entries = new AssetTransactionAmountEntry[size]; // int index = 0; // for (JSONRPCTransactionAmount ata : amounts) { // entries[index++] = new AssetTransactionAmountEntry(ata.getAssetRef(), ata); // } /* Get send and receive address */ TransactionOutput myOutput = null; TransactionOutput theirOutput = null; List<TransactionOutput> transactionOutputs = tx.getOutputs(); if (transactionOutputs != null) { for (TransactionOutput transactionOutput : transactionOutputs) { if (transactionOutput != null && transactionOutput.isMine(w)) { myOutput = transactionOutput; } if (transactionOutput != null && !transactionOutput.isMine(w)) { // We have to skip the OP_RETURN output as there is no address and it result sin an exception when trying to get the destination address Script script = transactionOutput.getScriptPubKey(); if (script != null) { if (script.isSentToAddress() || script.isSentToP2SH()) { theirOutput = transactionOutput; } } } } } boolean hasAssets = amounts.size()>1; String myReceiveAddress = null; String theirAddress = null; if (incoming) { try { if (myOutput != null) { Address toAddress = new Address(this.controller.getModel().getNetworkParameters(), myOutput.getScriptPubKey().getPubKeyHash()); myReceiveAddress = toAddress.toString(); } if (myReceiveAddress != null && hasAssets) { String s = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(myReceiveAddress); if (s != null) { myReceiveAddress = s; } } } catch (ScriptException e) { } } else { // outgoing transaction if (theirOutput != null) { // First let's see if we have stored the recipient in our map try { Map<String,String> m = SparkBitMapDB.INSTANCE.getSendTransactionToCoinSparkAddressMap(); if (m != null) { theirAddress = m.get(tx.getHashAsString()); } } catch (Exception e) { } if (theirAddress == null) { try { theirAddress = theirOutput.getScriptPubKey().getToAddress(controller.getModel().getNetworkParameters()).toString(); } catch (ScriptException se) { } if (theirAddress != null & hasAssets) { String s = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(theirAddress); if (s != null) { theirAddress = s; } } } } } String address = ""; if (incoming && myReceiveAddress!=null) { address = myReceiveAddress; } else if (!incoming && theirAddress != null) { address = theirAddress; } String category = (incoming) ? "receive" : "send"; JSONRPCTransaction atx = new JSONRPCTransaction(unixtime, confirmations, category, amountsArray, fee, txid, address); resultList.add(atx); } JSONRPCTransaction[] resultArray = resultList.toArray(new JSONRPCTransaction[0]); return resultArray; } /* * Return array of asset transaction objects. * Original method is in CSMiscUtils, so any changes there, must be reflected here. */ private ArrayList<JSONRPCTransactionAmount> getAssetTransactionAmounts(Wallet wallet, Transaction tx, boolean excludeBTCFee, boolean absoluteBTCFee) { if (wallet==null || tx==null) return null; Map<Integer, BigInteger> receiveMap = wallet.CS.getAssetsSentToMe(tx); Map<Integer, BigInteger> sendMap = wallet.CS.getAssetsSentFromMe(tx); // System.out.println(">>>> tx = " + tx.getHashAsString()); // System.out.println(">>>> receive map = " + receiveMap); // System.out.println(">>>> send map = " + sendMap); //Map<String, String> nameAmountMap = new TreeMap<>(); ArrayList<JSONRPCTransactionAmount> resultList = new ArrayList<>(); boolean isSentByMe = tx.sent(wallet); Map<Integer, BigInteger> loopMap = (isSentByMe) ? sendMap : receiveMap; // Integer assetID = null; BigInteger netAmount = null; // for (Map.Entry<Integer, BigInteger> entry : loopMap.entrySet()) { for (Integer assetID : loopMap.keySet()) { // assetID = entry.getKey(); if (assetID == null || assetID == 0) continue; // skip bitcoin BigInteger receivedAmount = receiveMap.get(assetID); // should be number of raw units BigInteger sentAmount = sendMap.get(assetID); boolean isReceivedAmountMissing = (receivedAmount==null); boolean isSentAmountMissing = (sentAmount==null); netAmount = BigInteger.ZERO; if (!isReceivedAmountMissing) netAmount = netAmount.add(receivedAmount); if (!isSentAmountMissing) netAmount = netAmount.subtract(sentAmount); if (isSentByMe && !isSentAmountMissing && sentAmount.equals(BigInteger.ZERO)) { // Catch a case where for a send transaction, the send amount for an asset is 0, // but the receive cmount is not 0. Also the asset was not valid. continue; } CSAsset asset = wallet.CS.getAsset(assetID); if (asset==null) { // something went wrong, we have asset id but no asset, probably deleted. // For now, we carry on, and we display what we know. } if (netAmount.equals(BigInteger.ZERO) && isSentByMe) { // If net asset is 0 and this is our send transaction, // we don't need to show anything, as this probably due to implicit transfer. // So continue the loop. continue; } if (netAmount.equals(BigInteger.ZERO) && !isSentByMe) { // Receiving an asset, where the value is 0 because its not confirmed yet, // or not known because asset files not uploaded so we dont know display format. // Anyway, we don't do anything here as we do want to display this incoming // transaction the best we can. } // System.out.println(">>>> isSentAmountMissing = " + isSentAmountMissing); // System.out.println(">>>> asset reference = " + asset.getAssetReference()); // System.out.println(">>>> asset name = " + asset.getName()); String name = null; CoinSparkGenesis genesis = null; boolean isUnknown = false; if (asset!=null) { genesis = asset.getGenesis(); name = asset.getNameShort(); // could return null? } if (name == null) { isUnknown = true; if (genesis!=null) { name = "Asset from " + genesis.getDomainName(); } else { // No genesis block found yet name = "Other Asset"; } } String s1 = null; if (asset == null || isUnknown==true || (netAmount.equals(BigInteger.ZERO) && !isSentByMe) ) { // We don't have formatting details since asset is unknown or deleted // If there is a quantity, we don't display it since we don't have display format info // Of if incoming asset transfer, unconfirmed, it will be zero, so show ... instead s1 = "..."; } else { BigDecimal displayUnits = CSMiscUtils.getDisplayUnitsForRawUnits(asset, netAmount); s1 = CSMiscUtils.getFormattedDisplayString(asset, displayUnits); } // // Create JSONRPCTransactionAmount and add it to list // String fullName = ""; String assetRef = ""; if (asset!=null) { fullName = asset.getName(); if (fullName==null) fullName = name; // use short name assetRef = CSMiscUtils.getHumanReadableAssetRef(asset); } BigDecimal displayQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, netAmount); JSONRPCTransactionAmount amount = new JSONRPCTransactionAmount(); amount.setAsset_ref(assetRef); amount.setDisplay(s1); amount.setName(fullName); amount.setName_short(name); amount.setQty(displayQty.doubleValue()); amount.setRaw(netAmount.longValue()); resultList.add(amount); } BigInteger satoshiAmount = receiveMap.get(0); satoshiAmount = satoshiAmount.subtract(sendMap.get(0)); // We will show the fee separately so no need to include here. if (excludeBTCFee && isSentByMe) { BigInteger feeSatoshis = tx.calculateFee(wallet); // returns positive if (absoluteBTCFee) { satoshiAmount = satoshiAmount.abs().subtract(feeSatoshis); } else { satoshiAmount = satoshiAmount.add(feeSatoshis); } } String btcAmount = Utils.bitcoinValueToFriendlyString(satoshiAmount) + " BTC"; BigDecimal satoshiAmountBTC = new BigDecimal(satoshiAmount).divide(new BigDecimal(Utils.COIN)); JSONRPCTransactionAmount amount = new JSONRPCTransactionAmount(); amount.setAsset_ref("bitcoin"); amount.setDisplay(btcAmount); amount.setName("Bitcoin"); amount.setName_short("Bitcoin"); amount.setQty(satoshiAmountBTC.doubleValue()); amount.setRaw(satoshiAmount.longValue()); resultList.add(amount); return resultList; } /** * Returns an array of unspent transaction outputs, detailing the Bitcoin and * asset balances tied to that UTXO. * * Behavior is modeled from bitcoin: https://bitcoin.org/en/developer-reference#listunspent * minconf "Default is 1; use 0 to count unconfirmed transactions." * maxconf "Default is 9,999,999; use 0 to count unconfirmed transactions." * As minconf and maxconf are not optional, the default values above are ignored. * * @param walletname * @param minconf * @param maxconf * @param addresses List of CoinSpark or Bitcoin addresses * @return * @throws com.bitmechanic.barrister.RpcException */ @Override public JSONRPCUnspentTransactionOutput[] listunspent(String walletname, Long minconf, Long maxconf, String[] addresses) throws com.bitmechanic.barrister.RpcException { log.info("LIST UNSPENT TRANSACTION OUTPUTS"); log.info("wallet name = " + walletname); log.info("min number of confirmations = " + minconf); log.info("max number of confirmations = " + maxconf); log.info("addresses = " + Arrays.toString(addresses)); Wallet w = getWalletForWalletName(walletname); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } if (minconf<0 || maxconf<0) { JSONRPCError.CONFIRMATIONS_TOO_LOW.raiseRpcException(); } NetworkParameters networkParams = this.controller.getModel().getNetworkParameters(); int mostCommonChainHeight = this.controller.getMultiBitService().getPeerGroup().getMostCommonChainHeight(); boolean skipAddresses = addresses.length == 0; // Parse the list of addresses // If CoinSpark, convert to BTC. Set<String> setOfAddresses = new HashSet<String>(); for (String address: addresses) { address = address.trim(); if (address.length()==0) { continue; // ignore empty string } String btcAddress = null; String csAddress = null; if (address.startsWith("s")) { csAddress = address; btcAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address); if (btcAddress == null) { // Invalid CoinSpark address, so throw exception JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(csAddress); } } else { btcAddress = address; } boolean b = CSMiscUtils.validateBitcoinAddress(btcAddress, this.controller); if (b) { setOfAddresses.add(btcAddress); // convenience to add coinspark address for lookup // if (csAddress != null) setOfAddresses.add(csAddress); } else { if (csAddress != null) { // Invalid Bitcoin address from decoded CoinSpark address so throw exception. JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(csAddress + " --> decoded btc address " + btcAddress); } else { // Invalid Bitcoin address JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException(btcAddress); } } } // If the set of addresses is empty, list of addresses probably whitespace etc. // Let's treat as skipping addresses. if (setOfAddresses.size()==0) { skipAddresses = true; } Map<String, String> csAddressMap = SparkBitMapDB.INSTANCE.getSendTransactionToCoinSparkAddressMap(); ArrayList<JSONRPCUnspentTransactionOutput> resultList = new ArrayList<>(); Map<CSTransactionOutput, Map<Integer,CSBalance>> map = w.CS.getAllAssetTxOuts(); // Set<CSTransactionOutput> keys = map.keySet(); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); CSTransactionOutput cstxout = (CSTransactionOutput) entry.getKey(); // Only process if txout belongs to our wallet and is unspent Transaction tx = cstxout.getParentTransaction(); TransactionOutput txout = tx.getOutput(cstxout.getIndex()); if (!txout.isAvailableForSpending() || !txout.isMine(w)) { continue; } int txAppearedAtChainHeight = tx.getConfidence().getAppearedAtChainHeight(); int numConfirmations = mostCommonChainHeight - txAppearedAtChainHeight + 1; // if same, then it means 1 confirmation // NOTE: if we are syncing, result could be 0 or negative? // Only process if number of confirmations is within range. if (minconf==0 || maxconf==0) { // Unconfirmed transactions are okay, so do nothing. } else if (numConfirmations < minconf || numConfirmations > maxconf) { // Skip if outside of range continue; } // Only process if the BTC address for this tx is in the list of addresses String btcAddress = txout.getScriptPubKey().getToAddress(networkParams).toString(); if (!skipAddresses && !setOfAddresses.contains(btcAddress)) { continue; } // Get the bitcoin and asset balances on this utxo Map<Integer,CSBalance> balances = (Map<Integer,CSBalance>) entry.getValue(); boolean hasAssets = false; ArrayList<JSONRPCBalance> balancesList = new ArrayList<>(); for (Map.Entry<Integer, CSBalance> balanceEntry : balances.entrySet()) { Integer assetID = balanceEntry.getKey(); CSBalance balance = balanceEntry.getValue(); BigInteger qty = balance.getQty(); boolean isSelectable = DefaultCoinSelector.isSelectable(tx); log.info(">>>> assetID = " + assetID + " , qty = " + qty); // Handle Bitcoin specially if (assetID==0) { JSONRPCBalance bal = null; if (isSelectable) { bal = createBitcoinBalance(w, qty, qty); } else { bal = createBitcoinBalance(w, qty, BigInteger.ZERO); } System.out.println(">>> bal = " + bal.toString()); balancesList.add(bal); continue; } // Other assets hasAssets = true; if (qty.compareTo(BigInteger.ZERO)>0) { JSONRPCBalance bal = null; if (isSelectable) { bal = createAssetBalance(w, assetID, qty, qty); } else { bal = createAssetBalance(w, assetID, qty, BigInteger.ZERO); } balancesList.add(bal); } } JSONRPCBalance[] balancesArray = balancesList.toArray(new JSONRPCBalance[0]); String scriptPubKeyHexString = Utils.bytesToHexString( txout.getScriptBytes() ); // Build the object to return JSONRPCUnspentTransactionOutput utxo = new JSONRPCUnspentTransactionOutput(); utxo.setTxid(tx.getHashAsString()); utxo.setVout((long)cstxout.getIndex()); utxo.setScriptPubKey(scriptPubKeyHexString); utxo.setAmounts(balancesArray); //new JSONRPCBalance[0]); utxo.setConfirmations((long)numConfirmations); utxo.setBitcoin_address(btcAddress); if (hasAssets) { String sparkAddress = null; // First let's see if we have stored the recipient in our map and use it instead // of generating a new one from bitcoin address try { if (csAddressMap != null) { String spk = csAddressMap.get(tx.getHashAsString()); String btc = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(spk); if (btc.equals(btcAddress)) { sparkAddress = spk; } } } catch (Exception e) { } if (sparkAddress == null) { sparkAddress = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(btcAddress); } utxo.setCoinspark_address(sparkAddress); } utxo.setAmounts(balancesArray); resultList.add(utxo); } JSONRPCUnspentTransactionOutput[] resultArray = resultList.toArray(new JSONRPCUnspentTransactionOutput[0]); return resultArray; } /** * Create a JSONRPCBalance object for Bitcoin asset * @param w * @return */ private JSONRPCBalance createBitcoinBalance(Wallet w) { BigInteger rawBalanceSatoshi = w.getBalance(Wallet.BalanceType.ESTIMATED); BigInteger rawSpendableSatoshi = w.getBalance(Wallet.BalanceType.AVAILABLE); return createBitcoinBalance(w, rawSpendableSatoshi, rawBalanceSatoshi); } /** * Create a JSONRPCBalance object for Bitcoin asset * @param w * @param rawBalanceSatoshi In BitcoinJ terms, this is the estimated total balance * @param rawSpendableSatoshi In BitcoinJ terms, this is the available amount to spend * @return */ private JSONRPCBalance createBitcoinBalance(Wallet w, BigInteger rawBalanceSatoshi, BigInteger rawSpendableSatoshi) { BigDecimal rawBalanceBTC = new BigDecimal(rawBalanceSatoshi).divide(new BigDecimal(Utils.COIN)); BigDecimal rawSpendableBTC = new BigDecimal(rawSpendableSatoshi).divide(new BigDecimal(Utils.COIN)); String rawBalanceDisplay = Utils.bitcoinValueToFriendlyString(rawBalanceSatoshi) + " BTC"; String rawSpendableDisplay = Utils.bitcoinValueToFriendlyString(rawBalanceSatoshi) + " BTC"; JSONRPCBalanceAmount bitcoinBalanceAmount = new JSONRPCBalanceAmount(rawBalanceSatoshi.longValue(), rawBalanceBTC.doubleValue(), rawBalanceDisplay); JSONRPCBalanceAmount bitcoinSpendableAmount = new JSONRPCBalanceAmount(rawSpendableSatoshi.longValue(), rawSpendableBTC.doubleValue(), rawSpendableDisplay); JSONRPCBalance btcAssetBalance = new JSONRPCBalance(); btcAssetBalance.setAsset_ref("bitcoin"); btcAssetBalance.setBalance(bitcoinBalanceAmount); btcAssetBalance.setSpendable(bitcoinSpendableAmount); btcAssetBalance.setVisible(true); btcAssetBalance.setValid(true); return btcAssetBalance; } /** * Create and populate a JSONRPCBalance object given an assetID and balance * @param w * @param assetID * @param totalRaw * @param spendableRaw * @return */ private JSONRPCBalance createAssetBalance(Wallet w, int assetID, BigInteger totalRaw, BigInteger spendableRaw) { //Wallet.CoinSpark.AssetBalance assetBalance; CSAsset asset = w.CS.getAsset(assetID); String name = asset.getName(); String nameShort = asset.getNameShort(); if (name == null) { CoinSparkGenesis genesis = asset.getGenesis(); if (genesis != null) { name = "Asset from " + genesis.getDomainName(); nameShort = name; } else { // No genesis block found yet name = "Other Asset"; nameShort = "Other Asset"; } } String assetRef = CSMiscUtils.getHumanReadableAssetRef(asset); if (assetRef == null) { assetRef = "Awaiting new asset confirmation..."; } Double spendableQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, spendableRaw).doubleValue(); String spendableDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, spendableRaw); JSONRPCBalanceAmount spendableAmount = new JSONRPCBalanceAmount(spendableRaw.longValue(), spendableQty, spendableDisplay); Double balanceQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, totalRaw).doubleValue(); String balanceDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, totalRaw); JSONRPCBalanceAmount balanceAmount = new JSONRPCBalanceAmount(totalRaw.longValue(), balanceQty, balanceDisplay); JSONRPCBalance ab = new JSONRPCBalance(); ab.setAsset_ref(assetRef); ab.setBalance(balanceAmount); ab.setSpendable(spendableAmount); ab.setName(name); ab.setName_short(nameShort); String domain = CSMiscUtils.getDomainHost(asset.getDomainURL()); ab.setDomain(domain); ab.setUrl(asset.getAssetWebPageURL()); ab.setIssuer(asset.getIssuer()); ab.setDescription(asset.getDescription()); ab.setUnits(asset.getUnits()); ab.setMultiple(asset.getMultiple()); ab.setStatus(CSMiscUtils.getHumanReadableAssetState(asset.getAssetState())); boolean isValid = (asset.getAssetState() == CSAsset.CSAssetState.VALID); // FIXME: Check num confirms too? ab.setValid(isValid); Date validCheckedDate = asset.getValidChecked(); if (validCheckedDate != null) { ab.setChecked_unixtime(validCheckedDate.getTime() / 1000L); } ab.setContract_url(asset.getContractUrl()); String contractPath = asset.getContractPath(); if (contractPath != null) { String appDirPath = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory(); File file = new File(contractPath); File dir = new File(appDirPath); try { URI absolute = file.toURI(); URI base = dir.toURI(); URI relative = base.relativize(absolute); contractPath = relative.getPath(); } catch (Exception e) { // do nothing, if error, just use full contractPath } } ab.setContract_file(contractPath); ab.setGenesis_txid(asset.getGenTxID()); Date creationDate = asset.getDateCreation(); if (creationDate != null) { ab.setAdded_unixtime(creationDate.getTime() / 1000L); } // 3 October 2014, 1:47 am SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, h:mm"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // CoinSpark asset web page shows GMT/UTC. SimpleDateFormat ampmdf = new SimpleDateFormat(" a"); // by default is uppercase and we need lower to match website Date issueDate = asset.getIssueDate(); if (issueDate != null) { ab.setIssue_date(sdf.format(issueDate) + ampmdf.format(issueDate).toLowerCase()); ab.setIssue_unixtime(issueDate.getTime() / 1000L); } // Never expires Date expiryDate = asset.getExpiryDate(); if (expiryDate != null) { ab.setExpiry_date(sdf.format(expiryDate) + ampmdf.format(expiryDate).toLowerCase()); ab.setExpiry_unixtime(expiryDate.getTime() / 1000L); } ab.setTracker_urls(asset.getCoinsparkTrackerUrls()); ab.setIcon_url(asset.getIconUrl()); ab.setImage_url(asset.getImageUrl()); ab.setFeed_url(asset.getFeedUrl()); ab.setRedemption_url(asset.getRedemptionUrl()); ab.setVisible(asset.isVisible()); return ab; } @Override public JSONRPCBalance[] listbalances(String walletID, Boolean onlyVisible) throws com.bitmechanic.barrister.RpcException { log.info("LIST BALANCES"); log.info("wallet name = " + walletID); log.info("only visible = " + onlyVisible); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } ArrayList<JSONRPCBalance> resultList = new ArrayList<>(); // Add entry for BTC balances JSONRPCBalance btcAssetBalance = createBitcoinBalance(w); resultList.add(btcAssetBalance); int[] assetIDs = w.CS.getAssetIDs(); int n = 0; if (assetIDs!=null) { n = assetIDs.length; } Wallet.CoinSpark.AssetBalance assetBalance; for (int i=0; i<n; i++) { int id = assetIDs[i]; if (id==0) continue; CSAsset asset = w.CS.getAsset(id); if (asset==null) continue; if (onlyVisible && !asset.isVisible()) continue; String name=asset.getName(); String nameShort=asset.getNameShort(); if (name == null) { CoinSparkGenesis genesis = asset.getGenesis(); if (genesis!=null) { name = "Asset from " + genesis.getDomainName(); nameShort = name; } else { // No genesis block found yet name = "Other Asset"; nameShort = "Other Asset"; } } String assetRef = CSMiscUtils.getHumanReadableAssetRef(asset); if (assetRef==null) assetRef = "Awaiting new asset confirmation..."; assetBalance = w.CS.getAssetBalance(id); JSONRPCBalance ab = createAssetBalance(w, id, assetBalance.total, assetBalance.spendable); /* Long spendableRaw = assetBalance.spendable.longValue(); Double spendableQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, assetBalance.spendable).doubleValue(); String spendableDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, assetBalance.spendable); JSONRPCBalanceAmount spendableAmount = new JSONRPCBalanceAmount(spendableRaw, spendableQty, spendableDisplay); Long balanceRaw = assetBalance.total.longValue(); Double balanceQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, assetBalance.total).doubleValue(); String balanceDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, assetBalance.total); JSONRPCBalanceAmount balanceAmount = new JSONRPCBalanceAmount(balanceRaw, balanceQty, balanceDisplay); JSONRPCBalance ab = new JSONRPCBalance(); ab.setAsset_ref(assetRef); ab.setBalance(balanceAmount); ab.setSpendable(spendableAmount); ab.setName(name); ab.setName_short(nameShort); String domain = CSMiscUtils.getDomainHost(asset.getDomainURL()); ab.setDomain(domain); ab.setUrl(asset.getAssetWebPageURL()); ab.setIssuer(asset.getIssuer()); ab.setDescription(asset.getDescription()); ab.setUnits(asset.getUnits()); ab.setMultiple(asset.getMultiple()); ab.setStatus(CSMiscUtils.getHumanReadableAssetState(asset.getAssetState())); boolean isValid = (asset.getAssetState()==CSAsset.CSAssetState.VALID); // FIXME: Check num confirms too? ab.setValid(isValid); Date validCheckedDate = asset.getValidChecked(); if (validCheckedDate!=null) { ab.setChecked_unixtime(validCheckedDate.getTime()/1000L); } ab.setContract_url(asset.getContractUrl()); String contractPath = asset.getContractPath(); if (contractPath!=null) { String appDirPath = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory(); File file = new File(contractPath); File dir = new File(appDirPath); try { URI absolute = file.toURI(); URI base = dir.toURI(); URI relative = base.relativize(absolute); contractPath = relative.getPath(); } catch (Exception e) { // do nothing, if error, just use full contractPath } } ab.setContract_file(contractPath); ab.setGenesis_txid(asset.getGenTxID()); Date creationDate = asset.getDateCreation(); if (creationDate != null) { ab.setAdded_unixtime(creationDate.getTime()/1000L); } // 3 October 2014, 1:47 am SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, h:mm"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // CoinSpark asset web page shows GMT/UTC. SimpleDateFormat ampmdf = new SimpleDateFormat(" a"); // by default is uppercase and we need lower to match website Date issueDate = asset.getIssueDate(); if (issueDate != null) { ab.setIssue_date(sdf.format(issueDate) + ampmdf.format(issueDate).toLowerCase()); ab.setIssue_unixtime(issueDate.getTime()/1000L); } // Never expires Date expiryDate = asset.getExpiryDate(); if (expiryDate != null) { ab.setExpiry_date(sdf.format(expiryDate) + ampmdf.format(expiryDate).toLowerCase() ); ab.setExpiry_unixtime(expiryDate.getTime()/1000L); } ab.setTracker_urls(asset.getCoinsparkTrackerUrls()); ab.setIcon_url(asset.getIconUrl()); ab.setImage_url(asset.getImageUrl()); ab.setFeed_url(asset.getFeedUrl()); ab.setRedemption_url(asset.getRedemptionUrl()); ab.setVisible(asset.isVisible()); */ resultList.add(ab); } JSONRPCBalance[] resultArray = resultList.toArray(new JSONRPCBalance[0]); return resultArray; } @Override public synchronized String sendbitcoin(String walletID, String address, Double amount) throws com.bitmechanic.barrister.RpcException { log.info("SEND BITCOIN"); log.info("wallet name = " + walletID); log.info("address = " + address); log.info("amount = " + amount); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } if (amount<=0.0) { JSONRPCError.SEND_BITCOIN_AMOUNT_TOO_LOW.raiseRpcException(); } String bitcoinAddress = address; if (address.startsWith("s")) { bitcoinAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address); if (bitcoinAddress==null) { JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(); } } boolean isValid = CSMiscUtils.validateBitcoinAddress(bitcoinAddress, controller); if (!isValid) { JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException(); } String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); if (wd.isBusy()) { JSONRPCError.WALLEY_IS_BUSY.raiseRpcException(); } else { wd.setBusy(true); wd.setBusyTaskKey("jsonrpc.busy.sendbitcoin"); this.controller.fireWalletBusyChange(true); } Transaction sendTransaction = null; boolean sendValidated = false; boolean sendSuccessful = false; String sendTxHash = null; try { String sendAmount = amount.toString(); // Create a SendRequest. Address sendAddressObject; sendAddressObject = new Address(controller.getModel().getNetworkParameters(), bitcoinAddress); Wallet.SendRequest sendRequest = Wallet.SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount)); // SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount), 6, new BigInteger("10000"),1); sendRequest.ensureMinRequiredFee = true; sendRequest.fee = BigInteger.ZERO; sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT; // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form. // Complete it (which works out the fee) but do not sign it yet. log.info("Just about to complete the tx (and calculate the fee)..."); w.completeTx(sendRequest, false); sendValidated = true; log.info("The fee after completing the transaction was " + sendRequest.fee); // Let's do it for real now. sendTransaction = this.controller.getMultiBitService().sendCoins(wd, sendRequest, null); if (sendTransaction == null) { // a null transaction returned indicates there was not // enough money (in spite of our validation) JSONRPCError.SEND_BITCOIN_INSUFFICIENT_MONEY.raiseRpcException(); } else { sendSuccessful = true; sendTxHash = sendTransaction.getHashAsString(); log.info("Sent transaction was:\n" + sendTransaction.toString()); } if (sendSuccessful) { // There is enough money. /* If sending assets or BTC to a coinspark address, record transaction id --> coinspark address, into hashmap so we can use when displaying transactions */ if (address.startsWith("s")) { java.util.Map<String, String> m = SparkBitMapDB.INSTANCE.getSendTransactionToCoinSparkAddressMap(); if (m != null) { m.put(sendTxHash, address); SparkBitMapDB.INSTANCE.getMapDB().commit(); } } } else { // There is not enough money } // } catch (WrongNetworkException e1) { // } catch (AddressFormatException e1) { // } catch (KeyCrypterException e1) { } catch (InsufficientMoneyException e) { JSONRPCError.SEND_BITCOIN_INSUFFICIENT_MONEY.raiseRpcException(); } catch (Exception e) { JSONRPCError.throwAsRpcException("Could not send bitcoin due to error", e); } finally { // Save the wallet. try { this.controller.getFileHandler().savePerWalletModelData(wd, false); } catch (WalletSaveException e) { // log.error(e.getMessage(), e); } if (sendSuccessful) { // This returns immediately if rpcsendassettimeout is 0. JSONRPCController.INSTANCE.waitForTxSelectable(sendTransaction); // JSONRPCController.INSTANCE.waitForTxBroadcast(sendTxHash); } // Declare that wallet is no longer busy with the task. wd.setBusyTaskKey(null); wd.setBusy(false); this.controller.fireWalletBusyChange(false); } if (sendSuccessful) { controller.fireRecreateAllViews(false); } return sendTxHash; } @Override public synchronized String sendasset(String walletID, String address, String assetRef, Double quantity, Boolean senderPays) throws com.bitmechanic.barrister.RpcException { log.info("SEND ASSET"); log.info("wallet name = " + walletID); log.info("address = " + address); log.info("asset ref = " + assetRef); log.info("quantity = " + quantity); log.info("sender pays = " + senderPays); String sendTxHash = null; boolean sendValidated = false; boolean sendSuccessful = false; Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } if (quantity<=0.0) { JSONRPCError.SEND_ASSET_AMOUNT_TOO_LOW.raiseRpcException(); } String bitcoinAddress = address; if (!address.startsWith("s")) { JSONRPCError.ADDRESS_NOT_COINSPARK_ADDRESS.raiseRpcException(); } else { bitcoinAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address); if (bitcoinAddress==null) { JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(); } CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(address); if (!CSMiscUtils.canSendAssetsToCoinSparkAddress(csa)) { JSONRPCError.COINSPARK_ADDRESS_MISSING_ASSET_FLAG.raiseRpcException(); } } boolean isValid = CSMiscUtils.validateBitcoinAddress(bitcoinAddress, controller); if (!isValid) { JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException(); } String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); if (wd.isBusy()) { JSONRPCError.WALLEY_IS_BUSY.raiseRpcException(); } else { wd.setBusy(true); wd.setBusyTaskKey("jsonrpc.busy.sendasset"); this.controller.fireWalletBusyChange(true); } Transaction sendTransaction = null; try { // -- boilerplate ends here.... CSAsset asset = getAssetForAssetRefString(w, assetRef); if (asset==null) { if (isAssetRefValid(assetRef)) { JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException(); } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } if (asset.getAssetState()!=CSAsset.CSAssetState.VALID) { if (!CSMiscUtils.canSendInvalidAsset(controller)) { JSONRPCError.ASSET_STATE_INVALID.raiseRpcException(); } } // Check number of confirms int lastHeight = w.getLastBlockSeenHeight(); CoinSparkAssetRef assetReference = asset.getAssetReference(); if (assetReference != null) { final int blockIndex = (int) assetReference.getBlockNum(); final int numConfirmations = lastHeight - blockIndex + 1; // 0 means no confirmation, 1 is yes for sa int threshold = NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD; // FIXME: REMOVE/COMMENT OUT BEFORE RELEASE? String sendAssetWithJustOneConfirmation = controller.getModel().getUserPreference("sendAssetWithJustOneConfirmation"); if (Boolean.TRUE.toString().equals(sendAssetWithJustOneConfirmation)) { threshold = 1; } //System.out.println(">>>> " + CSMiscUtils.getHumanReadableAssetRef(asset) + " num confirmations " + numConfirmations + ", threshold = " + threshold); if (numConfirmations < threshold) { JSONRPCError.ASSET_NOT_CONFIRMED.raiseRpcException(); } } String displayQtyString = new BigDecimal(quantity).toPlainString(); BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, displayQtyString); int assetID = asset.getAssetID(); BigInteger spendableAmount = w.CS.getAssetBalance(assetID).spendable; log.info("Want to send: " + assetAmountRawUnits + " , AssetID=" + assetID + ", total="+w.CS.getAssetBalance(assetID).total + ", spendable=" + w.CS.getAssetBalance(assetID).spendable ); String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT); CoinSparkGenesis genesis = asset.getGenesis(); long desiredRawUnits = assetAmountRawUnits.longValue(); short chargeBasisPoints = genesis.getChargeBasisPoints(); long rawFlatChargeAmount = genesis.getChargeFlat(); boolean chargeExists = ( rawFlatChargeAmount>0 || chargeBasisPoints>0 ); if (chargeExists) { if (senderPays) { long x = genesis.calcGross(desiredRawUnits); assetAmountRawUnits = new BigInteger(String.valueOf(x)); } else { // We don't have to do anything if recipient pays, just send gross amount. // calcNet() returns what the recipient will receive, but it's not what we send. } } if (assetAmountRawUnits.compareTo(spendableAmount) > 0) { JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException(); } // Create a SendRequest. Address sendAddressObject; String sendAddress = bitcoinAddress; sendAddressObject = new Address(controller.getModel().getNetworkParameters(), sendAddress); //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount)); //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) { //BigInteger assetAmountRawUnits = new BigInteger(assetAmount); BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount); Wallet.SendRequest sendRequest = Wallet.SendRequest.to(sendAddressObject, bitcoinAmountSatoshis, assetID, assetAmountRawUnits, 1); sendRequest.ensureMinRequiredFee = true; sendRequest.fee = BigInteger.ZERO; sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT; // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form. // Complete it (which works out the fee) but do not sign it yet. log.info("Just about to complete the tx (and calculate the fee)..."); // there is enough money, so let's do it for real now w.completeTx(sendRequest, false); sendValidated = true; log.info("The fee after completing the transaction was " + sendRequest.fee); // Let's do it for real now. sendTransaction = this.controller.getMultiBitService().sendCoins(wd, sendRequest, null); if (sendTransaction == null) { // a null transaction returned indicates there was not // enough money (in spite of our validation) JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException(); } else { sendSuccessful = true; sendTxHash = sendTransaction.getHashAsString(); } if (sendSuccessful) { // There is enough money. /* If sending assets or BTC to a coinspark address, record transaction id --> coinspark address, into hashmap so we can use when displaying transactions */ if (address.startsWith("s")) { java.util.Map<String, String> m = SparkBitMapDB.INSTANCE.getSendTransactionToCoinSparkAddressMap(); if (m != null) { m.put(sendTxHash, address); SparkBitMapDB.INSTANCE.getMapDB().commit(); } } } else { // There is not enough money } //--- bolilerplate begins... } catch (InsufficientMoneyException ime) { JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException(); } catch (com.bitmechanic.barrister.RpcException e) { throw(e); } catch (Exception e) { JSONRPCError.throwAsRpcException("Could not send asset due to error: " , e); } finally { // Save the wallet. try { this.controller.getFileHandler().savePerWalletModelData(wd, false); } catch (WalletSaveException e) { // log.error(e.getMessage(), e); } if (sendSuccessful) { // This returns immediately if rpcsendassettimeout is 0. JSONRPCController.INSTANCE.waitForTxSelectable(sendTransaction); // JSONRPCController.INSTANCE.waitForTxBroadcast(sendTxHash); } // Declare that wallet is no longer busy with the task. wd.setBusyTaskKey(null); wd.setBusy(false); this.controller.fireWalletBusyChange(false); } if (sendSuccessful) { controller.fireRecreateAllViews(false); } return sendTxHash; } }
src/main/java/org/sparkbit/jsonrpc/SparkBitJSONRPCServiceImpl.java
/* * SparkBit * * Copyright 2014 Coin Sciences Ltd * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sparkbit.jsonrpc; import com.bitmechanic.barrister.RpcException; import org.multibit.controller.bitcoin.BitcoinController; import org.sparkbit.jsonrpc.autogen.*; import java.util.List; import java.util.ArrayList; import org.multibit.model.bitcoin.WalletData; import org.multibit.viewsystem.swing.MultiBitFrame; import org.multibit.model.core.StatusEnum; import org.multibit.network.ReplayManager; import com.google.bitcoin.core.*; //import java.util.HashMap; import java.util.Iterator; //import org.apache.commons.codec.digest.DigestUtils; import org.coinspark.protocol.CoinSparkAddress; import org.coinspark.protocol.CoinSparkAssetRef; import org.coinspark.wallet.CSAsset; import org.coinspark.wallet.CSAssetDatabase; import org.coinspark.wallet.CSEventBus; import org.coinspark.wallet.CSEventType; import org.multibit.utils.CSMiscUtils; import org.coinspark.protocol.CoinSparkAssetRef; import org.multibit.model.bitcoin.BitcoinModel; import org.multibit.model.bitcoin.WalletAddressBookData; import org.multibit.model.bitcoin.WalletInfoData; import com.google.bitcoin.crypto.KeyCrypter; import org.multibit.file.FileHandler; import java.io.*; import org.multibit.file.BackupManager; import com.google.bitcoin.crypto.KeyCrypterException; import com.google.bitcoin.script.Script; import com.google.bitcoin.wallet.DefaultCoinSelector; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.coinspark.protocol.CoinSparkGenesis; import org.joda.time.DateTime; import org.joda.time.LocalDateTime; import org.multibit.exchange.CurrencyConverter; import org.sparkbit.SBEvent; import org.sparkbit.SBEventType; import org.multibit.network.MultiBitService; import org.multibit.store.MultiBitWalletVersion; import java.util.Date; import org.multibit.file.WalletSaveException; import static org.multibit.model.bitcoin.WalletAssetComboBoxModel.NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD; import java.util.concurrent.ConcurrentHashMap; import org.coinspark.core.CSUtils; import java.text.SimpleDateFormat; import static org.multibit.network.MultiBitService.WALLET_SUFFIX; import static org.multibit.network.MultiBitService.getFilePrefix; import org.sparkbit.utils.FileNameCleaner; import org.apache.commons.io.FilenameUtils; import java.util.TimeZone; import org.multibit.viewsystem.swing.action.ExitAction; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import org.sparkbit.SparkBitMapDB; import org.apache.commons.io.FileDeleteStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.Arrays; import java.util.Set; import org.coinspark.wallet.CSBalance; import org.coinspark.wallet.CSTransactionOutput; import java.util.HashSet; /** * For now, synchronized access to commands which mutate */ public class SparkBitJSONRPCServiceImpl implements sparkbit { private static final Logger log = LoggerFactory.getLogger(SparkBitJSONRPCServiceImpl.class); // Limit on the number of addresses you can create in one call public static final int CREATE_ADDRESSES_LIMIT = 100; // How many milliseconds before we shutdown via ExitAction public static final int SHUTDOWN_DELAY = JettyEmbeddedServer.GRACEFUL_SHUTDOWN_PERIOD + 1000; private BitcoinController controller; // private MultiBitFrame mainFrame; // private ConcurrentHashMap<String,String> walletFilenameMap; private Timer stopTimer; public SparkBitJSONRPCServiceImpl() { this.controller = JSONRPCController.INSTANCE.getBitcoinController(); // this.mainFrame = JSONRPCController.INSTANCE.getMultiBitFrame(); // walletFilenameMap = new ConcurrentHashMap<>(); // updateWalletFilenameMap(); } // Quit after a delay so we can return true to JSON-RPC client. @Override public Boolean stop() throws com.bitmechanic.barrister.RpcException { log.info("STOP"); log.info("Shutting down JSON-RPC server, will wait " + SHUTDOWN_DELAY + " milliseconds before instructing SparkBit to exit."); final BitcoinController myController = this.controller; stopTimer = new Timer(); stopTimer.schedule(new TimerTask() { @Override public void run() { ExitAction exitAction = new ExitAction(myController, null); exitAction.setBitcoinController(myController); exitAction.actionPerformed(null); } }, SHUTDOWN_DELAY); // Signal the server to stop Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { JSONRPCController.INSTANCE.stopServer(); } }); return true; } /* Get status on a per wallet basis. */ @Override public JSONRPCStatusResponse getstatus() throws com.bitmechanic.barrister.RpcException { log.info("GET STATUS"); // boolean replayTaskRunning = ReplayManager.INSTANCE.getCurrentReplayTask()!=null ; // boolean regularDownloadRunning = ReplayManager.isRegularDownloadRunning(); // boolean synced = !regularDownloadRunning && !replayTaskRunning; // A regular download can be running in the background, because there is a new block, // and thus we are behind by one block, but the UI will still show that we synced. // We will consider ourselves to be out of sync if we are two or more blocks behind our peers. // PeerGroup pg = controller.getMultiBitService().getPeerGroup(); // if (pg!=null) { // Peer peer = pg.getDownloadPeer(); // if (peer != null) { // int n = peer.getPeerBlockHeightDifference(); // if (synced && n>=2) { // synced = false; // } // } // } int mostCommonChainHeight = controller.getMultiBitService().getPeerGroup().getMostCommonChainHeight(); //int bestChainHeight = controller.getMultiBitService().getChain().getBestChainHeight(); List<WalletData> perWalletModelDataList = controller.getModel().getPerWalletModelDataList(); List<JSONRPCWalletStatus> wallets = new ArrayList<JSONRPCWalletStatus>(); if (perWalletModelDataList != null) { for (WalletData wd : perWalletModelDataList) { Wallet w = wd.getWallet(); long lastSeenBlock = w.getLastBlockSeenHeight(); // getLastBlockSeenHeight() returns -1 if the wallet doesn't have this data yet if (lastSeenBlock==-1) lastSeenBlock = mostCommonChainHeight; boolean synced = (lastSeenBlock == mostCommonChainHeight); log.debug(">>>> *** description = " + wd.getWalletDescription()); log.debug(">>>> last block = " + lastSeenBlock); log.debug(">>>> mostCommonChainHeight = " + mostCommonChainHeight); log.debug(">>>> replay UUID = " + wd.getReplayTaskUUID()); log.debug(">>>> busy key = " + wd.getBusyTaskKey()); if (wd.getReplayTaskUUID() != null) { synced = false; } else if (wd.isBusy()) { String key = wd.getBusyTaskKey(); if (key.equals("multiBitDownloadListener.downloadingText") || key.equals("singleWalletPanel.waiting.text")) { synced = false; } } String filename = wd.getWalletFilename(); String base = FilenameUtils.getBaseName(filename); JSONRPCWalletStatus ws = new JSONRPCWalletStatus(base, synced, lastSeenBlock); wallets.add(ws); } } String versionNumber = controller.getLocaliser().getVersionNumber(); int numConnectedPeers = controller.getMultiBitService().getPeerGroup().numConnectedPeers(); boolean isTestNet = controller.getMultiBitService().isTestNet3(); JSONRPCStatusResponse resp = new JSONRPCStatusResponse(); resp.setVersion(versionNumber); resp.setConnections((long)numConnectedPeers); resp.setTestnet(isTestNet); JSONRPCWalletStatus[] x = wallets.toArray(new JSONRPCWalletStatus[0]); resp.setWallets( x ); return resp; } @Override public String[] listwallets() throws com.bitmechanic.barrister.RpcException { log.info("LIST WALLETS"); List<WalletData> perWalletModelDataList = controller.getModel().getPerWalletModelDataList(); List<String> names = new ArrayList<String>(); if (perWalletModelDataList != null) { for (WalletData loopPerWalletModelData : perWalletModelDataList) { String filename = loopPerWalletModelData.getWalletFilename(); String base = FilenameUtils.getBaseName(filename); names.add(base); // store/update local cache //walletFilenameMap.put(digest, filename); } } String[] resultArray = names.toArray(new String[0]); return resultArray; } @Override public synchronized Boolean createwallet(String name) throws com.bitmechanic.barrister.RpcException { log.info("CREATE WALLET"); log.info("wallet name = " + name); boolean isNameSane = sanityCheckName(name); if (!isNameSane) { JSONRPCError.WALLET_NAME_BAD_CHARS.raiseRpcException(); } if (name.startsWith(".") || name.endsWith(".")) { JSONRPCError.WALLET_NAME_PERIOD_START_END.raiseRpcException(); } String newWalletFilename = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory() + File.separator + name + MultiBitService.WALLET_SUFFIX; File newWalletFile = new File(newWalletFilename); if (newWalletFile.exists()) { JSONRPCError.WALLET_ID_ALREADY_EXISTS.raiseRpcException(); } LocalDateTime dt = new DateTime().toLocalDateTime(); String description = name + " (jsonrpc " + dt.toString("YYYY-MM-DD HH:mm" + ")"); //.SSS"); // Create a new wallet - protobuf.2 initially for backwards compatibility. try { Wallet newWallet = new Wallet(this.controller.getModel().getNetworkParameters()); ECKey newKey = new ECKey(); newWallet.addKey(newKey); WalletData perWalletModelData = new WalletData(); /* CoinSpark START */ // set default address label for first key WalletInfoData walletInfo = new WalletInfoData(newWalletFilename, newWallet, MultiBitWalletVersion.PROTOBUF); NetworkParameters networkParams = this.controller.getModel().getNetworkParameters(); Address defaultReceivingAddress = newKey.toAddress(networkParams); walletInfo.getReceivingAddresses().add(new WalletAddressBookData("Default Address", defaultReceivingAddress.toString())); perWalletModelData.setWalletInfo(walletInfo); /* CoinSpark END */ perWalletModelData.setWallet(newWallet); perWalletModelData.setWalletFilename(newWalletFilename); perWalletModelData.setWalletDescription(description); this.controller.getFileHandler().savePerWalletModelData(perWalletModelData, true); // Start using the new file as the wallet. this.controller.addWalletFromFilename(newWalletFile.getAbsolutePath()); // We could select the new wallet if we wanted to. //this.controller.getModel().setActiveWalletByFilename(newWalletFilename); //controller.getModel().setUserPreference(BitcoinModel.GRAB_FOCUS_FOR_ACTIVE_WALLET, "true"); // Save the user properties to disk. FileHandler.writeUserPreferences(this.controller); //log.debug("User preferences with new wallet written successfully"); // Backup the wallet and wallet info. BackupManager.INSTANCE.backupPerWalletModelData(controller.getFileHandler(), perWalletModelData); controller.fireRecreateAllViews(true); controller.fireDataChangedUpdateNow(); } catch (Exception e) { JSONRPCError.CREATE_WALLET_FAILED.raiseRpcException(); //JSONRPCError.throwAsRpcException("Could not create wallet", e); } // updateWalletFilenameMap(); return true; } @Override public synchronized Boolean deletewallet(String walletID) throws com.bitmechanic.barrister.RpcException { log.info("DELETE WALLET"); log.info("wallet name = " + walletID); Wallet w = getWalletForWalletName(walletID); if (w == null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } // Are there any asset or btc balances? Do not allow deleting wallet if any balance exists? Map<Integer, Wallet.CoinSpark.AssetBalance> map = w.CS.getAllAssetBalances(); for (Wallet.CoinSpark.AssetBalance ab : map.values()) { if (ab.total.compareTo(BigInteger.ZERO)>0) { JSONRPCError.DELETE_WALLET_NOT_EMPTY.raiseRpcException(); } } String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); WalletInfoData winfo = wd.getWalletInfo(); if (wd.isBusy()) { JSONRPCError.WALLEY_IS_BUSY.raiseRpcException(); } // Deleting a wallet even if not currently active, causes list of wallets to be unselected // so we need to keep track of what was active befor eremoval String activeFilename = this.controller.getModel().getActiveWalletFilename(); if (wd.getWalletFilename().equals(activeFilename)) { activeFilename = null; } // Unhook it from the PeerGroup. this.controller.getMultiBitService().getPeerGroup().removeWallet(w); // Remove it from the model. this.controller.getModel().remove(wd); // Perform delete if possible etc. FileHandler fileHandler = this.controller.getFileHandler(); try { fileHandler.deleteWalletAndWalletInfo(wd); // Delete .cs String csassets = filename + ".csassets"; String csbalances = filename + ".csbalances"; File f = new File(csassets); if (f.exists()) { if (!f.delete()) { //log.error(">>>> Asset DB: Cannot delete"); } } f = new File(csbalances); if (f.exists()) { if (!f.delete()) { //log.error(">>>> Balances DB: Cannot delete"); } } String cslog = filename + ".cslog"; f = new File(cslog); if (f.exists()) { if (!f.delete()) { // log.error(">>>> CS Log File: Cannot delete"); } } // Delete cached contracts String csfiles = filename + ".csfiles"; f = new File(csfiles); if (f.exists()) { FileDeleteStrategy.FORCE.delete(f); } // Delete the backup folder and cached contracts String backupFolderPath = BackupManager.INSTANCE.calculateTopLevelBackupDirectoryName(new File(filename)); f = new File(backupFolderPath); if (f.exists()) { FileDeleteStrategy.FORCE.delete(f); } } catch (Exception e) { JSONRPCError.throwAsRpcException("Error deleting wallet files", e); } if (!winfo.isDeleted()) { JSONRPCError.throwAsRpcException("Wallet was not deleted. Reason unknown."); } // Set the new Wallet to be the old active wallet, or the first wallet if (activeFilename!=null) { this.controller.getModel().setActiveWalletByFilename(activeFilename); } else if (!this.controller.getModel().getPerWalletModelDataList().isEmpty()) { WalletData firstPerWalletModelData = this.controller.getModel().getPerWalletModelDataList().get(0); this.controller.getModel().setActiveWalletByFilename(firstPerWalletModelData.getWalletFilename()); } controller.fireRecreateAllViews(true); // updateWalletFilenameMap(); return true; } /* Synchronized access: clear and recreate the wallet filename map. */ // private synchronized void updateWalletFilenameMap() { // walletFilenameMap.clear(); // List<WalletData> perWalletModelDataList = controller.getModel().getPerWalletModelDataList(); // if (perWalletModelDataList != null) { // for (WalletData loopPerWalletModelData : perWalletModelDataList) { // String filename = loopPerWalletModelData.getWalletFilename(); // String id = loopPerWalletModelData.getWalletDescription(); // walletFilenameMap. put(id, filename); //// //// String filename = loopPerWalletModelData.getWalletFilename(); //// String digest = DigestUtils.md5Hex(filename); //// walletFilenameMap. put(digest, filename); // } // } // // } /* Get full path for wallet given it's name */ private String getFullPathForWalletName(String name) { String filename = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory() + File.separator + name + WALLET_SUFFIX; return filename; } /* Check to see if a name gets cleaned or not because it contains characters bad for a filename */ private boolean sanityCheckName(String name) { String cleaned = FileNameCleaner.cleanFileName(name); return (cleaned.equals(name)); } private Wallet getWalletForWalletName(String walletID) { Wallet w = null; String filename = getFullPathForWalletName(walletID); if (filename != null) { WalletData wd = controller.getModel().getPerWalletModelDataByWalletFilename(filename); if (wd!=null) { w = wd.getWallet(); } } return w; } // Helper function private boolean isAssetRefValid(String s) { if (s!=null) { s = s.trim(); CoinSparkAssetRef assetRef = new CoinSparkAssetRef(); if (assetRef.decode(s)) { return true; } } return false; } private CSAsset getAssetForAssetRefString(Wallet w, String assetRef) { CSAssetDatabase db = w.CS.getAssetDB(); int[] assetIDs = w.CS.getAssetIDs(); if (assetIDs != null) { for (int id : assetIDs) { CSAsset asset = db.getAsset(id); if (asset != null) { //CoinSparkAssetRef ref = asset.getAssetReference(); String s = CSMiscUtils.getHumanReadableAssetRef(asset); if (s.equals(assetRef)) { return asset; } } } } return null; } @Override public synchronized Boolean setassetvisible(String walletID, String assetRef, Boolean visibility) throws com.bitmechanic.barrister.RpcException { log.info("SET ASSET VISIBILITY"); log.info("wallet name = " + walletID); log.info("asset ref = " + assetRef); log.info("visibility = " + visibility); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } CSAsset asset = getAssetForAssetRefString(w, assetRef); if (asset == null) { if (isAssetRefValid(assetRef)) { JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException(); } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } else { asset.setVisibility(visibility); CSEventBus.INSTANCE.postAsyncEvent(CSEventType.ASSET_VISIBILITY_CHANGED, asset.getAssetID()); } return true; } @Override public synchronized Boolean addasset(String walletID, String assetRefString) throws com.bitmechanic.barrister.RpcException { log.info("ADD ASSET"); log.info("wallet name = " + walletID); log.info("asset ref = " + assetRefString); Wallet w = getWalletForWalletName(walletID); if (w == null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } String s = assetRefString; if ((s != null) && (s.length() > 0)) { s = s.trim(); // Does the asset already exist? If so, return true. if (getAssetForAssetRefString(w, s) != null) { return true; } //System.out.println("asset ref detected! " + s); CoinSparkAssetRef assetRef = new CoinSparkAssetRef(); if (assetRef.decode(s)) { // Wallet wallet = this.controller.getModel().getActiveWallet(); CSAssetDatabase assetDB = w.CS.getAssetDB(); if (assetDB != null) { CSAsset asset = new CSAsset(assetRef, CSAsset.CSAssetSource.MANUAL); if (assetDB.insertAsset(asset) != null) { //System.out.println("Inserted new asset manually: " + asset); } else { JSONRPCError.throwAsRpcException("Internal error, assetDB.insertAsset() failed for an unknown reason"); } } } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } return true; } @Override public Boolean deleteasset(String walletname, String assetRef) throws com.bitmechanic.barrister.RpcException { log.info("DELETE ASSET"); log.info("wallet name = " + walletname); log.info("asset ref = " + assetRef); Wallet w = getWalletForWalletName(walletname); boolean success = false; CSAsset asset = getAssetForAssetRefString(w, assetRef); if (asset != null) { int assetID = asset.getAssetID(); BigInteger x = w.CS.getAssetBalance(assetID).total; boolean canDelete = x.equals(BigInteger.ZERO); // Delete invalid asset if property allows String s = controller.getModel().getUserPreference(BitcoinModel.CAN_DELETE_INVALID_ASSETS); boolean isAssetInvalid = asset.getAssetState() != CSAsset.CSAssetState.VALID; boolean deleteInvalidAsset = false; if (Boolean.TRUE.toString().equals(s) && isAssetInvalid) { deleteInvalidAsset = true; } if (canDelete || deleteInvalidAsset) { success = w.CS.deleteAsset(asset); if (success) { // Note: the event can be fired, but the listener can do nothing if in headless mode. // We want main asset panel to refresh, since there isn't an event fired on manual reset. CSEventBus.INSTANCE.postAsyncEvent(CSEventType.ASSET_DELETED, assetID); } else { JSONRPCError.DELETE_ASSET_FAILED.raiseRpcException(); } } else { if (isAssetInvalid) { JSONRPCError.DELETE_INVALID_ASSET_FAILED.raiseRpcException(); } else { JSONRPCError.DELETE_ASSET_NONZERO_BALANCE.raiseRpcException(); } } } else { if (isAssetRefValid(assetRef)) { JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException(); } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } return success; } @Override public synchronized Boolean refreshasset(String walletID, String assetRef) throws com.bitmechanic.barrister.RpcException { log.info("REFRESH ASSET"); log.info("wallet name = " + walletID); log.info("asset ref = " + assetRef); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } CSAsset asset = getAssetForAssetRefString(w, assetRef); if (asset != null) { asset.setRefreshState(); // Note: the event can be fired, but the listener can do nothing if in headless mode. // We want main asset panel to refresh, since there isn't an event fired on manual reset. CSEventBus.INSTANCE.postAsyncEvent(CSEventType.ASSET_UPDATED, asset.getAssetID()); } else { if (isAssetRefValid(assetRef)) { JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException(); } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } return true; } @Override public JSONRPCAddressBookEntry[] listaddresses(String walletID) throws com.bitmechanic.barrister.RpcException { log.info("LIST ADDRESSES"); log.info("wallet name = " + walletID); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } List<JSONRPCAddressBookEntry> addresses = new ArrayList<JSONRPCAddressBookEntry>(); String address, sparkAddress, label; String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); final WalletInfoData addressBook = wd.getWalletInfo(); if (addressBook != null) { ArrayList<WalletAddressBookData> receivingAddresses = addressBook.getReceivingAddresses(); if (receivingAddresses != null) { Iterator<WalletAddressBookData> iter = receivingAddresses.iterator(); while (iter.hasNext()) { WalletAddressBookData addressBookData = iter.next(); if (addressBookData != null) { address = addressBookData.getAddress(); label = addressBookData.getLabel(); sparkAddress = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(address); if (sparkAddress != null) { JSONRPCAddressBookEntry entry = new JSONRPCAddressBookEntry(label, address, sparkAddress); addresses.add(entry); } } } } } JSONRPCAddressBookEntry[] resultArray = addresses.toArray(new JSONRPCAddressBookEntry[0]); return resultArray; } // TODO: Should we remove limit of 100 addresses? @Override public synchronized JSONRPCAddressBookEntry[] createaddresses(String walletID, Long quantity) throws com.bitmechanic.barrister.RpcException { log.info("CREATE ADDRESSES"); log.info("wallet name = " + walletID); log.info("quantity = " + quantity); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } int qty = quantity.intValue(); if (qty <= 0) { JSONRPCError.CREATE_ADDRESS_TOO_FEW.raiseRpcException(); } if (qty > CREATE_ADDRESSES_LIMIT) { JSONRPCError.CREATE_ADDRESS_TOO_MANY.raiseRpcException(); } String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); if (wd.isBusy()) { JSONRPCError.WALLEY_IS_BUSY.raiseRpcException(); } else { wd.setBusy(true); wd.setBusyTaskKey("jsonrpc.busy.createaddress"); this.controller.fireWalletBusyChange(true); } List<JSONRPCAddressBookEntry> addresses = new ArrayList<JSONRPCAddressBookEntry>(); try { List<ECKey> newKeys = new ArrayList<ECKey>(); for (int i = 0; i < qty; i++) { ECKey newKey = new ECKey(); newKeys.add(newKey); } FileHandler fileHandler = this.controller.getFileHandler(); synchronized (wd.getWallet()) { wd.getWallet().addKeys(newKeys); } // Recalculate the bloom filter. if (this.controller.getMultiBitService() != null) { this.controller.getMultiBitService().recalculateFastCatchupAndFilter(); } // Add keys to address book. int n = 1, count = newKeys.size(); for (ECKey newKey : newKeys) { String lastAddressString = newKey.toAddress(this.controller.getModel().getNetworkParameters()).toString(); LocalDateTime dt = new DateTime().toLocalDateTime(); String label = "Created on " + dt.toString("d MMM y, HH:mm:ss z") + " (" + n++ + " of " + count + ")"; // unlikely address is already present, we don't want to update the label wd.getWalletInfo().addReceivingAddress(new WalletAddressBookData(label, lastAddressString), false); // Create structure for JSON response String sparkAddress = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(lastAddressString); if (sparkAddress == null) sparkAddress = "Internal error creating CoinSparkAddress from this Bitcoin address"; JSONRPCAddressBookEntry entry = new JSONRPCAddressBookEntry(label, lastAddressString, sparkAddress); addresses.add(entry); } // Backup the wallet and wallet info. BackupManager.INSTANCE.backupPerWalletModelData(fileHandler, wd); } catch (KeyCrypterException e) { JSONRPCError.throwAsRpcException("Create addresses failed with KeyCrypterException", e); } catch (Exception e) { JSONRPCError.throwAsRpcException("Create addresses failed", e); } finally { // Declare that wallet is no longer busy with the task. wd.setBusyTaskKey(null); wd.setBusy(false); this.controller.fireWalletBusyChange(false); } CSEventBus.INSTANCE.postAsync(new SBEvent(SBEventType.ADDRESS_CREATED)); wd.setDirty(true); JSONRPCAddressBookEntry[] resultArray = addresses.toArray(new JSONRPCAddressBookEntry[0]); return resultArray; } @Override public synchronized Boolean setaddresslabel(String walletID, String address, String label) throws com.bitmechanic.barrister.RpcException { log.info("SET ADDRESS LABEL"); log.info("wallet name = " + walletID); log.info("address = " + address); log.info("label = " + label); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } if (address.startsWith("s")) { address = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address); if (address==null) { JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(); } } if (label==null) label=""; // this shouldn't happen when invoked via barrister boolean success = false; String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); final WalletInfoData addressBook = wd.getWalletInfo(); if (addressBook != null) { ArrayList<WalletAddressBookData> receivingAddresses = addressBook.getReceivingAddresses(); if (receivingAddresses != null) { Iterator<WalletAddressBookData> iter = receivingAddresses.iterator(); while (iter.hasNext()) { WalletAddressBookData addressBookData = iter.next(); if (addressBookData != null) { String btcAddress = addressBookData.getAddress(); if (btcAddress.equals(address)) { addressBookData.setLabel(label); success = true; break; } } } } } if (success) { CSEventBus.INSTANCE.postAsync(new SBEvent(SBEventType.ADDRESS_UPDATED)); wd.setDirty(true); } else { JSONRPCError.ADDRESS_NOT_FOUND.raiseRpcException(); } return success; } @Override public JSONRPCTransaction[] listtransactions(String walletID, Long limit) throws com.bitmechanic.barrister.RpcException { log.info("LIST TRANSACTIONS"); log.info("wallet name = " + walletID); log.info("limit # = " + limit); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } // if (limit>100) { // JSONRPCError.LIST_TRANSACTIONS_TOO_MANY.raiseRpcException(); // } else if (limit<0) { JSONRPCError.LIST_TRANSACTIONS_TOO_FEW.raiseRpcException(); } // if limit is 0 get them all List<JSONRPCTransaction> resultList = new ArrayList<JSONRPCTransaction>(); int lastSeenBlock = controller.getMultiBitService().getChain().getBestChainHeight(); List<Transaction> transactions = null; if (limit > 0) { transactions = w.getRecentTransactions(limit.intValue(), false); } else { transactions = w.getTransactionsByTime(); } for (Transaction tx : transactions) { Date txDate = controller.getModel().getDateOfTransaction(controller, tx); long unixtime = txDate.getTime()/1000L; // unix epoch in seconds long confirmations = 0; try { confirmations = lastSeenBlock - tx.getConfidence().getAppearedAtChainHeight(); } catch (IllegalStateException e) { } boolean incoming = !tx.sent(w); BigInteger feeSatoshis = tx.calculateFee(w); Double fee = null; if (!incoming) { BigDecimal feeBTC = new BigDecimal(feeSatoshis).divide(new BigDecimal(Utils.COIN)); fee = -1.0 * feeBTC.doubleValue(); } String txid = tx.getHashAsString(); ArrayList<JSONRPCTransactionAmount> amounts = getAssetTransactionAmounts(w, tx, true, false); JSONRPCTransactionAmount[] amountsArray = amounts.toArray(new JSONRPCTransactionAmount[0]); // int size = amounts.size(); // AssetTransactionAmountEntry[] entries = new AssetTransactionAmountEntry[size]; // int index = 0; // for (JSONRPCTransactionAmount ata : amounts) { // entries[index++] = new AssetTransactionAmountEntry(ata.getAssetRef(), ata); // } /* Get send and receive address */ TransactionOutput myOutput = null; TransactionOutput theirOutput = null; List<TransactionOutput> transactionOutputs = tx.getOutputs(); if (transactionOutputs != null) { for (TransactionOutput transactionOutput : transactionOutputs) { if (transactionOutput != null && transactionOutput.isMine(w)) { myOutput = transactionOutput; } if (transactionOutput != null && !transactionOutput.isMine(w)) { // We have to skip the OP_RETURN output as there is no address and it result sin an exception when trying to get the destination address Script script = transactionOutput.getScriptPubKey(); if (script != null) { if (script.isSentToAddress() || script.isSentToP2SH()) { theirOutput = transactionOutput; } } } } } boolean hasAssets = amounts.size()>1; String myReceiveAddress = null; String theirAddress = null; if (incoming) { try { if (myOutput != null) { Address toAddress = new Address(this.controller.getModel().getNetworkParameters(), myOutput.getScriptPubKey().getPubKeyHash()); myReceiveAddress = toAddress.toString(); } if (myReceiveAddress != null && hasAssets) { String s = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(myReceiveAddress); if (s != null) { myReceiveAddress = s; } } } catch (ScriptException e) { } } else { // outgoing transaction if (theirOutput != null) { // First let's see if we have stored the recipient in our map try { Map<String,String> m = SparkBitMapDB.INSTANCE.getSendTransactionToCoinSparkAddressMap(); if (m != null) { theirAddress = m.get(tx.getHashAsString()); } } catch (Exception e) { } if (theirAddress == null) { try { theirAddress = theirOutput.getScriptPubKey().getToAddress(controller.getModel().getNetworkParameters()).toString(); } catch (ScriptException se) { } if (theirAddress != null & hasAssets) { String s = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(theirAddress); if (s != null) { theirAddress = s; } } } } } String address = ""; if (incoming && myReceiveAddress!=null) { address = myReceiveAddress; } else if (!incoming && theirAddress != null) { address = theirAddress; } String category = (incoming) ? "receive" : "send"; JSONRPCTransaction atx = new JSONRPCTransaction(unixtime, confirmations, category, amountsArray, fee, txid, address); resultList.add(atx); } JSONRPCTransaction[] resultArray = resultList.toArray(new JSONRPCTransaction[0]); return resultArray; } /* * Return array of asset transaction objects. * Original method is in CSMiscUtils, so any changes there, must be reflected here. */ private ArrayList<JSONRPCTransactionAmount> getAssetTransactionAmounts(Wallet wallet, Transaction tx, boolean excludeBTCFee, boolean absoluteBTCFee) { if (wallet==null || tx==null) return null; Map<Integer, BigInteger> receiveMap = wallet.CS.getAssetsSentToMe(tx); Map<Integer, BigInteger> sendMap = wallet.CS.getAssetsSentFromMe(tx); // System.out.println(">>>> tx = " + tx.getHashAsString()); // System.out.println(">>>> receive map = " + receiveMap); // System.out.println(">>>> send map = " + sendMap); //Map<String, String> nameAmountMap = new TreeMap<>(); ArrayList<JSONRPCTransactionAmount> resultList = new ArrayList<>(); boolean isSentByMe = tx.sent(wallet); Map<Integer, BigInteger> loopMap = (isSentByMe) ? sendMap : receiveMap; // Integer assetID = null; BigInteger netAmount = null; // for (Map.Entry<Integer, BigInteger> entry : loopMap.entrySet()) { for (Integer assetID : loopMap.keySet()) { // assetID = entry.getKey(); if (assetID == null || assetID == 0) continue; // skip bitcoin BigInteger receivedAmount = receiveMap.get(assetID); // should be number of raw units BigInteger sentAmount = sendMap.get(assetID); boolean isReceivedAmountMissing = (receivedAmount==null); boolean isSentAmountMissing = (sentAmount==null); netAmount = BigInteger.ZERO; if (!isReceivedAmountMissing) netAmount = netAmount.add(receivedAmount); if (!isSentAmountMissing) netAmount = netAmount.subtract(sentAmount); if (isSentByMe && !isSentAmountMissing && sentAmount.equals(BigInteger.ZERO)) { // Catch a case where for a send transaction, the send amount for an asset is 0, // but the receive cmount is not 0. Also the asset was not valid. continue; } CSAsset asset = wallet.CS.getAsset(assetID); if (asset==null) { // something went wrong, we have asset id but no asset, probably deleted. // For now, we carry on, and we display what we know. } if (netAmount.equals(BigInteger.ZERO) && isSentByMe) { // If net asset is 0 and this is our send transaction, // we don't need to show anything, as this probably due to implicit transfer. // So continue the loop. continue; } if (netAmount.equals(BigInteger.ZERO) && !isSentByMe) { // Receiving an asset, where the value is 0 because its not confirmed yet, // or not known because asset files not uploaded so we dont know display format. // Anyway, we don't do anything here as we do want to display this incoming // transaction the best we can. } // System.out.println(">>>> isSentAmountMissing = " + isSentAmountMissing); // System.out.println(">>>> asset reference = " + asset.getAssetReference()); // System.out.println(">>>> asset name = " + asset.getName()); String name = null; CoinSparkGenesis genesis = null; boolean isUnknown = false; if (asset!=null) { genesis = asset.getGenesis(); name = asset.getNameShort(); // could return null? } if (name == null) { isUnknown = true; if (genesis!=null) { name = "Asset from " + genesis.getDomainName(); } else { // No genesis block found yet name = "Other Asset"; } } String s1 = null; if (asset == null || isUnknown==true || (netAmount.equals(BigInteger.ZERO) && !isSentByMe) ) { // We don't have formatting details since asset is unknown or deleted // If there is a quantity, we don't display it since we don't have display format info // Of if incoming asset transfer, unconfirmed, it will be zero, so show ... instead s1 = "..."; } else { BigDecimal displayUnits = CSMiscUtils.getDisplayUnitsForRawUnits(asset, netAmount); s1 = CSMiscUtils.getFormattedDisplayString(asset, displayUnits); } // // Create JSONRPCTransactionAmount and add it to list // String fullName = ""; String assetRef = ""; if (asset!=null) { fullName = asset.getName(); if (fullName==null) fullName = name; // use short name assetRef = CSMiscUtils.getHumanReadableAssetRef(asset); } BigDecimal displayQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, netAmount); JSONRPCTransactionAmount amount = new JSONRPCTransactionAmount(); amount.setAsset_ref(assetRef); amount.setDisplay(s1); amount.setName(fullName); amount.setName_short(name); amount.setQty(displayQty.doubleValue()); amount.setRaw(netAmount.longValue()); resultList.add(amount); } BigInteger satoshiAmount = receiveMap.get(0); satoshiAmount = satoshiAmount.subtract(sendMap.get(0)); // We will show the fee separately so no need to include here. if (excludeBTCFee && isSentByMe) { BigInteger feeSatoshis = tx.calculateFee(wallet); // returns positive if (absoluteBTCFee) { satoshiAmount = satoshiAmount.abs().subtract(feeSatoshis); } else { satoshiAmount = satoshiAmount.add(feeSatoshis); } } String btcAmount = Utils.bitcoinValueToFriendlyString(satoshiAmount) + " BTC"; BigDecimal satoshiAmountBTC = new BigDecimal(satoshiAmount).divide(new BigDecimal(Utils.COIN)); JSONRPCTransactionAmount amount = new JSONRPCTransactionAmount(); amount.setAsset_ref("bitcoin"); amount.setDisplay(btcAmount); amount.setName("Bitcoin"); amount.setName_short("Bitcoin"); amount.setQty(satoshiAmountBTC.doubleValue()); amount.setRaw(satoshiAmount.longValue()); resultList.add(amount); return resultList; } /** * Returns an array of unspent transaction outputs, detailing the Bitcoin and * asset balances tied to that UTXO. * * Behavior is modeled from bitcoin: https://bitcoin.org/en/developer-reference#listunspent * minconf "Default is 1; use 0 to count unconfirmed transactions." * maxconf "Default is 9,999,999; use 0 to count unconfirmed transactions." * As minconf and maxconf are not optional, the default values above are ignored. * * @param walletname * @param minconf * @param maxconf * @param addresses List of CoinSpark or Bitcoin addresses * @return * @throws com.bitmechanic.barrister.RpcException */ @Override public JSONRPCUnspentTransactionOutput[] listunspent(String walletname, Long minconf, Long maxconf, String[] addresses) throws com.bitmechanic.barrister.RpcException { log.info("LIST UNSPENT TRANSACTION OUTPUTS"); log.info("wallet name = " + walletname); log.info("min number of confirmations = " + minconf); log.info("max number of confirmations = " + maxconf); log.info("addresses = " + Arrays.toString(addresses)); Wallet w = getWalletForWalletName(walletname); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } if (minconf<0 || maxconf<0) { JSONRPCError.CONFIRMATIONS_TOO_LOW.raiseRpcException(); } NetworkParameters networkParams = this.controller.getModel().getNetworkParameters(); int mostCommonChainHeight = this.controller.getMultiBitService().getPeerGroup().getMostCommonChainHeight(); boolean skipAddresses = addresses.length == 0; // Parse the list of addresses // If CoinSpark, convert to BTC. Set<String> setOfAddresses = new HashSet<String>(); for (String address: addresses) { address = address.trim(); if (address.length()==0) { continue; // ignore empty string } String btcAddress = null; String csAddress = null; if (address.startsWith("s")) { csAddress = address; btcAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address); if (btcAddress == null) { // Invalid CoinSpark address, so throw exception JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(csAddress); } } else { btcAddress = address; } boolean b = CSMiscUtils.validateBitcoinAddress(btcAddress, this.controller); if (b) { setOfAddresses.add(btcAddress); // convenience to add coinspark address for lookup // if (csAddress != null) setOfAddresses.add(csAddress); } else { if (csAddress != null) { // Invalid Bitcoin address from decoded CoinSpark address so throw exception. JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(csAddress + " --> decoded btc address " + btcAddress); } else { // Invalid Bitcoin address JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException(btcAddress); } } } // If the set of addresses is empty, list of addresses probably whitespace etc. // Let's treat as skipping addresses. if (setOfAddresses.size()==0) { skipAddresses = true; } Map<String, String> csAddressMap = SparkBitMapDB.INSTANCE.getSendTransactionToCoinSparkAddressMap(); ArrayList<JSONRPCUnspentTransactionOutput> resultList = new ArrayList<>(); Map<CSTransactionOutput, Map<Integer,CSBalance>> map = w.CS.getAllAssetTxOuts(); // Set<CSTransactionOutput> keys = map.keySet(); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); CSTransactionOutput cstxout = (CSTransactionOutput) entry.getKey(); // Only process if txout belongs to our wallet and is unspent Transaction tx = cstxout.getParentTransaction(); TransactionOutput txout = tx.getOutput(cstxout.getIndex()); if (!txout.isAvailableForSpending() || !txout.isMine(w)) { continue; } int txAppearedAtChainHeight = tx.getConfidence().getAppearedAtChainHeight(); int numConfirmations = mostCommonChainHeight - txAppearedAtChainHeight + 1; // if same, then it means 1 confirmation // NOTE: if we are syncing, result could be 0 or negative? // Only process if number of confirmations is within range. if (minconf==0 || maxconf==0) { // Unconfirmed transactions are okay, so do nothing. } else if (numConfirmations < minconf || numConfirmations > maxconf) { // Skip if outside of range continue; } // Only process if the BTC address for this tx is in the list of addresses String btcAddress = txout.getScriptPubKey().getToAddress(networkParams).toString(); if (!skipAddresses && !setOfAddresses.contains(btcAddress)) { continue; } // Get the bitcoin and asset balances on this utxo Map<Integer,CSBalance> balances = (Map<Integer,CSBalance>) entry.getValue(); // FIXME: Debugging log.info(">>>> balances = " + balances); if (balances.isEmpty()) { Map<Integer, BigInteger> receiveMap = w.CS.getAssetsSentToMe(tx); Map<Integer, BigInteger> sendMap = w.CS.getAssetsSentFromMe(tx); log.info(">>>> ...receiveMap = " + receiveMap); log.info(">>>> ...sendMap = " + sendMap); } // END FIXME: boolean hasAssets = false; ArrayList<JSONRPCBalance> balancesList = new ArrayList<>(); for (Map.Entry<Integer, CSBalance> balanceEntry : balances.entrySet()) { Integer assetID = balanceEntry.getKey(); CSBalance balance = balanceEntry.getValue(); BigInteger qty = balance.getQty(); boolean isSelectable = DefaultCoinSelector.isSelectable(tx); log.info(">>>> assetID = " + assetID + " , qty = " + qty); // Handle Bitcoin specially if (assetID==0) { JSONRPCBalance bal = null; if (isSelectable) { bal = createBitcoinBalance(w, qty, qty); } else { bal = createBitcoinBalance(w, qty, BigInteger.ZERO); } System.out.println(">>> bal = " + bal.toString()); balancesList.add(bal); continue; } // Other assets hasAssets = true; if (qty.compareTo(BigInteger.ZERO)>0) { JSONRPCBalance bal = null; if (isSelectable) { bal = createAssetBalance(w, assetID, qty, qty); } else { bal = createAssetBalance(w, assetID, qty, BigInteger.ZERO); } balancesList.add(bal); } } JSONRPCBalance[] balancesArray = balancesList.toArray(new JSONRPCBalance[0]); String scriptPubKeyHexString = Utils.bytesToHexString( txout.getScriptBytes() ); // Build the object to return JSONRPCUnspentTransactionOutput utxo = new JSONRPCUnspentTransactionOutput(); utxo.setTxid(tx.getHashAsString()); utxo.setVout((long)cstxout.getIndex()); utxo.setScriptPubKey(scriptPubKeyHexString); utxo.setAmounts(balancesArray); //new JSONRPCBalance[0]); utxo.setConfirmations((long)numConfirmations); utxo.setBitcoin_address(btcAddress); if (hasAssets) { String sparkAddress = null; // First let's see if we have stored the recipient in our map and use it instead // of generating a new one from bitcoin address try { if (csAddressMap != null) { String spk = csAddressMap.get(tx.getHashAsString()); String btc = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(spk); if (btc.equals(btcAddress)) { sparkAddress = spk; } } } catch (Exception e) { } if (sparkAddress == null) { sparkAddress = CSMiscUtils.convertBitcoinAddressToCoinSparkAddress(btcAddress); } utxo.setCoinspark_address(sparkAddress); } utxo.setAmounts(balancesArray); resultList.add(utxo); } JSONRPCUnspentTransactionOutput[] resultArray = resultList.toArray(new JSONRPCUnspentTransactionOutput[0]); return resultArray; } /** * Create a JSONRPCBalance object for Bitcoin asset * @param w * @return */ private JSONRPCBalance createBitcoinBalance(Wallet w) { BigInteger rawBalanceSatoshi = w.getBalance(Wallet.BalanceType.ESTIMATED); BigInteger rawSpendableSatoshi = w.getBalance(Wallet.BalanceType.AVAILABLE); return createBitcoinBalance(w, rawSpendableSatoshi, rawBalanceSatoshi); } /** * Create a JSONRPCBalance object for Bitcoin asset * @param w * @param rawBalanceSatoshi In BitcoinJ terms, this is the estimated total balance * @param rawSpendableSatoshi In BitcoinJ terms, this is the available amount to spend * @return */ private JSONRPCBalance createBitcoinBalance(Wallet w, BigInteger rawBalanceSatoshi, BigInteger rawSpendableSatoshi) { BigDecimal rawBalanceBTC = new BigDecimal(rawBalanceSatoshi).divide(new BigDecimal(Utils.COIN)); BigDecimal rawSpendableBTC = new BigDecimal(rawSpendableSatoshi).divide(new BigDecimal(Utils.COIN)); String rawBalanceDisplay = Utils.bitcoinValueToFriendlyString(rawBalanceSatoshi) + " BTC"; String rawSpendableDisplay = Utils.bitcoinValueToFriendlyString(rawBalanceSatoshi) + " BTC"; JSONRPCBalanceAmount bitcoinBalanceAmount = new JSONRPCBalanceAmount(rawBalanceSatoshi.longValue(), rawBalanceBTC.doubleValue(), rawBalanceDisplay); JSONRPCBalanceAmount bitcoinSpendableAmount = new JSONRPCBalanceAmount(rawSpendableSatoshi.longValue(), rawSpendableBTC.doubleValue(), rawSpendableDisplay); JSONRPCBalance btcAssetBalance = new JSONRPCBalance(); btcAssetBalance.setAsset_ref("bitcoin"); btcAssetBalance.setBalance(bitcoinBalanceAmount); btcAssetBalance.setSpendable(bitcoinSpendableAmount); btcAssetBalance.setVisible(true); btcAssetBalance.setValid(true); return btcAssetBalance; } /** * Create and populate a JSONRPCBalance object given an assetID and balance * @param w * @param assetID * @param totalRaw * @param spendableRaw * @return */ private JSONRPCBalance createAssetBalance(Wallet w, int assetID, BigInteger totalRaw, BigInteger spendableRaw) { //Wallet.CoinSpark.AssetBalance assetBalance; CSAsset asset = w.CS.getAsset(assetID); String name = asset.getName(); String nameShort = asset.getNameShort(); if (name == null) { CoinSparkGenesis genesis = asset.getGenesis(); if (genesis != null) { name = "Asset from " + genesis.getDomainName(); nameShort = name; } else { // No genesis block found yet name = "Other Asset"; nameShort = "Other Asset"; } } String assetRef = CSMiscUtils.getHumanReadableAssetRef(asset); if (assetRef == null) { assetRef = "Awaiting new asset confirmation..."; } Double spendableQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, spendableRaw).doubleValue(); String spendableDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, spendableRaw); JSONRPCBalanceAmount spendableAmount = new JSONRPCBalanceAmount(spendableRaw.longValue(), spendableQty, spendableDisplay); Double balanceQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, totalRaw).doubleValue(); String balanceDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, totalRaw); JSONRPCBalanceAmount balanceAmount = new JSONRPCBalanceAmount(totalRaw.longValue(), balanceQty, balanceDisplay); JSONRPCBalance ab = new JSONRPCBalance(); ab.setAsset_ref(assetRef); ab.setBalance(balanceAmount); ab.setSpendable(spendableAmount); ab.setName(name); ab.setName_short(nameShort); String domain = CSMiscUtils.getDomainHost(asset.getDomainURL()); ab.setDomain(domain); ab.setUrl(asset.getAssetWebPageURL()); ab.setIssuer(asset.getIssuer()); ab.setDescription(asset.getDescription()); ab.setUnits(asset.getUnits()); ab.setMultiple(asset.getMultiple()); ab.setStatus(CSMiscUtils.getHumanReadableAssetState(asset.getAssetState())); boolean isValid = (asset.getAssetState() == CSAsset.CSAssetState.VALID); // FIXME: Check num confirms too? ab.setValid(isValid); Date validCheckedDate = asset.getValidChecked(); if (validCheckedDate != null) { ab.setChecked_unixtime(validCheckedDate.getTime() / 1000L); } ab.setContract_url(asset.getContractUrl()); String contractPath = asset.getContractPath(); if (contractPath != null) { String appDirPath = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory(); File file = new File(contractPath); File dir = new File(appDirPath); try { URI absolute = file.toURI(); URI base = dir.toURI(); URI relative = base.relativize(absolute); contractPath = relative.getPath(); } catch (Exception e) { // do nothing, if error, just use full contractPath } } ab.setContract_file(contractPath); ab.setGenesis_txid(asset.getGenTxID()); Date creationDate = asset.getDateCreation(); if (creationDate != null) { ab.setAdded_unixtime(creationDate.getTime() / 1000L); } // 3 October 2014, 1:47 am SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, h:mm"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // CoinSpark asset web page shows GMT/UTC. SimpleDateFormat ampmdf = new SimpleDateFormat(" a"); // by default is uppercase and we need lower to match website Date issueDate = asset.getIssueDate(); if (issueDate != null) { ab.setIssue_date(sdf.format(issueDate) + ampmdf.format(issueDate).toLowerCase()); ab.setIssue_unixtime(issueDate.getTime() / 1000L); } // Never expires Date expiryDate = asset.getExpiryDate(); if (expiryDate != null) { ab.setExpiry_date(sdf.format(expiryDate) + ampmdf.format(expiryDate).toLowerCase()); ab.setExpiry_unixtime(expiryDate.getTime() / 1000L); } ab.setTracker_urls(asset.getCoinsparkTrackerUrls()); ab.setIcon_url(asset.getIconUrl()); ab.setImage_url(asset.getImageUrl()); ab.setFeed_url(asset.getFeedUrl()); ab.setRedemption_url(asset.getRedemptionUrl()); ab.setVisible(asset.isVisible()); return ab; } @Override public JSONRPCBalance[] listbalances(String walletID, Boolean onlyVisible) throws com.bitmechanic.barrister.RpcException { log.info("LIST BALANCES"); log.info("wallet name = " + walletID); log.info("only visible = " + onlyVisible); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } ArrayList<JSONRPCBalance> resultList = new ArrayList<>(); // Add entry for BTC balances BigInteger rawBalanceSatoshi = w.getBalance(Wallet.BalanceType.ESTIMATED); BigInteger rawSpendableSatoshi = w.getBalance(Wallet.BalanceType.AVAILABLE); BigDecimal rawBalanceBTC = new BigDecimal(rawBalanceSatoshi).divide(new BigDecimal(Utils.COIN)); BigDecimal rawSpendableBTC = new BigDecimal(rawSpendableSatoshi).divide(new BigDecimal(Utils.COIN)); String rawBalanceDisplay = Utils.bitcoinValueToFriendlyString(rawBalanceSatoshi) + " BTC"; String rawSpendableDisplay = Utils.bitcoinValueToFriendlyString(rawBalanceSatoshi) + " BTC"; JSONRPCBalanceAmount bitcoinBalanceAmount = new JSONRPCBalanceAmount(rawBalanceSatoshi.longValue(), rawBalanceBTC.doubleValue(), rawBalanceDisplay); JSONRPCBalanceAmount bitcoinSpendableAmount = new JSONRPCBalanceAmount(rawSpendableSatoshi.longValue(), rawSpendableBTC.doubleValue(), rawSpendableDisplay); JSONRPCBalance btcAssetBalance = new JSONRPCBalance(); btcAssetBalance.setAsset_ref("bitcoin"); btcAssetBalance.setBalance(bitcoinBalanceAmount); btcAssetBalance.setSpendable(bitcoinSpendableAmount); btcAssetBalance.setVisible(true); btcAssetBalance.setValid(true); resultList.add(btcAssetBalance); int[] assetIDs = w.CS.getAssetIDs(); int n = 0; if (assetIDs!=null) { n = assetIDs.length; } Wallet.CoinSpark.AssetBalance assetBalance; for (int i=0; i<n; i++) { int id = assetIDs[i]; if (id==0) continue; CSAsset asset = w.CS.getAsset(id); if (asset==null) continue; if (onlyVisible && !asset.isVisible()) continue; String name=asset.getName(); String nameShort=asset.getNameShort(); if (name == null) { CoinSparkGenesis genesis = asset.getGenesis(); if (genesis!=null) { name = "Asset from " + genesis.getDomainName(); nameShort = name; } else { // No genesis block found yet name = "Other Asset"; nameShort = "Other Asset"; } } String assetRef = CSMiscUtils.getHumanReadableAssetRef(asset); if (assetRef==null) assetRef = "Awaiting new asset confirmation..."; assetBalance = w.CS.getAssetBalance(id); Long spendableRaw = assetBalance.spendable.longValue(); Double spendableQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, assetBalance.spendable).doubleValue(); String spendableDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, assetBalance.spendable); JSONRPCBalanceAmount spendableAmount = new JSONRPCBalanceAmount(spendableRaw, spendableQty, spendableDisplay); Long balanceRaw = assetBalance.total.longValue(); Double balanceQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, assetBalance.total).doubleValue(); String balanceDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, assetBalance.total); JSONRPCBalanceAmount balanceAmount = new JSONRPCBalanceAmount(balanceRaw, balanceQty, balanceDisplay); JSONRPCBalance ab = new JSONRPCBalance(); ab.setAsset_ref(assetRef); ab.setBalance(balanceAmount); ab.setSpendable(spendableAmount); ab.setName(name); ab.setName_short(nameShort); String domain = CSMiscUtils.getDomainHost(asset.getDomainURL()); ab.setDomain(domain); ab.setUrl(asset.getAssetWebPageURL()); ab.setIssuer(asset.getIssuer()); ab.setDescription(asset.getDescription()); ab.setUnits(asset.getUnits()); ab.setMultiple(asset.getMultiple()); ab.setStatus(CSMiscUtils.getHumanReadableAssetState(asset.getAssetState())); boolean isValid = (asset.getAssetState()==CSAsset.CSAssetState.VALID); // FIXME: Check num confirms too? ab.setValid(isValid); Date validCheckedDate = asset.getValidChecked(); if (validCheckedDate!=null) { ab.setChecked_unixtime(validCheckedDate.getTime()/1000L); } ab.setContract_url(asset.getContractUrl()); String contractPath = asset.getContractPath(); if (contractPath!=null) { String appDirPath = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory(); File file = new File(contractPath); File dir = new File(appDirPath); try { URI absolute = file.toURI(); URI base = dir.toURI(); URI relative = base.relativize(absolute); contractPath = relative.getPath(); } catch (Exception e) { // do nothing, if error, just use full contractPath } } ab.setContract_file(contractPath); ab.setGenesis_txid(asset.getGenTxID()); Date creationDate = asset.getDateCreation(); if (creationDate != null) { ab.setAdded_unixtime(creationDate.getTime()/1000L); } // 3 October 2014, 1:47 am SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, h:mm"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // CoinSpark asset web page shows GMT/UTC. SimpleDateFormat ampmdf = new SimpleDateFormat(" a"); // by default is uppercase and we need lower to match website Date issueDate = asset.getIssueDate(); if (issueDate != null) { ab.setIssue_date(sdf.format(issueDate) + ampmdf.format(issueDate).toLowerCase()); ab.setIssue_unixtime(issueDate.getTime()/1000L); } // Never expires Date expiryDate = asset.getExpiryDate(); if (expiryDate != null) { ab.setExpiry_date(sdf.format(expiryDate) + ampmdf.format(expiryDate).toLowerCase() ); ab.setExpiry_unixtime(expiryDate.getTime()/1000L); } ab.setTracker_urls(asset.getCoinsparkTrackerUrls()); ab.setIcon_url(asset.getIconUrl()); ab.setImage_url(asset.getImageUrl()); ab.setFeed_url(asset.getFeedUrl()); ab.setRedemption_url(asset.getRedemptionUrl()); ab.setVisible(asset.isVisible()); resultList.add(ab); } JSONRPCBalance[] resultArray = resultList.toArray(new JSONRPCBalance[0]); return resultArray; } @Override public synchronized String sendbitcoin(String walletID, String address, Double amount) throws com.bitmechanic.barrister.RpcException { log.info("SEND BITCOIN"); log.info("wallet name = " + walletID); log.info("address = " + address); log.info("amount = " + amount); Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } if (amount<=0.0) { JSONRPCError.SEND_BITCOIN_AMOUNT_TOO_LOW.raiseRpcException(); } String bitcoinAddress = address; if (address.startsWith("s")) { bitcoinAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address); if (bitcoinAddress==null) { JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(); } } boolean isValid = CSMiscUtils.validateBitcoinAddress(bitcoinAddress, controller); if (!isValid) { JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException(); } String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); if (wd.isBusy()) { JSONRPCError.WALLEY_IS_BUSY.raiseRpcException(); } else { wd.setBusy(true); wd.setBusyTaskKey("jsonrpc.busy.sendbitcoin"); this.controller.fireWalletBusyChange(true); } Transaction sendTransaction = null; boolean sendValidated = false; boolean sendSuccessful = false; String sendTxHash = null; try { String sendAmount = amount.toString(); // Create a SendRequest. Address sendAddressObject; sendAddressObject = new Address(controller.getModel().getNetworkParameters(), bitcoinAddress); Wallet.SendRequest sendRequest = Wallet.SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount)); // SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount), 6, new BigInteger("10000"),1); sendRequest.ensureMinRequiredFee = true; sendRequest.fee = BigInteger.ZERO; sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT; // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form. // Complete it (which works out the fee) but do not sign it yet. log.info("Just about to complete the tx (and calculate the fee)..."); w.completeTx(sendRequest, false); sendValidated = true; log.info("The fee after completing the transaction was " + sendRequest.fee); // Let's do it for real now. sendTransaction = this.controller.getMultiBitService().sendCoins(wd, sendRequest, null); if (sendTransaction == null) { // a null transaction returned indicates there was not // enough money (in spite of our validation) JSONRPCError.SEND_BITCOIN_INSUFFICIENT_MONEY.raiseRpcException(); } else { sendSuccessful = true; sendTxHash = sendTransaction.getHashAsString(); log.info("Sent transaction was:\n" + sendTransaction.toString()); } if (sendSuccessful) { // There is enough money. /* If sending assets or BTC to a coinspark address, record transaction id --> coinspark address, into hashmap so we can use when displaying transactions */ if (address.startsWith("s")) { java.util.Map<String, String> m = SparkBitMapDB.INSTANCE.getSendTransactionToCoinSparkAddressMap(); if (m != null) { m.put(sendTxHash, address); SparkBitMapDB.INSTANCE.getMapDB().commit(); } } } else { // There is not enough money } // } catch (WrongNetworkException e1) { // } catch (AddressFormatException e1) { // } catch (KeyCrypterException e1) { } catch (InsufficientMoneyException e) { JSONRPCError.SEND_BITCOIN_INSUFFICIENT_MONEY.raiseRpcException(); } catch (Exception e) { JSONRPCError.throwAsRpcException("Could not send bitcoin due to error", e); } finally { // Save the wallet. try { this.controller.getFileHandler().savePerWalletModelData(wd, false); } catch (WalletSaveException e) { // log.error(e.getMessage(), e); } if (sendSuccessful) { // This returns immediately if rpcsendassettimeout is 0. JSONRPCController.INSTANCE.waitForTxSelectable(sendTransaction); // JSONRPCController.INSTANCE.waitForTxBroadcast(sendTxHash); } // Declare that wallet is no longer busy with the task. wd.setBusyTaskKey(null); wd.setBusy(false); this.controller.fireWalletBusyChange(false); } if (sendSuccessful) { controller.fireRecreateAllViews(false); } return sendTxHash; } @Override public synchronized String sendasset(String walletID, String address, String assetRef, Double quantity, Boolean senderPays) throws com.bitmechanic.barrister.RpcException { log.info("SEND ASSET"); log.info("wallet name = " + walletID); log.info("address = " + address); log.info("asset ref = " + assetRef); log.info("quantity = " + quantity); log.info("sender pays = " + senderPays); String sendTxHash = null; boolean sendValidated = false; boolean sendSuccessful = false; Wallet w = getWalletForWalletName(walletID); if (w==null) { JSONRPCError.WALLET_NOT_FOUND.raiseRpcException(); } if (quantity<=0.0) { JSONRPCError.SEND_ASSET_AMOUNT_TOO_LOW.raiseRpcException(); } String bitcoinAddress = address; if (!address.startsWith("s")) { JSONRPCError.ADDRESS_NOT_COINSPARK_ADDRESS.raiseRpcException(); } else { bitcoinAddress = CSMiscUtils.getBitcoinAddressFromCoinSparkAddress(address); if (bitcoinAddress==null) { JSONRPCError.COINSPARK_ADDRESS_INVALID.raiseRpcException(); } CoinSparkAddress csa = CSMiscUtils.decodeCoinSparkAddress(address); if (!CSMiscUtils.canSendAssetsToCoinSparkAddress(csa)) { JSONRPCError.COINSPARK_ADDRESS_MISSING_ASSET_FLAG.raiseRpcException(); } } boolean isValid = CSMiscUtils.validateBitcoinAddress(bitcoinAddress, controller); if (!isValid) { JSONRPCError.BITCOIN_ADDRESS_INVALID.raiseRpcException(); } String filename = getFullPathForWalletName(walletID); final WalletData wd = this.controller.getModel().getPerWalletModelDataByWalletFilename(filename); if (wd.isBusy()) { JSONRPCError.WALLEY_IS_BUSY.raiseRpcException(); } else { wd.setBusy(true); wd.setBusyTaskKey("jsonrpc.busy.sendasset"); this.controller.fireWalletBusyChange(true); } Transaction sendTransaction = null; try { // -- boilerplate ends here.... CSAsset asset = getAssetForAssetRefString(w, assetRef); if (asset==null) { if (isAssetRefValid(assetRef)) { JSONRPCError.ASSETREF_NOT_FOUND.raiseRpcException(); } else { JSONRPCError.ASSETREF_INVALID.raiseRpcException(); } } if (asset.getAssetState()!=CSAsset.CSAssetState.VALID) { if (!CSMiscUtils.canSendInvalidAsset(controller)) { JSONRPCError.ASSET_STATE_INVALID.raiseRpcException(); } } // Check number of confirms int lastHeight = w.getLastBlockSeenHeight(); CoinSparkAssetRef assetReference = asset.getAssetReference(); if (assetReference != null) { final int blockIndex = (int) assetReference.getBlockNum(); final int numConfirmations = lastHeight - blockIndex + 1; // 0 means no confirmation, 1 is yes for sa int threshold = NUMBER_OF_CONFIRMATIONS_TO_SEND_ASSET_THRESHOLD; // FIXME: REMOVE/COMMENT OUT BEFORE RELEASE? String sendAssetWithJustOneConfirmation = controller.getModel().getUserPreference("sendAssetWithJustOneConfirmation"); if (Boolean.TRUE.toString().equals(sendAssetWithJustOneConfirmation)) { threshold = 1; } //System.out.println(">>>> " + CSMiscUtils.getHumanReadableAssetRef(asset) + " num confirmations " + numConfirmations + ", threshold = " + threshold); if (numConfirmations < threshold) { JSONRPCError.ASSET_NOT_CONFIRMED.raiseRpcException(); } } String displayQtyString = new BigDecimal(quantity).toPlainString(); BigInteger assetAmountRawUnits = CSMiscUtils.getRawUnitsFromDisplayString(asset, displayQtyString); int assetID = asset.getAssetID(); BigInteger spendableAmount = w.CS.getAssetBalance(assetID).spendable; log.info("Want to send: " + assetAmountRawUnits + " , AssetID=" + assetID + ", total="+w.CS.getAssetBalance(assetID).total + ", spendable=" + w.CS.getAssetBalance(assetID).spendable ); String sendAmount = Utils.bitcoinValueToPlainString(BitcoinModel.COINSPARK_SEND_MINIMUM_AMOUNT); CoinSparkGenesis genesis = asset.getGenesis(); long desiredRawUnits = assetAmountRawUnits.longValue(); short chargeBasisPoints = genesis.getChargeBasisPoints(); long rawFlatChargeAmount = genesis.getChargeFlat(); boolean chargeExists = ( rawFlatChargeAmount>0 || chargeBasisPoints>0 ); if (chargeExists) { if (senderPays) { long x = genesis.calcGross(desiredRawUnits); assetAmountRawUnits = new BigInteger(String.valueOf(x)); } else { // We don't have to do anything if recipient pays, just send gross amount. // calcNet() returns what the recipient will receive, but it's not what we send. } } if (assetAmountRawUnits.compareTo(spendableAmount) > 0) { JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException(); } // Create a SendRequest. Address sendAddressObject; String sendAddress = bitcoinAddress; sendAddressObject = new Address(controller.getModel().getNetworkParameters(), sendAddress); //SendRequest sendRequest = SendRequest.to(sendAddressObject, Utils.toNanoCoins(sendAmount)); //public static SendRequest to(Address destination,BigInteger value,int assetID, BigInteger assetValue,int split) { //BigInteger assetAmountRawUnits = new BigInteger(assetAmount); BigInteger bitcoinAmountSatoshis = Utils.toNanoCoins(sendAmount); Wallet.SendRequest sendRequest = Wallet.SendRequest.to(sendAddressObject, bitcoinAmountSatoshis, assetID, assetAmountRawUnits, 1); sendRequest.ensureMinRequiredFee = true; sendRequest.fee = BigInteger.ZERO; sendRequest.feePerKb = BitcoinModel.SEND_FEE_PER_KB_DEFAULT; // Note - Request is populated with the AES key in the SendBitcoinNowAction after the user has entered it on the SendBitcoinConfirm form. // Complete it (which works out the fee) but do not sign it yet. log.info("Just about to complete the tx (and calculate the fee)..."); // there is enough money, so let's do it for real now w.completeTx(sendRequest, false); sendValidated = true; log.info("The fee after completing the transaction was " + sendRequest.fee); // Let's do it for real now. sendTransaction = this.controller.getMultiBitService().sendCoins(wd, sendRequest, null); if (sendTransaction == null) { // a null transaction returned indicates there was not // enough money (in spite of our validation) JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException(); } else { sendSuccessful = true; sendTxHash = sendTransaction.getHashAsString(); } if (sendSuccessful) { // There is enough money. /* If sending assets or BTC to a coinspark address, record transaction id --> coinspark address, into hashmap so we can use when displaying transactions */ if (address.startsWith("s")) { java.util.Map<String, String> m = SparkBitMapDB.INSTANCE.getSendTransactionToCoinSparkAddressMap(); if (m != null) { m.put(sendTxHash, address); SparkBitMapDB.INSTANCE.getMapDB().commit(); } } } else { // There is not enough money } //--- bolilerplate begins... } catch (InsufficientMoneyException ime) { JSONRPCError.ASSET_INSUFFICIENT_BALANCE.raiseRpcException(); } catch (com.bitmechanic.barrister.RpcException e) { throw(e); } catch (Exception e) { JSONRPCError.throwAsRpcException("Could not send asset due to error: " , e); } finally { // Save the wallet. try { this.controller.getFileHandler().savePerWalletModelData(wd, false); } catch (WalletSaveException e) { // log.error(e.getMessage(), e); } if (sendSuccessful) { // This returns immediately if rpcsendassettimeout is 0. JSONRPCController.INSTANCE.waitForTxSelectable(sendTransaction); // JSONRPCController.INSTANCE.waitForTxBroadcast(sendTxHash); } // Declare that wallet is no longer busy with the task. wd.setBusyTaskKey(null); wd.setBusy(false); this.controller.fireWalletBusyChange(false); } if (sendSuccessful) { controller.fireRecreateAllViews(false); } return sendTxHash; } }
Removed debug code. Refactored listbalances to use new createAssetBalance() and createBitcoinBalance() methods.
src/main/java/org/sparkbit/jsonrpc/SparkBitJSONRPCServiceImpl.java
Removed debug code. Refactored listbalances to use new createAssetBalance() and createBitcoinBalance() methods.
<ide><path>rc/main/java/org/sparkbit/jsonrpc/SparkBitJSONRPCServiceImpl.java <ide> // Get the bitcoin and asset balances on this utxo <ide> Map<Integer,CSBalance> balances = (Map<Integer,CSBalance>) entry.getValue(); <ide> <del> // FIXME: Debugging <del> log.info(">>>> balances = " + balances); <del> if (balances.isEmpty()) { <del> Map<Integer, BigInteger> receiveMap = w.CS.getAssetsSentToMe(tx); <del> Map<Integer, BigInteger> sendMap = w.CS.getAssetsSentFromMe(tx); <del> log.info(">>>> ...receiveMap = " + receiveMap); <del> log.info(">>>> ...sendMap = " + sendMap); <del> } <del> // END FIXME: <del> <ide> boolean hasAssets = false; <ide> ArrayList<JSONRPCBalance> balancesList = new ArrayList<>(); <ide> <ide> ArrayList<JSONRPCBalance> resultList = new ArrayList<>(); <ide> <ide> // Add entry for BTC balances <del> BigInteger rawBalanceSatoshi = w.getBalance(Wallet.BalanceType.ESTIMATED); <del> BigInteger rawSpendableSatoshi = w.getBalance(Wallet.BalanceType.AVAILABLE); <del> BigDecimal rawBalanceBTC = new BigDecimal(rawBalanceSatoshi).divide(new BigDecimal(Utils.COIN)); <del> BigDecimal rawSpendableBTC = new BigDecimal(rawSpendableSatoshi).divide(new BigDecimal(Utils.COIN)); <del> String rawBalanceDisplay = Utils.bitcoinValueToFriendlyString(rawBalanceSatoshi) + " BTC"; <del> String rawSpendableDisplay = Utils.bitcoinValueToFriendlyString(rawBalanceSatoshi) + " BTC"; <del> <del> JSONRPCBalanceAmount bitcoinBalanceAmount = new JSONRPCBalanceAmount(rawBalanceSatoshi.longValue(), rawBalanceBTC.doubleValue(), rawBalanceDisplay); <del> JSONRPCBalanceAmount bitcoinSpendableAmount = new JSONRPCBalanceAmount(rawSpendableSatoshi.longValue(), rawSpendableBTC.doubleValue(), rawSpendableDisplay); <del> JSONRPCBalance btcAssetBalance = new JSONRPCBalance(); <del> btcAssetBalance.setAsset_ref("bitcoin"); <del> btcAssetBalance.setBalance(bitcoinBalanceAmount); <del> btcAssetBalance.setSpendable(bitcoinSpendableAmount); <del> btcAssetBalance.setVisible(true); <del> btcAssetBalance.setValid(true); <add> JSONRPCBalance btcAssetBalance = createBitcoinBalance(w); <ide> resultList.add(btcAssetBalance); <ide> <ide> <ide> <ide> String assetRef = CSMiscUtils.getHumanReadableAssetRef(asset); <ide> if (assetRef==null) assetRef = "Awaiting new asset confirmation..."; <del> <add> <ide> assetBalance = w.CS.getAssetBalance(id); <add> <add> JSONRPCBalance ab = createAssetBalance(w, id, assetBalance.total, assetBalance.spendable); <add>/* <add> <ide> Long spendableRaw = assetBalance.spendable.longValue(); <ide> Double spendableQty = CSMiscUtils.getDisplayUnitsForRawUnits(asset, assetBalance.spendable).doubleValue(); <ide> String spendableDisplay = CSMiscUtils.getFormattedDisplayStringForRawUnits(asset, assetBalance.spendable); <ide> ab.setFeed_url(asset.getFeedUrl()); <ide> ab.setRedemption_url(asset.getRedemptionUrl()); <ide> ab.setVisible(asset.isVisible()); <add> */ <ide> resultList.add(ab); <ide> } <ide>
Java
mit
ed4a2c4c8901367c0aadd4e20b82634c36fa18b8
0
leMaik/RpgPlus
package de.craften.plugins.rpgplus.components.entitymanager; import de.craften.plugins.managedentities.ManagedEntityBase; import de.craften.plugins.managedentities.behavior.SecondNameBehavior; import de.craften.plugins.managedentities.behavior.VisibleNameBehavior; import de.craften.plugins.managedentities.util.nms.NmsEntityUtil; import org.bukkit.Location; import org.bukkit.entity.*; /** * A basic managed entity without any special logic. */ public abstract class RpgPlusEntity<T extends Entity> extends ManagedEntityBase<T> { private boolean isTakingDamage = true; private boolean nameVisible = true; public RpgPlusEntity(Location location) { super(location); addBehavior(new VisibleNameBehavior()); addBehavior(new SecondNameBehavior()); } @Override public void spawn() { super.spawn(); if (getEntity() instanceof LivingEntity && !isTakingDamage) { NmsEntityUtil.setInvulnerable((LivingEntity) getEntity(), true); } } public String getName() { return getProperty(VisibleNameBehavior.NAME_PROPERTY_KEY); } public void setName(String name) { setProperty(VisibleNameBehavior.NAME_PROPERTY_KEY, name); } public String getSecondName() { return getProperty(SecondNameBehavior.NAME_PROPERTY_KEY); } public void setSecondName(String secondName) { setProperty(SecondNameBehavior.NAME_PROPERTY_KEY, secondName); } public boolean isTakingDamage() { return isTakingDamage; } public void setTakingDamage(boolean isTakingDamage) { this.isTakingDamage = isTakingDamage; if (getEntity() instanceof LivingEntity) { NmsEntityUtil.setInvulnerable((LivingEntity) getEntity(), !isTakingDamage); } } public boolean isNameVisible() { return nameVisible; } public void setNameVisible(boolean nameVisible) { if (nameVisible != this.nameVisible) { this.nameVisible = nameVisible; if (nameVisible) { removeBehavior(getBehaviors(VisibleNameBehavior.class).iterator().next()); } else { addBehavior(new VisibleNameBehavior()); } } } public Object getTarget() { Entity entity = getEntity(); if (entity instanceof Creature) { return ((Creature) entity).getTarget(); } return null; } public void setTarget(Player player) { Entity entity = getEntity(); if (entity instanceof Creature) { ((Monster) entity).setTarget(player); } //TODO remember the target if the entity is not spawned yet } @Override public void teleport(Location location) { Location old = getLocation(); if (old != null) { super.teleport(location.clone().setDirection(location.toVector().subtract(old.toVector()))); } else { super.teleport(location); } } }
src/main/java/de/craften/plugins/rpgplus/components/entitymanager/RpgPlusEntity.java
package de.craften.plugins.rpgplus.components.entitymanager; import de.craften.plugins.managedentities.ManagedEntityBase; import de.craften.plugins.managedentities.behavior.SecondNameBehavior; import de.craften.plugins.managedentities.behavior.VisibleNameBehavior; import org.bukkit.Location; import org.bukkit.entity.Creature; import org.bukkit.entity.Entity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; /** * A basic managed entity without any special logic. */ public abstract class RpgPlusEntity<T extends Entity> extends ManagedEntityBase<T> { private boolean isTakingDamage = true; private boolean nameVisible = true; public RpgPlusEntity(Location location) { super(location); addBehavior(new VisibleNameBehavior()); addBehavior(new SecondNameBehavior()); } public String getName() { return getProperty(VisibleNameBehavior.NAME_PROPERTY_KEY); } public void setName(String name) { setProperty(VisibleNameBehavior.NAME_PROPERTY_KEY, name); } public String getSecondName() { return getProperty(SecondNameBehavior.NAME_PROPERTY_KEY); } public void setSecondName(String secondName) { setProperty(SecondNameBehavior.NAME_PROPERTY_KEY, secondName); } public boolean isTakingDamage() { return isTakingDamage; } public void setTakingDamage(boolean isTakingDamage) { this.isTakingDamage = isTakingDamage; //TODO this has no effect right now } public boolean isNameVisible() { return nameVisible; } public void setNameVisible(boolean nameVisible) { if (nameVisible != this.nameVisible) { this.nameVisible = nameVisible; if (nameVisible) { removeBehavior(getBehaviors(VisibleNameBehavior.class).iterator().next()); } else { addBehavior(new VisibleNameBehavior()); } } } public Object getTarget() { Entity entity = getEntity(); if (entity instanceof Creature) { return ((Creature) entity).getTarget(); } return null; } public void setTarget(Player player) { Entity entity = getEntity(); if (entity instanceof Creature) { ((Monster) entity).setTarget(player); } //TODO remember the target if the entity is not spawned yet } @Override public void teleport(Location location) { Location old = getLocation(); if (old != null) { super.teleport(location.clone().setDirection(location.toVector().subtract(old.toVector()))); } else { super.teleport(location); } } }
Make invulnerable entities actually invulnerable.
src/main/java/de/craften/plugins/rpgplus/components/entitymanager/RpgPlusEntity.java
Make invulnerable entities actually invulnerable.
<ide><path>rc/main/java/de/craften/plugins/rpgplus/components/entitymanager/RpgPlusEntity.java <ide> import de.craften.plugins.managedentities.ManagedEntityBase; <ide> import de.craften.plugins.managedentities.behavior.SecondNameBehavior; <ide> import de.craften.plugins.managedentities.behavior.VisibleNameBehavior; <add>import de.craften.plugins.managedentities.util.nms.NmsEntityUtil; <ide> import org.bukkit.Location; <del>import org.bukkit.entity.Creature; <del>import org.bukkit.entity.Entity; <del>import org.bukkit.entity.Monster; <del>import org.bukkit.entity.Player; <add>import org.bukkit.entity.*; <ide> <ide> /** <ide> * A basic managed entity without any special logic. <ide> <ide> addBehavior(new VisibleNameBehavior()); <ide> addBehavior(new SecondNameBehavior()); <add> } <add> <add> @Override <add> public void spawn() { <add> super.spawn(); <add> <add> if (getEntity() instanceof LivingEntity && !isTakingDamage) { <add> NmsEntityUtil.setInvulnerable((LivingEntity) getEntity(), true); <add> } <ide> } <ide> <ide> public String getName() { <ide> <ide> public void setTakingDamage(boolean isTakingDamage) { <ide> this.isTakingDamage = isTakingDamage; <del> //TODO this has no effect right now <add> <add> if (getEntity() instanceof LivingEntity) { <add> NmsEntityUtil.setInvulnerable((LivingEntity) getEntity(), !isTakingDamage); <add> } <ide> } <ide> <ide> public boolean isNameVisible() {
Java
lgpl-2.1
f05f857bc8704627cb870f03c964e2ce82aa5436
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
/* * jETeL/Clover - Java based ETL application framework. * Copyright (C) 2005-06 Javlin Consulting <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.jetel.component; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.jetel.data.DataField; import org.jetel.data.DataFieldFactory; import org.jetel.data.DataRecord; import org.jetel.data.primitive.Numeric; import org.jetel.data.sequence.Sequence; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.PolicyType; import org.jetel.exception.TransformException; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.file.WcardPattern; import org.jetel.util.primitive.DuplicateKeyMap; import org.jetel.util.string.StringUtils; /** * * Class used for generating data transformation. It has methods for mapping input fields on output fields, assigning * constants, sequence methods and parameter's values to output fields. * * <h4>Patterns for data fields can be given in three ways:</h4> * <ol> * <li> <i>record.field</i> where <i>record</i> is number, name or wild card of input or output record and <i>field</i> * is name, number or wild card of <i>record's</i> data field </li> * <li> <i>${record.field}</i> where <i>record</i> and <i>field</i> have to be as described above</li> * <li> <i>${in/out.record.field}</i> where <i>record</i> and <i>field</i> have to be as described above</li> * </ol> * * <h4>Order of execution/methods call</h4> * <ol> * <li>setGraph()</li> * <li>setFieldPolicy(PolicyType) - default value is STRICT</li> * <li>setUseAlternativeRules(boolean) - default is <b>false</b> * <li>add...Rule(...)<br> .<br> * </li> * <li>deleteRule(...)<br> .<br> * </li> * <li>init()</li> * <li>transform() <i>for each input&amp;output records pair</i></li> * <li><i>optionally</i> getMessage() <i>or</i> signal() <i>or</i> getSemiResult()</li> * <li>finished() * </ol> * * <h4>Example:</h4> * <b>Records:</b> * * <pre> * in: * #0|Name|S-&gt; HELLO * #1|Age|N-&gt;135.0 * #2|City|S-&gt;Some silly longer string. * #3|Born|D-&gt; * #4|Value|d-&gt;-999.0000000000 * * in1: * #0|Name|S-&gt; My name * #1|Age|N-&gt;13.25 * #2|City|S-&gt;Prague * #3|Born|D-&gt;Thu Nov 30 09:54:07 CET 2006 * #4|Value|i-&gt; * out: * #0|Name|B-&gt; * #1|Age|N-&gt; * #2|City|S-&gt; * #3|Born|D-&gt; * #4|Value|d-&gt; * out1: * #0|Name|S-&gt; * #1|Age|d-&gt; * #2|City|S-&gt; * #3|Born|D-&gt; * #4|Value|i-&gt; * </pre> * * <b>Java code:</b> * * <pre> * CustomizedRecordTransform transform = new CustomizedRecordTransform(LogFactory.getLog(this.getClass())); * transform.setGraph(graph); * transform.addFieldToFieldRule(&quot;${1.?a*}&quot;, &quot;${1.*e}&quot;); * transform.addFieldToFieldRule(&quot;*.City&quot;, 0, 2); * transform.addConstantToFieldRule(1, 3, new GregorianCalendar(1973, 3, 23).getTime()); * transform.addConstantToFieldRule(4, &quot;1.111111111&quot;); * transform.addSequenceToFieldRule(&quot;*.Age&quot;, graph.getSequence(&quot;ID&quot;)); * transform.addRule(&quot;out.City&quot;, &quot;${seq.ID.nextString}&quot;); * transform.addParameterToFieldRule(1, 0, &quot;${WORKSPACE}&quot;); * transform.addParameterToFieldRule(1, &quot;City&quot;, &quot;YourCity&quot;); * transform.deleteRule(1, &quot;Age&quot;); * transform.init(properties, new DataRecordMetadata[] { metadata, metadata1 }, new DataRecordMetadata[] { metaOut, * metaOut1 }); * List&lt;String&gt; rules = transform.getRules(); * System.out.println(&quot;Rules:&quot;); * for (Iterator&lt;String&gt; i = rules.iterator(); i.hasNext();) { * System.out.println(i.next()); * } * rules = transform.getResolvedRules(); * System.out.println(&quot;Resolved rules:&quot;); * for (Iterator&lt;String&gt; i = rules.iterator(); i.hasNext();) { * System.out.println(i.next()); * } * List&lt;Integer[]&gt; fields = transform.getFieldsWithoutRules(); * System.out.println(&quot;Fields without rules:&quot;); * Integer[] index; * for (Iterator&lt;Integer[]&gt; i = fields.iterator(); i.hasNext();) { * index = i.next(); * System.out.println(outMatedata[index[0]].getName() + CustomizedRecordTransform.DOT * + outMatedata[index[0]].getField(index[1]).getName()); * } * fields = transform.getNotUsedFields(); * System.out.println(&quot;Not used input fields:&quot;); * for (Iterator&lt;Integer[]&gt; i = fields.iterator(); i.hasNext();) { * index = i.next(); * System.out.println(inMetadata[index[0]].getName() + CustomizedRecordTransform.DOT * + inMetadata[index[0]].getField(index[1]).getName()); * } * transform.transform(new DataRecord[] { record, record1 }, new DataRecord[] { out, out1 }); * System.out.println(record.getMetadata().getName() + &quot;:\n&quot; + record.toString()); * System.out.println(record1.getMetadata().getName() + &quot;:\n&quot; + record1.toString()); * System.out.println(out.getMetadata().getName() + &quot;:\n&quot; + out.toString()); * System.out.println(out1.getMetadata().getName() + &quot;:\n&quot; + out1.toString()); * </pre> * * <b>Output:</b> * * <pre> * Rules: * FIELD_RULE:${1.?a*}=${1.*e} * FIELD_RULE:*.City=0.2 * CONSTANT_RULE:1.3=Apr 23, 1973 * CONSTANT_RULE:0.4=1.111111111 * SEQUENCE_RULE:*.Age=ID * SEQUENCE_RULE:out.City=ID.nextString * PARAMETER_RULE:1.0=${WORKSPACE} * PARAMETER_RULE:1.City=YourCity * DELETE_RULE:1.Age=1.Age * Resolved rules: * out.Age=${seq.ID} * out.City=${seq.ID.nextString} * out.Value=1.111111111 * out1.Name=/home/avackova/workspace * out1.City=London * out1.Born=23-04-1973 * out1.Value=in1.Value * Fields without rules: * out.Name * out.Born * out1.Age * Not used input fields: * in.Name * in.Age * in.City * in.Born * in.Value * in1.Name * in1.Age * in1.City * in1.Born * in: * #0|Name|S-&gt; HELLO * #1|Age|N-&gt;135.0 * #2|City|S-&gt;Some silly longer string. * #3|Born|D-&gt; * #4|Value|d-&gt;-999.0000000000 * * in1: * #0|Name|S-&gt; My name * #1|Age|N-&gt;13.25 * #2|City|S-&gt;Prague * #3|Born|D-&gt;Thu Nov 30 10:40:15 CET 2006 * #4|Value|i-&gt; * * out: * #0|Name|B-&gt; * #1|Age|N-&gt;2.0 * #2|City|S-&gt;1 * #3|Born|D-&gt; * #4|Value|d-&gt;1.1 * * out1: * #0|Name|S-&gt;/home/user/workspace * #1|Age|d-&gt; * #2|City|S-&gt;London * #3|Born|D-&gt;23-04-1973 * #4|Value|i-&gt; * </pre> * * @author avackova ([email protected]) ; (c) JavlinConsulting s.r.o. www.javlinconsulting.cz * * @since Nov 16, 2006 * @see org.jetel.component.RecordTransform * @see org.jetel.component.DataRecordTransform */ public class CustomizedRecordTransform implements RecordTransform { protected Properties parameters; protected DataRecordMetadata[] sourceMetadata; protected DataRecordMetadata[] targetMetadata; protected TransformationGraph graph; protected PolicyType fieldPolicy = PolicyType.STRICT; protected boolean useAlternativeRules = false; protected Log logger; protected String errorMessage; /** * Map "rules" stores rules given by user in following form: key: patternOut value: proper descendant of Rule class */ protected DuplicateKeyMap rules = new DuplicateKeyMap(new LinkedHashMap<String, Rule>()); protected Rule[][] transformMapArray;// rules from "rules" map translated for concrete metadata protected ArrayList<Rule[][]> alternativeTransformMapArrays; protected int[][] order;// order for assigning output fields (important if assigning sequence values) protected ArrayList<Integer[][]> alternativeOrder; protected static final int REC_NO = 0; protected static final int FIELD_NO = 1; protected static final char DOT = '.'; protected static final char COLON = ':'; protected static final char PARAMETER_CHAR = '$'; protected static final String[] WILDCARDS = new String[WcardPattern.WCARD_CHAR.length]; static { for (int i = 0; i < WILDCARDS.length; i++) { WILDCARDS[i] = String.valueOf(WcardPattern.WCARD_CHAR[i]); } } protected final static String PARAM_OPCODE_REGEX = "\\$\\{par\\.(.*)\\}"; protected final static Pattern PARAM_PATTERN = Pattern.compile(PARAM_OPCODE_REGEX); protected final static String SEQ_OPCODE_REGEX = "\\$\\{seq\\.(.*)\\}"; protected final static Pattern SEQ_PATTERN = Pattern.compile(SEQ_OPCODE_REGEX); protected final static String FIELD_OPCODE_REGEX = "\\$\\{in\\.(.*)\\}"; protected final static Pattern FIELD_PATTERN = Pattern.compile(FIELD_OPCODE_REGEX); private Object value; /** * @param logger */ public CustomizedRecordTransform(Log logger) { this.logger = logger; } /** * Mathod for adding field mapping rule * * @param patternOut * output field's pattern * @param patternIn * input field's pattern */ public void addFieldToFieldRule(String patternOut, String patternIn) { rules.put(patternOut, new FieldRule(patternIn)); } /** * Mathod for adding field mapping rule * * @param recNo * output record number * @param fieldNo * output record's field number * @param patternIn * input field's pattern */ public void addFieldToFieldRule(int recNo, int fieldNo, String patternIn) { addFieldToFieldRule(String.valueOf(recNo) + DOT + fieldNo, patternIn); } /** * Mathod for adding field mapping rule * * @param recNo * output record number * @param field * output record's field name * @param patternIn * input field's pattern */ public void addFieldToFieldRule(int recNo, String field, String patternIn) { addFieldToFieldRule(String.valueOf(recNo) + DOT + field, patternIn); } /** * Mathod for adding field mapping rule * * @param fieldNo * output record's field number * @param patternIn * input field's pattern */ public void addFieldToFieldRule(int fieldNo, String patternIn) { addFieldToFieldRule(0, fieldNo, patternIn); } /** * Mathod for adding field mapping rule * * @param patternOut * output fields' pattern * @param recNo * input record's number * @param fieldNo * input record's field number */ public void addFieldToFieldRule(String patternOut, int recNo, int fieldNo) { addFieldToFieldRule(patternOut, String.valueOf(recNo) + DOT + fieldNo); } /** * Mathod for adding field mapping rule * * @param patternOut * output fields' pattern * @param recNo * input record's number * @param field * input record's field name */ public void addFieldToFieldRule(String patternOut, int recNo, String field) { addFieldToFieldRule(patternOut, String.valueOf(recNo) + DOT + field); } /** * Mathod for adding field mapping rule * * @param outRecNo * output record's number * @param outFieldNo * output record's field number * @param inRecNo * input record's number * @param inFieldNo * input record's field number */ public void addFieldToFieldRule(int outRecNo, int outFieldNo, int inRecNo, int inFieldNo) { addFieldToFieldRule(String.valueOf(outRecNo) + DOT + outFieldNo, String.valueOf(inRecNo) + DOT + inFieldNo); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign (can be string representation of any type) */ public void addConstantToFieldRule(String patternOut, String source) { rules.put(patternOut, new ConstantRule(source)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, int value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, long value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, double value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, Date value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, Numeric value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param source * value value to assign (can be string representation of any type) */ public void addConstantToFieldRule(int recNo, int fieldNo, String source) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, source); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, int value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, long value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, double value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, Date value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, Numeric value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param source * value value to assign (can be string representation of any type) */ public void addConstantToFieldRule(int recNo, String field, String source) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, source); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, int value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, long value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, double value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, Date value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, Numeric value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param source * value value to assign (can be string representation of any type) */ public void addConstantToFieldRule(int fieldNo, String source) { addConstantToFieldRule(0, fieldNo, source); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, int value) { addConstantToFieldRule(0, fieldNo, String.valueOf(value)); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, long value) { addConstantToFieldRule(0, fieldNo, String.valueOf(value)); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, double value) { addConstantToFieldRule(0, fieldNo, String.valueOf(value)); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, Date value) { addConstantToFieldRule(0, fieldNo, value); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, Numeric value) { addConstantToFieldRule(0, fieldNo, String.valueOf(value)); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param patternOut * output fields' pattern * @param sequence * sequence ID, optionally with sequence method (can be in form ${seq.seqID}, eg. "MySequence" is the * same as "MySequence.nextIntValue()" or "${seq.MySequence.nextIntValue()}" */ public void addSequenceToFieldRule(String patternOut, String sequence) { String sequenceString = sequence.startsWith("${") ? sequence.substring(sequence.indexOf(DOT) + 1, sequence .length() - 1) : sequence; rules.put(patternOut, new SequenceRule(sequenceString)); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param recNo * output record's number * @param fieldNo * output record's field number * @param sequence * sequence ID, optionally with sequence method (can be in form ${seq.seqID}, eg. "MySequence" is the * same as "MySequence.nextIntValue()" or "${seq.MySequence.nextIntValue()}" */ public void addSequenceToFieldRule(int recNo, int fieldNo, String sequence) { addSequenceToFieldRule(String.valueOf(recNo) + DOT + fieldNo, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param recNo * output record's number * @param field * output record's field name * @param sequence * sequence ID, optionally with sequence method (can be in form ${seq.seqID}, eg. "MySequence" is the * same as "MySequence.nextIntValue()" or "${seq.MySequence.nextIntValue()}" */ public void addSequenceToFieldRule(int recNo, String field, String sequence) { addSequenceToFieldRule(String.valueOf(recNo) + DOT + field, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields in 0th record * * @param fieldNo * output record's field number * @param sequence * sequence ID, optionally with sequence method (can be in form ${seq.seqID}, eg. "MySequence" is the * same as "MySequence.nextIntValue()" or "${seq.MySequence.nextIntValue()}" */ public void addSequenceToFieldRule(int fieldNo, String sequence) { addSequenceToFieldRule(0, fieldNo, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param patternOut * output fields' pattern * @param sequence * sequence for getting value */ public void addSequenceToFieldRule(String patternOut, Sequence sequence) { rules.put(patternOut, new SequenceRule(sequence)); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param recNo * output record's number * @param fieldNo * output record's field number * @param sequence * sequence for getting value */ public void addSequenceToFieldRule(int recNo, int fieldNo, Sequence sequence) { addSequenceToFieldRule(String.valueOf(recNo) + DOT + fieldNo, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param recNo * output record's number * @param field * output record's field name * @param sequence * sequence for getting value */ public void addSequenceToFieldRule(int recNo, String field, Sequence sequence) { addSequenceToFieldRule(String.valueOf(recNo) + DOT + field, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields in 0th output record * * @param fieldNo * output record's field number * @param sequence * sequence for getting value */ public void addSequenceToFieldRule(int fieldNo, Sequence sequence) { addSequenceToFieldRule(0, fieldNo, sequence); } /** * Mathod for adding rule: assigning parameter value to output fields * * @param patternOut * output fields' pattern * @param parameterName * (can be in form ${par.parameterName}) */ public void addParameterToFieldRule(String patternOut, String parameterName) { if (parameterName.indexOf(DOT) > -1) { parameterName = parameterName.substring(parameterName.indexOf(DOT) + 1, parameterName.length() - 1); } rules.put(patternOut, new ParameterRule(parameterName)); } /** * Mathod for adding rule: assigning parameter value to output fields * * @param recNo * output record's number * @param fieldNo * output record's field number * @param parameterName * (can be in form ${par.parameterName}) */ public void addParameterToFieldRule(int recNo, int fieldNo, String parameterName) { addParameterToFieldRule(String.valueOf(recNo) + DOT + fieldNo, parameterName); } /** * Mathod for adding rule: assigning parameter value to output fields * * @param recNo * output record's number * @param field * output record's field name * @param parameterName * (can be in form ${par.parameterName}) */ public void addParameterToFieldRule(int recNo, String field, String parameterName) { addParameterToFieldRule(String.valueOf(recNo) + DOT + field, parameterName); } /** * Mathod for adding rule: assigning parameter value to output fields in 0th output record * * @param fieldNo * output record's field number * @param parameterName * (can be in form ${par.parameterName}) */ public void addParameterToFieldRule(int fieldNo, String parameterName) { addParameterToFieldRule(0, fieldNo, parameterName); } /** * Method for adding rule in CloverETL syntax This method calls proper add....Rule depending on syntax of pattern * * @see org.jetel.util.CodeParser * @param patternOut * output field's pattern * @param pattern * rule for output field as: ${par.parameterName}, ${seq.sequenceID}, * ${in.inRecordPattern.inFieldPattern}. If "pattern" doesn't much to any above, it is regarded as * constant. */ public void addRule(String patternOut, String pattern) { Matcher matcher = PARAM_PATTERN.matcher(pattern); if (matcher.find()) { addParameterToFieldRule(patternOut, pattern); } else { matcher = SEQ_PATTERN.matcher(pattern); if (matcher.find()) { addSequenceToFieldRule(patternOut, pattern); } else { matcher = FIELD_PATTERN.matcher(pattern); if (matcher.find()) { addFieldToFieldRule(patternOut, pattern); } else { addConstantToFieldRule(patternOut, pattern); } } } } /** * This method deletes rule for given fields, which was set before * * @param patternOut * output field pattern for deleting rule */ public void deleteRule(String patternOut) { rules.put(patternOut, new DeleteRule()); } /** * This method deletes rule for given field, which was set before * * @param outRecNo * output record number * @param outFieldNo * output record's field number */ public void deleteRule(int outRecNo, int outFieldNo) { String patternOut = String.valueOf(outRecNo) + DOT + outFieldNo; rules.put(patternOut, new DeleteRule()); } /** * This method deletes rule for given field, which was set before * * @param outRecNo * output record number * @param outField * output record's field name */ public void deleteRule(int outRecNo, String outField) { String patternOut = String.valueOf(outRecNo) + DOT + outField; rules.put(patternOut, new DeleteRule()); } /** * This method deletes rule for given field in 0th output record, which was set before * * @param outFieldNo * output record's field number */ public void deleteRule(int outFieldNo) { String patternOut = String.valueOf(0) + DOT + outFieldNo; rules.put(patternOut, new DeleteRule()); } public void finished() { // TODO Auto-generated method stub } public TransformationGraph getGraph() { return graph; } public String getMessage() { return errorMessage; } public Object getSemiResult() { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see org.jetel.component.RecordTransform#init(java.util.Properties, org.jetel.metadata.DataRecordMetadata[], * org.jetel.metadata.DataRecordMetadata[]) */ public boolean init(Properties parameters, DataRecordMetadata[] sourcesMetadata, DataRecordMetadata[] targetMetadata) throws ComponentNotReadyException { if (sourcesMetadata == null || targetMetadata == null) { return false; } this.parameters = parameters; this.sourceMetadata = sourcesMetadata; this.targetMetadata = targetMetadata; return init(); } /** * Checks if given string contans wild cards * * @see WcardPattern * * @param str * @return */ private boolean containsWCard(String str) { for (int i = 0; i < WILDCARDS.length; i++) { if (str.contains(WILDCARDS[i])) { return true; } } return false; } /** * Method with initialize user customized transformation with concrete metadata * * @return * @throws ComponentNotReadyException */ private boolean init() throws ComponentNotReadyException { // map storing transformation for concrete output fields // key is in form: recNumber.fieldNumber Map<String, Rule> transformMap = new LinkedHashMap<String, Rule>(); ArrayList<Map<String, Rule>> alternativeTransformMaps = new ArrayList<Map<String, Rule>>(); Entry<String, ArrayList<Rule>> rulesEntry; String field; String ruleString = null; String[] outFields = new String[0]; String[] inFields; // iteration over each user given rule for (Iterator<Entry<String, ArrayList<Rule>>> iterator = rules.entrySet().iterator(); iterator.hasNext();) { rulesEntry = iterator.next(); for (Rule rule : rulesEntry.getValue()) { rule.setGraph(getGraph()); rule.setLogger(logger); rule.setProperties(parameters); // find output fields pattern field = resolveField(rulesEntry.getKey()); if (field == null) { errorMessage = "Wrong pattern for output fields: " + rulesEntry.getKey(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } // find output fields from pattern outFields = findFields(field, targetMetadata).toArray(new String[0]); if (outFields.length == 0) { errorMessage = "There is no output field matching \"" + field + "\" pattern"; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } inFields = new String[0]; if (rule instanceof DeleteRule) { for (int i = 0; i < outFields.length; i++) { rule = transformMap.remove(outFields[i]); } continue; } if (rule instanceof FieldRule) { // find input fields from pattern ruleString = resolveField(rule.getSource()); if (ruleString == null) { errorMessage = "Wrong pattern for output fields: " + ruleString; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } inFields = findFields(ruleString, sourceMetadata).toArray(new String[0]); if (inFields.length == 0) { errorMessage = "There is no input field matching \"" + ruleString + "\" pattern"; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } if (rule instanceof FieldRule && inFields.length > 1) { // find mapping by names if (putMappingByNames(transformMap, alternativeTransformMaps, outFields, inFields, rule.getSource()) == 0) { if (!useAlternativeRules) { errorMessage = "Not found any field for mapping by names due to rule:\n" + field + " - output fields pattern\n" + ruleString + " - input fields pattern"; logger.warn(errorMessage); } } } else {// for each output field the same rule // for each output field from pattern, put rule to map for (int i = 0; i < outFields.length; i++) { if (!containsWCard(field) || !transformMap.containsKey(outFields[i])) {// check primary map transformMap.put(outFields[i], rule.duplicate()); } else if (useAlternativeRules) {// rule is in primery map --> put to alternative map putRuleInAlternativeMap(outFields[i], rule, alternativeTransformMaps); } } } } } // changing map to array transformMapArray = new Rule[targetMetadata.length][maxNumFields(targetMetadata)]; order = new int[transformMap.size()][2]; int index = 0; for (Entry<String, Rule> i : transformMap.entrySet()) { field = i.getKey(); order[index][REC_NO] = getRecNo(field); order[index][FIELD_NO] = getFieldNo(field); transformMapArray[order[index][REC_NO]][order[index][FIELD_NO]] = i.getValue(); transformMapArray[order[index][REC_NO]][order[index][FIELD_NO]].init(sourceMetadata, targetMetadata, getRecNo(field), getFieldNo(field), fieldPolicy); index++; } // create and initialize alternative rules if (useAlternativeRules && alternativeTransformMaps.size() > 0) { alternativeTransformMapArrays = new ArrayList<Rule[][]>(alternativeTransformMaps.size()); alternativeOrder = new ArrayList<Integer[][]>(alternativeTransformMaps.size()); for (Map<String, Rule> map : alternativeTransformMaps) { Rule[][] ruleArray = new Rule[targetMetadata.length][maxNumFields(targetMetadata)]; alternativeTransformMapArrays.add(ruleArray); Integer[][] orderArray = new Integer[map.size()][2]; alternativeOrder.add(orderArray); index = 0; for (Entry<String, Rule> i : map.entrySet()) { field = i.getKey(); order[index][REC_NO] = getRecNo(field); order[index][FIELD_NO] = getFieldNo(field); ruleArray[order[index][REC_NO]][order[index][FIELD_NO]] = i.getValue(); ruleArray[order[index][REC_NO]][order[index][FIELD_NO]].init(sourceMetadata, targetMetadata, getRecNo(field), getFieldNo(field), fieldPolicy); index++; } } } return true; } /** * This method puts rule to the alternative map, which doesn't contain rule for this field. If all alternative maps * contain rule for requested field, new map is created and added to list * * @param field * output field * @param rule * rule to put * @param alternativeTransformMaps * list of alternative maps * @return */ private void putRuleInAlternativeMap(String field, Rule rule, List<Map<String, Rule>> alternativeTransformMaps) { for (Map<String, Rule> map : alternativeTransformMaps) { if (!map.containsKey(field)) { map.put(field, rule.duplicate()); return; } } // all maps checked --> create new one Map<String, Rule> newMap = new LinkedHashMap<String, Rule>(); alternativeTransformMaps.add(newMap); newMap.put(field, rule.duplicate()); } /** * Method, which puts mapping rules to map. First it tries to find fields with identical names in corresponding * input and output metadata. If not all output fields were found it tries to find them in other input records. If * not all output fields were found it tries to find fields with the same names ignoring case in corresponding * record. If still there are some output fields without paire it tries to find fields with the same name ignoring * case in other records, eg.<br> * outFieldsNames:<br> * <ul> * <li>lname, fname, address, phone</li> * <li>Lname, fname, id</li> * </ul> * inFieldsNames: * <ul> * <li>Lname, fname, id, address</li> * <li>lname, fname, phone</li> * </ul> * Mapping: * <ul> * <li>0.0 <-- 1.0</li> * <li>0.1 <-- 0.1</li> * <li>0.2 <-- 0.3</li> * <li>0.3 <-- 1.2</li> * <li>1.0 <-- 0.0</li> * <li>1.1 <-- 1.1</li> * <li>1.2 <-- 0.2</li> * </ul> * * @param transformMap * map to put rules * @param alternativeMaps * list of alternative maps, used if useAlternativeRules=true and primery map contains output field * @param outFields * output fields to mapping * @param inFields * input fields for mapping * @return number of mappings put to transform map */ protected int putMappingByNames(Map<String, Rule> transformMap, List<Map<String, Rule>> alternativeMaps, String[] outFields, String[] inFields, String rule) throws ComponentNotReadyException { int count = 0; String[][] outFieldsName = new String[targetMetadata.length][maxNumFields(targetMetadata)]; for (int i = 0; i < outFields.length; i++) { outFieldsName[getRecNo(outFields[i])][getFieldNo(outFields[i])] = targetMetadata[getRecNo(outFields[i])] .getField(getFieldNo(outFields[i])).getName(); } String[][] inFieldsName = new String[sourceMetadata.length][maxNumFields(sourceMetadata)]; for (int i = 0; i < inFields.length; i++) { inFieldsName[getRecNo(inFields[i])][getFieldNo(inFields[i])] = sourceMetadata[getRecNo(inFields[i])] .getField(getFieldNo(inFields[i])).getName(); } int index; // find identical in corresponding records for (int i = 0; (i < outFieldsName.length) && (i < inFieldsName.length); i++) { for (int j = 0; j < outFieldsName[i].length; j++) { if (outFieldsName[i][j] != null) { index = StringUtils.findString(outFieldsName[i][j], inFieldsName[i]); if (index > -1) {// output field name found amoung input fields if (putMapping(i, j, i, index, rule, transformMap, alternativeMaps)) { count++; outFieldsName[i][j] = null; inFieldsName[i][index] = null; } } } } } // find identical in other records for (int i = 0; i < outFieldsName.length; i++) { for (int j = 0; j < outFieldsName[i].length; j++) { for (int k = 0; k < inFieldsName.length; k++) { if ((outFieldsName[i][j] != null) && (k != i)) { index = StringUtils.findString(outFieldsName[i][j], inFieldsName[k]); if (index > -1) {// output field name found amoung input fields if (putMapping(i, j, k, index, rule, transformMap, alternativeMaps)) { count++; outFieldsName[i][j] = null; inFieldsName[k][index] = null; } } } } } } // find ignore case in corresponding records for (int i = 0; (i < outFieldsName.length) && (i < inFieldsName.length); i++) { for (int j = 0; j < outFieldsName[i].length; j++) { if (outFieldsName[i][j] != null) { index = StringUtils.findStringIgnoreCase(outFieldsName[i][j], inFieldsName[i]); if (index > -1) {// output field name found amoung input fields if (putMapping(i, j, i, index, rule, transformMap, alternativeMaps)) { count++; outFieldsName[i][j] = null; inFieldsName[i][index] = null; } } } } } // find ignore case in other records for (int i = 0; i < outFieldsName.length; i++) { for (int j = 0; j < outFieldsName[i].length; j++) { for (int k = 0; k < inFieldsName.length; k++) { if ((outFieldsName[i][j] != null) && (k != i)) { index = StringUtils.findStringIgnoreCase(outFieldsName[i][j], inFieldsName[k]); if (index > -1) {// output field name found amoung input fields if (putMapping(i, j, k, index, rule, transformMap, alternativeMaps)) { count++; outFieldsName[i][j] = null; inFieldsName[k][index] = null; } } } } } } return count; } /** * This method puts mapping into given output and input field to transform map if theese fields have correct types * due to policy type * * @param outRecNo * number of record from output metadata * @param outFieldNo * number of field from output metadata * @param inRecNo * number of record from input metadata * @param inFieldNo * number of field from input metadata * @param transformMap * @param alternativeMaps * list of alternative maps, used if useAlternativeRules=true and primery map contains output field * @return true if mapping was put into map, false in other case */ protected boolean putMapping(int outRecNo, int outFieldNo, int inRecNo, int inFieldNo, String ruleString, Map<String, Rule> transformMap, List<Map<String, Rule>> alternativeMaps) throws ComponentNotReadyException { if (!Rule.checkTypes(targetMetadata[outRecNo].getField(outFieldNo), sourceMetadata[inRecNo].getField(inFieldNo), fieldPolicy)) { if (fieldPolicy == PolicyType.STRICT) { logger.warn("Found fields with the same names but other types: "); logger.warn(targetMetadata[outRecNo].getName() + DOT + targetMetadata[outRecNo].getField(outFieldNo).getName() + " type - " + targetMetadata[outRecNo].getFieldTypeAsString(outFieldNo) + getDecimalParams(targetMetadata[outRecNo].getField(outFieldNo))); logger.warn(sourceMetadata[inRecNo].getName() + DOT + sourceMetadata[inRecNo].getField(inFieldNo).getName() + " type - " + sourceMetadata[inRecNo].getFieldTypeAsString(inFieldNo) + getDecimalParams(sourceMetadata[inRecNo].getField(inFieldNo))); } if (fieldPolicy == PolicyType.CONTROLLED) { logger.warn("Found fields with the same names but incompatible types: "); logger.warn(targetMetadata[outRecNo].getName() + DOT + targetMetadata[outRecNo].getField(outFieldNo).getName() + " type - " + targetMetadata[outRecNo].getFieldTypeAsString(outFieldNo) + getDecimalParams(targetMetadata[outRecNo].getField(outFieldNo))); logger.warn(sourceMetadata[inRecNo].getName() + DOT + sourceMetadata[inRecNo].getField(inFieldNo).getName() + " type - " + sourceMetadata[inRecNo].getFieldTypeAsString(inFieldNo) + getDecimalParams(sourceMetadata[inRecNo].getField(inFieldNo))); } return false; } else {// map fields FieldRule rule = new FieldRule(ruleString); rule.setFieldParams(String.valueOf(inRecNo) + DOT + inFieldNo); if (!transformMap.containsKey(String.valueOf(outRecNo) + DOT + outFieldNo)) { transformMap.put(String.valueOf(outRecNo) + DOT + outFieldNo, rule); } else if (useAlternativeRules) { putRuleInAlternativeMap(String.valueOf(outRecNo) + DOT + outFieldNo, rule, alternativeMaps); } return true; } } /** * Finds fields from metadata matching given pattern * * @param pattern * @param metadata * @return list of fields matching given metadata */ public static ArrayList<String> findFields(String pattern, DataRecordMetadata[] metadata) { ArrayList<String> list = new ArrayList<String>(); String recordNoString = pattern.substring(0, pattern.indexOf(DOT)); String fieldNoString = pattern.substring(pattern.indexOf(DOT) + 1); int fieldNo; int recNo; try {// check if first part of pattern is "real" pattern or number of record recNo = Integer.parseInt(recordNoString); try {// we have one record Number // check if second part of pattern is "real" pattern or number of field fieldNo = Integer.parseInt(fieldNoString); // we have one record field number list.add(pattern); } catch (NumberFormatException e) {// second part of pattern is not a number // find matching fields for (int i = 0; i < metadata[recNo].getNumFields(); i++) { if (WcardPattern.checkName(fieldNoString, metadata[recNo].getField(i).getName())) { list.add(String.valueOf(recNo) + DOT + i); } } } } catch (NumberFormatException e) {// first part of pattern is not a number // check all matadata names if match pattern for (int i = 0; i < metadata.length; i++) { if (WcardPattern.checkName(recordNoString, metadata[i].getName())) { try {// check if second part of pattern is "real" pattern or number of field fieldNo = Integer.parseInt(fieldNoString); // we have matching metadata name and field number list.add(String.valueOf(i) + DOT + fieldNoString); } catch (NumberFormatException e1) {// second part of pattern is not a number // find matching fields for (int j = 0; j < metadata[i].getNumFields(); j++) { if (WcardPattern.checkName(fieldNoString, metadata[i].getField(j).getName())) { list.add(String.valueOf(i) + DOT + j); } } } } } } return list; } public void setGraph(TransformationGraph graph) { this.graph = graph; } public void signal(Object signalObject) { // TODO Auto-generated method stub } /** * Fills error message and throws exception * * @param ruleArray * @param recNo * @param FieldNo * @param ex * @throws TransformException */ private void throwException(Rule[][] ruleArray, int recNo, int FieldNo, Exception ex) throws TransformException { errorMessage = "TransformException caused by source: " + ruleArray[recNo][FieldNo].getSource(); logger.error(errorMessage, ex); throw new TransformException(errorMessage, ex, recNo, FieldNo); } /* * (non-Javadoc) * * @see org.jetel.component.RecordTransform#transform(org.jetel.data.DataRecord[], org.jetel.data.DataRecord[]) */ public boolean transform(DataRecord[] sources, DataRecord[] target) throws TransformException { // array "order" stores coordinates of output fields in order they will be assigned for (int i = 0; i < order.length; i++) { value = transformMapArray[order[i][REC_NO]][order[i][FIELD_NO]].getValue(sources); if (value != null || !useAlternativeRules) { try { target[order[i][REC_NO]].getField(order[i][FIELD_NO]).setValue(value); } catch (BadDataFormatException e) { // we can try to change value to String and set to output field if (value != null && fieldPolicy != PolicyType.STRICT) { try { target[order[i][REC_NO]].getField(order[i][FIELD_NO]).fromString(value.toString()); } catch (BadDataFormatException e1) { if (!useAlternativeRules || !setAlternativeValue(sources, target, order[i][REC_NO], order[i][FIELD_NO], 0, e1)) { throwException(transformMapArray, order[i][REC_NO], order[i][FIELD_NO], e1); } } } else if (!useAlternativeRules || !setAlternativeValue(sources, target, order[i][REC_NO], order[i][FIELD_NO], 0, e)) {// value // is // null // or // value // can't // be // set // to // field throwException(transformMapArray, order[i][REC_NO], order[i][FIELD_NO], e); } } } else {// value is null and useuseAlternativeRules = true setAlternativeValue(sources, target, order[i][REC_NO], order[i][FIELD_NO], 0, null); } } return true; } /** * Tries to set value due to given alternative rule * * @param sources * source records * @param target * target records * @param trgRec * target record number * @param trgField * target field number * @param alternativeRuleNumber * @param cause * why we call alternative rule * @return true if value was set, in other case throws TransformException * @throws TransformException */ private boolean setAlternativeValue(DataRecord[] sources, DataRecord[] target, int trgRec, int trgField, int alternativeRuleNumber, Exception cause) throws TransformException { Rule[][] ruleArray = alternativeTransformMapArrays.get(alternativeRuleNumber); if (ruleArray[trgRec][trgField] == null) { throwException(ruleArray, trgRec, trgField, cause); } value = ruleArray[trgRec][trgField].getValue(sources); if (value != null) { try { target[trgRec].getField(trgField).setValue(value); return true; } catch (BadDataFormatException e) { if (fieldPolicy != PolicyType.STRICT) { try { target[trgRec].getField(trgField).fromString(value.toString()); return true; } catch (BadDataFormatException e1) { if (++alternativeRuleNumber < alternativeTransformMapArrays.size()) { return setAlternativeValue(sources, target, trgRec, trgField, alternativeRuleNumber, e1); } else { throwException(ruleArray, trgRec, trgField, e1); } } } else if (++alternativeRuleNumber < alternativeTransformMapArrays.size()) { return setAlternativeValue(sources, target, trgRec, trgField, alternativeRuleNumber, e); } else { throwException(ruleArray, trgRec, trgField, e); } } } else if (++alternativeRuleNumber < alternativeTransformMapArrays.size()) { return setAlternativeValue(sources, target, trgRec, trgField, alternativeRuleNumber, cause); } else {// value is null try { target[trgRec].getField(trgField).setValue(value); return true; } catch (BadDataFormatException e) { throwException(ruleArray, trgRec, trgField, e); } } return true; } /** * Changes pattern given in one of possible format to record.field * * @param pattern * @return pattern in format record.field of null if it is not possible */ public static String resolveField(String pattern) { String[] parts = pattern.split("\\."); switch (parts.length) { case 2: if (parts[0].startsWith("$")) {// ${recNo.field} return parts[0].substring(2) + DOT + parts[1].substring(0, parts[1].length() - 1); } else {// recNo.field return pattern; } case 3: if (parts[0].startsWith("$")) {// ${in/out.recNo.field} return parts[1] + DOT + parts[2].substring(0, parts[2].length() - 1); } else {// in/out.recNo.field return parts[1] + DOT + parts[2]; } default: return null; } } /** * Gets rule in form they were set by user * * @return rules */ public ArrayList<String> getRulesAsStrings() { ArrayList<String> list = new ArrayList<String>(); Entry<String, ArrayList<Rule>> entry; ArrayList<Rule> subList; for (Iterator<Entry<String, ArrayList<Rule>>> iterator = rules.entrySet().iterator(); iterator.hasNext();) { entry = iterator.next(); subList = entry.getValue(); for (int i = 0; i < subList.size(); i++) { list.add(subList.get(i).getType() + ":" + entry.getKey() + "=" + subList.get(i).getSource()); } } return list; } /** * Gets rules for concrete metadata in well readable form * * @return resolved rules */ public ArrayList<String> getResolvedRules() { ArrayList<String> list = new ArrayList<String>(); String value; for (int recNo = 0; recNo < transformMapArray.length; recNo++) { for (int fieldNo = 0; fieldNo < transformMapArray[0].length; fieldNo++) { if (transformMapArray[recNo][fieldNo] != null) { value = transformMapArray[recNo][fieldNo].getCanonicalSource() != null ? transformMapArray[recNo][fieldNo] .getCanonicalSource().toString() : "null"; list.add(targetMetadata[recNo].getName() + DOT + targetMetadata[recNo].getField(fieldNo).getName() + "=" + value); } } } return list; } /** * Gets output fields, for which there wasn't set any rule * * @return indexes (output record number, output field number) of fields without rule */ public ArrayList<Integer[]> getFieldsWithoutRules() { ArrayList<Integer[]> list = new ArrayList<Integer[]>(); for (int recNo = 0; recNo < transformMapArray.length; recNo++) { for (int fieldNo = 0; fieldNo < transformMapArray[0].length; fieldNo++) { if (fieldNo < targetMetadata[recNo].getNumFields() && transformMapArray[recNo][fieldNo] == null) { list.add(new Integer[] { recNo, fieldNo }); } } } return list; } /** * Gets input fields not mapped on output fields * * @return indexes (output record number, output field number) of not used input fields */ public ArrayList<Integer[]> getNotUsedFields() { String[] inFields = findFields("*.*", sourceMetadata).toArray(new String[0]); Rule rule; int index; String field; for (int recNo = 0; recNo < transformMapArray.length; recNo++) { for (int fieldNo = 0; fieldNo < transformMapArray[0].length; fieldNo++) { rule = transformMapArray[recNo][fieldNo]; if (rule != null && rule instanceof FieldRule) { field = (String) rule.getCanonicalSource(); index = StringUtils.findString(field, inFields); if (index != -1) { inFields[index] = null; } } } } ArrayList<Integer[]> list = new ArrayList<Integer[]>(); for (int i = 0; i < inFields.length; i++) { if (inFields[i] != null) { list.add(new Integer[] { getRecNo(inFields[i]), getFieldNo(inFields[i]) }); } } return list; } /** * Gets rule for given output field * * @param recNo * output record number * @param fieldNo * output record's field number * @return rule for given output field */ public String getRule(int recNo, int fieldNo) { Rule rule = transformMapArray[recNo][fieldNo]; if (rule == null) { return null; } return (rule.getType()) + COLON + rule.getCanonicalSource(); } /** * Gets output fields, which mapped given input field * * @param inRecNo * input record number * @param inFieldNo * input record's field number * @return indexes (output record number, output field number) of fields, which mapped given input field */ public ArrayList<Integer[]> getRulesWithField(int inRecNo, int inFieldNo) { ArrayList<Integer[]> list = new ArrayList<Integer[]>(); Rule rule; for (int recNo = 0; recNo < transformMapArray.length; recNo++) { for (int fieldNo = 0; fieldNo < transformMapArray[0].length; fieldNo++) { rule = transformMapArray[recNo][fieldNo]; if (rule != null && rule instanceof FieldRule) { if (getRecNo((String) rule.getCanonicalSource()) == inRecNo && getFieldNo((String) rule.getCanonicalSource()) == inFieldNo) { list.add(new Integer[] { recNo, fieldNo }); } } } } return list; } public PolicyType getFieldPolicy() { return fieldPolicy; } /** * Sets the field policy: * <ul> * <li>PolicyType.STRICT - mapped output and input fields have to be of the same types * <li>PolicyType.CONTROLLED - mapped input fields have to be subtypes of output fields<br> * <li>PolicyType.LENIENT - field's types are not checked during initialization * </ul> * For PolicyType CONTROLLED and LENIENT method transform can work slower as for not identical types for is called * method fromString, when method setValue has failed. * * @param fieldPolicy */ public void setFieldPolicy(PolicyType fieldPolicy) { this.fieldPolicy = fieldPolicy; } /** * Finds maximal length of metadata * * @param metadata * @return maximal length of metadatas */ private int maxNumFields(DataRecordMetadata[] metadata) { int numFields = 0; for (int i = 0; i < metadata.length; i++) { if (metadata[i].getNumFields() > numFields) { numFields = metadata[i].getNumFields(); } } return numFields; } /** * Gets part of string before . and changed it to Integer * * @param recField * recNo.FieldNo * @return record number */ public static Integer getRecNo(String recField) { return Integer.valueOf(recField.substring(0, recField.indexOf(DOT))); } /** * Gets part of string after . and changed it to Integer * * @param recField * @return field number */ public static Integer getFieldNo(String recField) { return Integer.valueOf(recField.substring(recField.indexOf(DOT) + 1)); } /** * This method gets LENGTH and SCALE from decimal data field * * @param field * @return string (LENGTH,SCALE) */ public static String getDecimalParams(DataFieldMetadata field) { if (field.getType() != DataFieldMetadata.DECIMAL_FIELD) { return ""; } StringBuilder params = new StringBuilder(5); params.append('('); params.append(field.getProperty(DataFieldMetadata.LENGTH_ATTR)); params.append(','); params.append(field.getProperty(DataFieldMetadata.SCALE_ATTR)); params.append(')'); return params.toString(); } /* * (non-Javadoc) * * @see org.jetel.component.RecordTransform#reset() */ public void reset() { errorMessage = null; } public void setLogger(Log logger) { this.logger = logger; } /** * @return if transformation uses alternative rules * * @see setUseAlternativeRules */ public boolean isUseAlternativeRules() { return useAlternativeRules; } /** * Switchs on/off alternative rules. When alternative rules are switched on, more rules can be used for one field: * if value from primery rule is null or transformations failed trying to set it, there are used lternative rules. * Tranasformation fails if value of noone rule can be set to requested field. * * @param useAlternativeRules */ public void setUseAlternativeRules(boolean useAlternativeRules) { this.useAlternativeRules = useAlternativeRules; } }// class CustomizedRecordTransform /** * Private class for storing transformation rules */ abstract class Rule { Object value; String source; String errorMessage; Log logger; TransformationGraph graph; Properties parameters; Rule(String source) { this.source = source; } Rule(Object value) { this.value = value; } String getSource() { return source; } public void setLogger(Log logger) { this.logger = logger; } public void setGraph(TransformationGraph graph) { this.graph = graph; } public void setProperties(Properties parameters) { this.parameters = parameters; } abstract Rule duplicate(); abstract String getType(); abstract Object getCanonicalSource(); /** * Gets value for setting to data field * * @param sources * source data record (used only in Field rule) * @return value to be set to data field */ abstract Object getValue(DataRecord[] sources); /** * Prepares rule (source, value and check if value can be got) for getting values in transform method of * CustomizedRecordTransform class * * @param sourceMetadata * @param targetMetadata * @param recNo * output metadata number (from targetMetadata) * @param fieldNo * output field number * @param policy * field policy * @throws ComponentNotReadyException */ abstract void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException; /** * This method checks if input field is subtype of output type * * @param outRecNo * output record number * @param outFieldNo * output record's field number * @param inRecNo * input record number * @param inFieldNo * input record's field number * @return "true" if input field is subtype of output field, "false" in other cases */ public static boolean checkTypes(DataFieldMetadata outField, DataFieldMetadata inField, PolicyType policy) { boolean checkTypes; // check if both fields are of type DECIMAL, if yes inField must be subtype of outField if (outField.getType() == inField.getType()) { if (outField.getType() == DataFieldMetadata.DECIMAL_FIELD) { checkTypes = inField.isSubtype(outField); } else { checkTypes = true; } } else { checkTypes = false; } if (policy == PolicyType.STRICT && !checkTypes) { return false; } else if (policy == PolicyType.CONTROLLED && !inField.isSubtype(outField)) { return false; } return true; } } /** * Descendent of Rule class for storing field's mapping rule */ class FieldRule extends Rule { String fieldParams;// "recNo.fieldNo" = "resolved source" - it have to be set by setFieldParams method FieldRule(String source) { super(source); } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { if (fieldParams == null) { // try find ONE field in source metadata matching source fieldParams = CustomizedRecordTransform.resolveField(source); ArrayList<String> tmp = CustomizedRecordTransform.findFields(fieldParams, sourceMetadata); if (tmp.size() != 1) { throw new ComponentNotReadyException("Field parameters are " + "not set and can't be resolved from source: " + source); } fieldParams = tmp.get(0); } // check input and output fields types if (!checkTypes(targetMetadata[recNo].getField(fieldNo), sourceMetadata[CustomizedRecordTransform .getRecNo(fieldParams)].getField(CustomizedRecordTransform.getFieldNo(fieldParams)), policy)) { if (policy == PolicyType.STRICT) { errorMessage = "Output field type does not match input field " + "type:\n" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + " type - " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(targetMetadata[recNo].getField(fieldNo)) + "\n" + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getName() + CustomizedRecordTransform.DOT + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getField( CustomizedRecordTransform.getFieldNo(fieldParams)).getName() + " type - " + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getField( CustomizedRecordTransform.getFieldNo(fieldParams)).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(sourceMetadata[CustomizedRecordTransform .getRecNo(fieldParams)].getField(CustomizedRecordTransform.getFieldNo(fieldParams))); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } if (policy == PolicyType.CONTROLLED) { errorMessage = "Output field type is not compatible with input field " + "type:\n" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + " type - " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(targetMetadata[recNo].getField(fieldNo)) + "\n" + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getName() + CustomizedRecordTransform.DOT + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getField( CustomizedRecordTransform.getFieldNo(fieldParams)).getName() + " type - " + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getField( CustomizedRecordTransform.getFieldNo(fieldParams)).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(sourceMetadata[CustomizedRecordTransform .getRecNo(fieldParams)].getField(CustomizedRecordTransform.getFieldNo(fieldParams))); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } } public void setFieldParams(String fieldParams) { this.fieldParams = fieldParams; } @Override Object getCanonicalSource() { return fieldParams; } @Override String getType() { return "FIELD_RULE"; } /* * (non-Javadoc) * * @see org.jetel.component.Rule#getValue(org.jetel.data.DataRecord[]) * */ @Override Object getValue(DataRecord[] sources) { int dotIndex = fieldParams.indexOf(CustomizedRecordTransform.DOT); int recNo = dotIndex > -1 ? Integer.parseInt(fieldParams.substring(0, dotIndex)) : 0; int fieldNo = dotIndex > -1 ? Integer.parseInt(fieldParams.substring(dotIndex + 1)) : Integer .parseInt(fieldParams); return sources[recNo].getField(fieldNo).getValue(); } @Override Rule duplicate() { FieldRule duplicate = new FieldRule(source); duplicate.setFieldParams(fieldParams); duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } } /** * Descendent of Rule class for storing sequence rule */ class SequenceRule extends Rule { String method;// sequence Id with one of squence method used for // getting value from sequence eg.: // seq1.nextValueString() SequenceRule(String source) { super(source); } SequenceRule(Object value) { super(value); if (!(value instanceof Sequence)) { throw new IllegalArgumentException("Sequence rule doesn't accept " + value.getClass().getName() + " argument"); } source = ((Sequence) value).getId(); } @Override Rule duplicate() { SequenceRule duplicate; if (value != null) { duplicate = new SequenceRule(value); } else { duplicate = new SequenceRule(source); } duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } @Override String getType() { return "SEQUENCE_RULE"; } @Override Object getCanonicalSource() { return method; } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { // prepare sequence and method String sequenceID = source.indexOf(CustomizedRecordTransform.DOT) == -1 ? source : source.substring(0, source .indexOf(CustomizedRecordTransform.DOT)); if (value == null) { value = graph.getSequence(sequenceID); } if (value == null) { logger.warn("There is no sequence \"" + sequenceID + "\" in graph"); if (!(targetMetadata[recNo].getField(fieldNo).isNullable() || targetMetadata[recNo].getField(fieldNo) .isDefaultValue())) { errorMessage = "Null value not allowed to record: " + targetMetadata[recNo].getName() + " , field: " + targetMetadata[recNo].getField(fieldNo).getName(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } else { method = "null"; return; } } // check sequence method String method = source.indexOf(CustomizedRecordTransform.DOT) > -1 ? source.substring(source .indexOf(CustomizedRecordTransform.DOT) + 1) : null; char methodType = DataFieldMetadata.UNKNOWN_FIELD; if (method != null) { this.method = method; if (method.toLowerCase().startsWith("currentvaluestring") || method.toLowerCase().startsWith("currentstring") || method.toLowerCase().startsWith("nextvaluestring") || method.toLowerCase().startsWith("nextstring")) { methodType = DataFieldMetadata.STRING_FIELD; } if (method.toLowerCase().startsWith("currentvalueint") || method.toLowerCase().startsWith("currentint") || method.toLowerCase().startsWith("nextvalueint") || method.toLowerCase().startsWith("nextint")) { methodType = DataFieldMetadata.INTEGER_FIELD; } if (method.toLowerCase().startsWith("currentvaluelong") || method.toLowerCase().startsWith("currentlong") || method.toLowerCase().startsWith("nextvaluelong") || method.toLowerCase().startsWith("nextlong")) { methodType = DataFieldMetadata.LONG_FIELD; } } else {// method is not given, prepare the best switch (targetMetadata[recNo].getField(fieldNo).getType()) { case DataFieldMetadata.BYTE_FIELD: case DataFieldMetadata.BYTE_FIELD_COMPRESSED: case DataFieldMetadata.STRING_FIELD: this.method = sequenceID + CustomizedRecordTransform.DOT + "nextValueString()"; methodType = DataFieldMetadata.STRING_FIELD; break; case DataFieldMetadata.DECIMAL_FIELD: case DataFieldMetadata.LONG_FIELD: case DataFieldMetadata.NUMERIC_FIELD: this.method = sequenceID + CustomizedRecordTransform.DOT + "nextValueLong()"; methodType = DataFieldMetadata.LONG_FIELD; break; case DataFieldMetadata.INTEGER_FIELD: this.method = sequenceID + CustomizedRecordTransform.DOT + "nextValueInt()"; methodType = DataFieldMetadata.INTEGER_FIELD; break; default: errorMessage = "Can't set sequence to data field of type: " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + " (" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + ")"; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } DataFieldMetadata tmp; if (methodType == DataFieldMetadata.UNKNOWN_FIELD) { errorMessage = "Unknown sequence method: " + method; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } else { tmp = new DataFieldMetadata("tmp", methodType, ";"); } // check if value from sequence can be set to given field if (!checkTypes(targetMetadata[recNo].getField(fieldNo), tmp, policy)) { if (policy == PolicyType.STRICT) { errorMessage = "Sequence method:" + this.method + " does not " + "match field type:\n" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + " type - " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(targetMetadata[recNo].getField(fieldNo)); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } if (policy == PolicyType.CONTROLLED) { errorMessage = "Sequence method:" + this.method + " does not " + "match field type:\n" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + " type - " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(targetMetadata[recNo].getField(fieldNo)); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } } } /* * (non-Javadoc) * * @see org.jetel.component.Rule#getValue(org.jetel.data.DataRecord[]) */ @Override Object getValue(DataRecord[] sources) { if (value == null) { return null; } int dotIndex = method.indexOf(CustomizedRecordTransform.DOT); String method = this.method.substring(dotIndex + 1); if (method.toLowerCase().startsWith("currentvaluestring") || method.toLowerCase().startsWith("currentstring")) { return ((Sequence) value).currentValueString(); } if (method.toLowerCase().startsWith("nextvaluestring") || method.toLowerCase().startsWith("nextstring")) { return ((Sequence) value).nextValueString(); } if (method.toLowerCase().startsWith("currentvalueint") || method.toLowerCase().startsWith("currentint")) { return ((Sequence) value).currentValueInt(); } if (method.toLowerCase().startsWith("nextvalueint") || method.toLowerCase().startsWith("nextint")) { return ((Sequence) value).nextValueInt(); } if (method.toLowerCase().startsWith("currentvaluelong") || method.toLowerCase().startsWith("currentlong")) { return ((Sequence) value).currentValueLong(); } if (method.toLowerCase().startsWith("nextvaluelong") || method.toLowerCase().startsWith("nextlong")) { return ((Sequence) value).nextValueLong(); } // in method validateRule checked, that has to be one of method above return null; } } /** * Descendent of Rule class for storing constant rule */ class ConstantRule extends Rule { /** * Constructor for setting constant as string * * @param source */ ConstantRule(String source) { super(source); } /** * Constructor for setting constant as expected Object (due to data field type) * * @param value */ ConstantRule(Object value) { super(value); } @Override Rule duplicate() { ConstantRule duplicate; if (value != null) { duplicate = new ConstantRule(value); } else { duplicate = new ConstantRule(source); } duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } @Override String getType() { return "CONSTANT_RULE"; } @Override Object getCanonicalSource() { return source != null ? source : value; } @Override Object getValue(DataRecord[] sources) { return value; } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { // used temporary data field for checking constant DataField tmp = DataFieldFactory.createDataField(targetMetadata[recNo].getField(fieldNo), false); if (source != null) { try { tmp.fromString(source); value = tmp.getValue(); } catch (BadDataFormatException e) { errorMessage = e.getLocalizedMessage(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } else { try { tmp.setValue(value); source = tmp.toString(); } catch (BadDataFormatException e) { errorMessage = e.getLocalizedMessage(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } } } /** * Descendent of Rule class for storing parameter rule */ class ParameterRule extends Rule { ParameterRule(String source) { super(source); } @Override Rule duplicate() { ParameterRule duplicate = new ParameterRule(source); duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } @Override String getType() { return "PARAMETER_RULE"; } @Override Object getCanonicalSource() { return source; } @Override Object getValue(DataRecord[] sources) { return value; } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { // get parameter value String paramValue; if (source.startsWith("${")) {// get graph parameter paramValue = graph.getGraphProperties().getProperty(source.substring(2, source.lastIndexOf('}'))); } else if (source.startsWith(String.valueOf(CustomizedRecordTransform.PARAMETER_CHAR))) { // get parameter from node properties paramValue = parameters.getProperty((source)); } else { // try to find parameter with given name in node properties paramValue = parameters.getProperty(CustomizedRecordTransform.PARAMETER_CHAR + source); if (paramValue == null) { // try to find parameter with given name among graph parameters paramValue = graph.getGraphProperties().getProperty(source); } if (paramValue == null) { errorMessage = "Not found parameter: " + source; if (!(targetMetadata[recNo].getField(fieldNo).isNullable() || targetMetadata[recNo].getField(fieldNo) .isDefaultValue())) { logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } else { logger.warn(errorMessage); } } } // use temporary field to check if the value can be set to given data field DataField tmp = DataFieldFactory.createDataField(targetMetadata[recNo].getField(fieldNo), false); try { tmp.fromString(paramValue); value = tmp.getValue(); } catch (BadDataFormatException e) { errorMessage = e.getLocalizedMessage(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } } /** * Degenerated descendent of Rule class for marking fields for deleting previous rule */ class DeleteRule extends Rule { DeleteRule() { super(null); } @Override Rule duplicate() { DeleteRule duplicate = new DeleteRule(); duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } @Override String getType() { return "DELETE_RULE"; } @Override Object getCanonicalSource() { return null; } @Override Object getValue(DataRecord[] sources) { return null; } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { // do nothing } }
cloveretl.engine/src/org/jetel/component/CustomizedRecordTransform.java
/* * jETeL/Clover - Java based ETL application framework. * Copyright (C) 2005-06 Javlin Consulting <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package org.jetel.component; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.jetel.data.DataField; import org.jetel.data.DataFieldFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.primitive.Numeric; import org.jetel.data.sequence.Sequence; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.PolicyType; import org.jetel.exception.TransformException; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.file.WcardPattern; import org.jetel.util.primitive.DuplicateKeyMap; import org.jetel.util.string.StringUtils; /** * * Class used for generating data transformation. It has methods for mapping input fields on output fields, assigning * constants, sequence methods and parameter's values to output fields. * * <h4>Patterns for data fields can be given in three ways:</h4> * <ol> * <li> <i>record.field</i> where <i>record</i> is number, name or wild card of input or output record and <i>field</i> * is name, number or wild card of <i>record's</i> data field </li> * <li> <i>${record.field}</i> where <i>record</i> and <i>field</i> have to be as described above</li> * <li> <i>${in/out.record.field}</i> where <i>record</i> and <i>field</i> have to be as described above</li> * </ol> * * <h4>Order of execution/methods call</h4> * <ol> * <li>setGraph()</li> * <li>setFieldPolicy(PolicyType) - default value is STRICT</li> * <li>setUseAlternativeRules(boolean) - default is <b>false</b> * <li>add...Rule(...)<br> .<br> * </li> * <li>deleteRule(...)<br> .<br> * </li> * <li>init()</li> * <li>transform() <i>for each input&amp;output records pair</i></li> * <li><i>optionally</i> getMessage() <i>or</i> signal() <i>or</i> getSemiResult()</li> * <li>finished() * </ol> * * <h4>Example:</h4> * <b>Records:</b> * * <pre> * in: * #0|Name|S-&gt; HELLO * #1|Age|N-&gt;135.0 * #2|City|S-&gt;Some silly longer string. * #3|Born|D-&gt; * #4|Value|d-&gt;-999.0000000000 * * in1: * #0|Name|S-&gt; My name * #1|Age|N-&gt;13.25 * #2|City|S-&gt;Prague * #3|Born|D-&gt;Thu Nov 30 09:54:07 CET 2006 * #4|Value|i-&gt; * out: * #0|Name|B-&gt; * #1|Age|N-&gt; * #2|City|S-&gt; * #3|Born|D-&gt; * #4|Value|d-&gt; * out1: * #0|Name|S-&gt; * #1|Age|d-&gt; * #2|City|S-&gt; * #3|Born|D-&gt; * #4|Value|i-&gt; * </pre> * * <b>Java code:</b> * * <pre> * CustomizedRecordTransform transform = new CustomizedRecordTransform(LogFactory.getLog(this.getClass())); * transform.setGraph(graph); * transform.addFieldToFieldRule(&quot;${1.?a*}&quot;, &quot;${1.*e}&quot;); * transform.addFieldToFieldRule(&quot;*.City&quot;, 0, 2); * transform.addConstantToFieldRule(1, 3, new GregorianCalendar(1973, 3, 23).getTime()); * transform.addConstantToFieldRule(4, &quot;1.111111111&quot;); * transform.addSequenceToFieldRule(&quot;*.Age&quot;, graph.getSequence(&quot;ID&quot;)); * transform.addRule(&quot;out.City&quot;, &quot;${seq.ID.nextString}&quot;); * transform.addParameterToFieldRule(1, 0, &quot;${WORKSPACE}&quot;); * transform.addParameterToFieldRule(1, &quot;City&quot;, &quot;YourCity&quot;); * transform.deleteRule(1, &quot;Age&quot;); * transform.init(properties, new DataRecordMetadata[] { metadata, metadata1 }, new DataRecordMetadata[] { metaOut, * metaOut1 }); * List&lt;String&gt; rules = transform.getRules(); * System.out.println(&quot;Rules:&quot;); * for (Iterator&lt;String&gt; i = rules.iterator(); i.hasNext();) { * System.out.println(i.next()); * } * rules = transform.getResolvedRules(); * System.out.println(&quot;Resolved rules:&quot;); * for (Iterator&lt;String&gt; i = rules.iterator(); i.hasNext();) { * System.out.println(i.next()); * } * List&lt;Integer[]&gt; fields = transform.getFieldsWithoutRules(); * System.out.println(&quot;Fields without rules:&quot;); * Integer[] index; * for (Iterator&lt;Integer[]&gt; i = fields.iterator(); i.hasNext();) { * index = i.next(); * System.out.println(outMatedata[index[0]].getName() + CustomizedRecordTransform.DOT * + outMatedata[index[0]].getField(index[1]).getName()); * } * fields = transform.getNotUsedFields(); * System.out.println(&quot;Not used input fields:&quot;); * for (Iterator&lt;Integer[]&gt; i = fields.iterator(); i.hasNext();) { * index = i.next(); * System.out.println(inMetadata[index[0]].getName() + CustomizedRecordTransform.DOT * + inMetadata[index[0]].getField(index[1]).getName()); * } * transform.transform(new DataRecord[] { record, record1 }, new DataRecord[] { out, out1 }); * System.out.println(record.getMetadata().getName() + &quot;:\n&quot; + record.toString()); * System.out.println(record1.getMetadata().getName() + &quot;:\n&quot; + record1.toString()); * System.out.println(out.getMetadata().getName() + &quot;:\n&quot; + out.toString()); * System.out.println(out1.getMetadata().getName() + &quot;:\n&quot; + out1.toString()); * </pre> * * <b>Output:</b> * * <pre> * Rules: * FIELD_RULE:${1.?a*}=${1.*e} * FIELD_RULE:*.City=0.2 * CONSTANT_RULE:1.3=Apr 23, 1973 * CONSTANT_RULE:0.4=1.111111111 * SEQUENCE_RULE:*.Age=ID * SEQUENCE_RULE:out.City=ID.nextString * PARAMETER_RULE:1.0=${WORKSPACE} * PARAMETER_RULE:1.City=YourCity * DELETE_RULE:1.Age=1.Age * Resolved rules: * out.Age=${seq.ID} * out.City=${seq.ID.nextString} * out.Value=1.111111111 * out1.Name=/home/avackova/workspace * out1.City=London * out1.Born=23-04-1973 * out1.Value=in1.Value * Fields without rules: * out.Name * out.Born * out1.Age * Not used input fields: * in.Name * in.Age * in.City * in.Born * in.Value * in1.Name * in1.Age * in1.City * in1.Born * in: * #0|Name|S-&gt; HELLO * #1|Age|N-&gt;135.0 * #2|City|S-&gt;Some silly longer string. * #3|Born|D-&gt; * #4|Value|d-&gt;-999.0000000000 * * in1: * #0|Name|S-&gt; My name * #1|Age|N-&gt;13.25 * #2|City|S-&gt;Prague * #3|Born|D-&gt;Thu Nov 30 10:40:15 CET 2006 * #4|Value|i-&gt; * * out: * #0|Name|B-&gt; * #1|Age|N-&gt;2.0 * #2|City|S-&gt;1 * #3|Born|D-&gt; * #4|Value|d-&gt;1.1 * * out1: * #0|Name|S-&gt;/home/user/workspace * #1|Age|d-&gt; * #2|City|S-&gt;London * #3|Born|D-&gt;23-04-1973 * #4|Value|i-&gt; * </pre> * * @author avackova ([email protected]) ; (c) JavlinConsulting s.r.o. www.javlinconsulting.cz * * @since Nov 16, 2006 * @see org.jetel.component.RecordTransform * @see org.jetel.component.DataRecordTransform */ public class CustomizedRecordTransform implements RecordTransform { protected Properties parameters; protected DataRecordMetadata[] sourceMetadata; protected DataRecordMetadata[] targetMetadata; protected TransformationGraph graph; protected PolicyType fieldPolicy = PolicyType.STRICT; protected boolean useAlternativeRules = false; protected Log logger; protected String errorMessage; /** * Map "rules" stores rules given by user in following form: key: patternOut value: proper descendant of Rule class */ protected DuplicateKeyMap rules = new DuplicateKeyMap(new LinkedHashMap<String, Rule>()); protected Rule[][] transformMapArray;// rules from "rules" map translated for concrete metadata protected ArrayList<Rule[][]> alternativeTransformMapArrays; protected int[][] order;// order for assigning output fields (important if assigning sequence values) protected ArrayList<Integer[][]> alternativeOrder; protected static final int REC_NO = 0; protected static final int FIELD_NO = 1; protected static final char DOT = '.'; protected static final char COLON = ':'; protected static final char PARAMETER_CHAR = '$'; protected static final String[] WILDCARDS = new String[WcardPattern.WCARD_CHAR.length]; static { for (int i = 0; i < WILDCARDS.length; i++) { WILDCARDS[i] = String.valueOf(WcardPattern.WCARD_CHAR[i]); } } protected final static String PARAM_OPCODE_REGEX = "\\$\\{par\\.(.*)\\}"; protected final static Pattern PARAM_PATTERN = Pattern.compile(PARAM_OPCODE_REGEX); protected final static String SEQ_OPCODE_REGEX = "\\$\\{seq\\.(.*)\\}"; protected final static Pattern SEQ_PATTERN = Pattern.compile(SEQ_OPCODE_REGEX); protected final static String FIELD_OPCODE_REGEX = "\\$\\{in\\.(.*)\\}"; protected final static Pattern FIELD_PATTERN = Pattern.compile(FIELD_OPCODE_REGEX); private Object value; /** * @param logger */ public CustomizedRecordTransform(Log logger) { this.logger = logger; } /** * Mathod for adding field mapping rule * * @param patternOut * output field's pattern * @param patternIn * input field's pattern */ public void addFieldToFieldRule(String patternOut, String patternIn) { rules.put(patternOut, new FieldRule(patternIn)); } /** * Mathod for adding field mapping rule * * @param recNo * output record number * @param fieldNo * output record's field number * @param patternIn * input field's pattern */ public void addFieldToFieldRule(int recNo, int fieldNo, String patternIn) { addFieldToFieldRule(String.valueOf(recNo) + DOT + fieldNo, patternIn); } /** * Mathod for adding field mapping rule * * @param recNo * output record number * @param field * output record's field name * @param patternIn * input field's pattern */ public void addFieldToFieldRule(int recNo, String field, String patternIn) { addFieldToFieldRule(String.valueOf(recNo) + DOT + field, patternIn); } /** * Mathod for adding field mapping rule * * @param fieldNo * output record's field number * @param patternIn * input field's pattern */ public void addFieldToFieldRule(int fieldNo, String patternIn) { addFieldToFieldRule(0, fieldNo, patternIn); } /** * Mathod for adding field mapping rule * * @param patternOut * output fields' pattern * @param recNo * input record's number * @param fieldNo * input record's field number */ public void addFieldToFieldRule(String patternOut, int recNo, int fieldNo) { addFieldToFieldRule(patternOut, String.valueOf(recNo) + DOT + fieldNo); } /** * Mathod for adding field mapping rule * * @param patternOut * output fields' pattern * @param recNo * input record's number * @param field * input record's field name */ public void addFieldToFieldRule(String patternOut, int recNo, String field) { addFieldToFieldRule(patternOut, String.valueOf(recNo) + DOT + field); } /** * Mathod for adding field mapping rule * * @param outRecNo * output record's number * @param outFieldNo * output record's field number * @param inRecNo * input record's number * @param inFieldNo * input record's field number */ public void addFieldToFieldRule(int outRecNo, int outFieldNo, int inRecNo, int inFieldNo) { addFieldToFieldRule(String.valueOf(outRecNo) + DOT + outFieldNo, String.valueOf(inRecNo) + DOT + inFieldNo); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign (can be string representation of any type) */ public void addConstantToFieldRule(String patternOut, String source) { rules.put(patternOut, new ConstantRule(source)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, int value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, long value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, double value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, Date value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param patternOut * output fields' pattern * @param value * value to assign */ public void addConstantToFieldRule(String patternOut, Numeric value) { rules.put(patternOut, new ConstantRule(value)); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param source * value value to assign (can be string representation of any type) */ public void addConstantToFieldRule(int recNo, int fieldNo, String source) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, source); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, int value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, long value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, double value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, Date value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, int fieldNo, Numeric value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + fieldNo, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param source * value value to assign (can be string representation of any type) */ public void addConstantToFieldRule(int recNo, String field, String source) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, source); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, int value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, long value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, double value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, Date value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields rule * * @param recNo * output record's number * @param fieldNo * output record's field name * @param value * value value to assign */ public void addConstantToFieldRule(int recNo, String field, Numeric value) { addConstantToFieldRule(String.valueOf(recNo) + DOT + field, value); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param source * value value to assign (can be string representation of any type) */ public void addConstantToFieldRule(int fieldNo, String source) { addConstantToFieldRule(0, fieldNo, source); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, int value) { addConstantToFieldRule(0, fieldNo, String.valueOf(value)); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, long value) { addConstantToFieldRule(0, fieldNo, String.valueOf(value)); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, double value) { addConstantToFieldRule(0, fieldNo, String.valueOf(value)); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, Date value) { addConstantToFieldRule(0, fieldNo, value); } /** * Mathod for adding constant assigning to output fields from 0th output record rule * * @param fieldNo * output record's field number * @param value * value value to assign */ public void addConstantToFieldRule(int fieldNo, Numeric value) { addConstantToFieldRule(0, fieldNo, String.valueOf(value)); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param patternOut * output fields' pattern * @param sequence * sequence ID, optionally with sequence method (can be in form ${seq.seqID}, eg. "MySequence" is the * same as "MySequence.nextIntValue()" or "${seq.MySequence.nextIntValue()}" */ public void addSequenceToFieldRule(String patternOut, String sequence) { String sequenceString = sequence.startsWith("${") ? sequence.substring(sequence.indexOf(DOT) + 1, sequence .length() - 1) : sequence; rules.put(patternOut, new SequenceRule(sequenceString)); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param recNo * output record's number * @param fieldNo * output record's field number * @param sequence * sequence ID, optionally with sequence method (can be in form ${seq.seqID}, eg. "MySequence" is the * same as "MySequence.nextIntValue()" or "${seq.MySequence.nextIntValue()}" */ public void addSequenceToFieldRule(int recNo, int fieldNo, String sequence) { addSequenceToFieldRule(String.valueOf(recNo) + DOT + fieldNo, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param recNo * output record's number * @param field * output record's field name * @param sequence * sequence ID, optionally with sequence method (can be in form ${seq.seqID}, eg. "MySequence" is the * same as "MySequence.nextIntValue()" or "${seq.MySequence.nextIntValue()}" */ public void addSequenceToFieldRule(int recNo, String field, String sequence) { addSequenceToFieldRule(String.valueOf(recNo) + DOT + field, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields in 0th record * * @param fieldNo * output record's field number * @param sequence * sequence ID, optionally with sequence method (can be in form ${seq.seqID}, eg. "MySequence" is the * same as "MySequence.nextIntValue()" or "${seq.MySequence.nextIntValue()}" */ public void addSequenceToFieldRule(int fieldNo, String sequence) { addSequenceToFieldRule(0, fieldNo, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param patternOut * output fields' pattern * @param sequence * sequence for getting value */ public void addSequenceToFieldRule(String patternOut, Sequence sequence) { rules.put(patternOut, new SequenceRule(sequence)); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param recNo * output record's number * @param fieldNo * output record's field number * @param sequence * sequence for getting value */ public void addSequenceToFieldRule(int recNo, int fieldNo, Sequence sequence) { addSequenceToFieldRule(String.valueOf(recNo) + DOT + fieldNo, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields * * @param recNo * output record's number * @param field * output record's field name * @param sequence * sequence for getting value */ public void addSequenceToFieldRule(int recNo, String field, Sequence sequence) { addSequenceToFieldRule(String.valueOf(recNo) + DOT + field, sequence); } /** * Mathod for adding rule: assigning value from sequence to output fields in 0th output record * * @param fieldNo * output record's field number * @param sequence * sequence for getting value */ public void addSequenceToFieldRule(int fieldNo, Sequence sequence) { addSequenceToFieldRule(0, fieldNo, sequence); } /** * Mathod for adding rule: assigning parameter value to output fields * * @param patternOut * output fields' pattern * @param parameterName * (can be in form ${par.parameterName}) */ public void addParameterToFieldRule(String patternOut, String parameterName) { if (parameterName.indexOf(DOT) > -1) { parameterName = parameterName.substring(parameterName.indexOf(DOT) + 1, parameterName.length() - 1); } rules.put(patternOut, new ParameterRule(parameterName)); } /** * Mathod for adding rule: assigning parameter value to output fields * * @param recNo * output record's number * @param fieldNo * output record's field number * @param parameterName * (can be in form ${par.parameterName}) */ public void addParameterToFieldRule(int recNo, int fieldNo, String parameterName) { addParameterToFieldRule(String.valueOf(recNo) + DOT + fieldNo, parameterName); } /** * Mathod for adding rule: assigning parameter value to output fields * * @param recNo * output record's number * @param field * output record's field name * @param parameterName * (can be in form ${par.parameterName}) */ public void addParameterToFieldRule(int recNo, String field, String parameterName) { addParameterToFieldRule(String.valueOf(recNo) + DOT + field, parameterName); } /** * Mathod for adding rule: assigning parameter value to output fields in 0th output record * * @param fieldNo * output record's field number * @param parameterName * (can be in form ${par.parameterName}) */ public void addParameterToFieldRule(int fieldNo, String parameterName) { addParameterToFieldRule(0, fieldNo, parameterName); } /** * Method for adding rule in CloverETL syntax This method calls proper add....Rule depending on syntax of pattern * * @see org.jetel.util.CodeParser * @param patternOut * output field's pattern * @param pattern * rule for output field as: ${par.parameterName}, ${seq.sequenceID}, * ${in.inRecordPattern.inFieldPattern}. If "pattern" doesn't much to any above, it is regarded as * constant. */ public void addRule(String patternOut, String pattern) { Matcher matcher = PARAM_PATTERN.matcher(pattern); if (matcher.find()) { addParameterToFieldRule(patternOut, pattern); } else { matcher = SEQ_PATTERN.matcher(pattern); if (matcher.find()) { addSequenceToFieldRule(patternOut, pattern); } else { matcher = FIELD_PATTERN.matcher(pattern); if (matcher.find()) { addFieldToFieldRule(patternOut, pattern); } else { addConstantToFieldRule(patternOut, pattern); } } } } /** * This method deletes rule for given fields, which was set before * * @param patternOut * output field pattern for deleting rule */ public void deleteRule(String patternOut) { rules.put(patternOut, new DeleteRule()); } /** * This method deletes rule for given field, which was set before * * @param outRecNo * output record number * @param outFieldNo * output record's field number */ public void deleteRule(int outRecNo, int outFieldNo) { String patternOut = String.valueOf(outRecNo) + DOT + outFieldNo; rules.put(patternOut, new DeleteRule()); } /** * This method deletes rule for given field, which was set before * * @param outRecNo * output record number * @param outField * output record's field name */ public void deleteRule(int outRecNo, String outField) { String patternOut = String.valueOf(outRecNo) + DOT + outField; rules.put(patternOut, new DeleteRule()); } /** * This method deletes rule for given field in 0th output record, which was set before * * @param outFieldNo * output record's field number */ public void deleteRule(int outFieldNo) { String patternOut = String.valueOf(0) + DOT + outFieldNo; rules.put(patternOut, new DeleteRule()); } public void finished() { // TODO Auto-generated method stub } public TransformationGraph getGraph() { return graph; } public String getMessage() { return errorMessage; } public Object getSemiResult() { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see org.jetel.component.RecordTransform#init(java.util.Properties, org.jetel.metadata.DataRecordMetadata[], * org.jetel.metadata.DataRecordMetadata[]) */ public boolean init(Properties parameters, DataRecordMetadata[] sourcesMetadata, DataRecordMetadata[] targetMetadata) throws ComponentNotReadyException { if (sourcesMetadata == null || targetMetadata == null) { return false; } this.parameters = parameters; this.sourceMetadata = sourcesMetadata; this.targetMetadata = targetMetadata; return init(); } /** * Checks if given string contans wild cards * * @see WcardPattern * * @param str * @return */ private boolean containsWCard(String str) { for (int i = 0; i < WILDCARDS.length; i++) { if (str.contains(WILDCARDS[i])) { return true; } } return false; } /** * Method with initialize user customized transformation with concrete metadata * * @return * @throws ComponentNotReadyException */ private boolean init() throws ComponentNotReadyException { // map storing transformation for concrete output fields // key is in form: recNumber.fieldNumber Map<String, Rule> transformMap = new LinkedHashMap<String, Rule>(); ArrayList<Map<String, Rule>> alternativeTransformMaps = new ArrayList<Map<String, Rule>>(); Entry<String, ArrayList<Rule>> rulesEntry; String field; String ruleString = null; String[] outFields = new String[0]; String[] inFields; // iteration over each user given rule for (Iterator<Entry<String, ArrayList<Rule>>> iterator = rules.entrySet().iterator(); iterator.hasNext();) { rulesEntry = iterator.next(); for (Rule rule : rulesEntry.getValue()) { rule.setGraph(getGraph()); rule.setLogger(logger); rule.setProperties(parameters); // find output fields pattern field = resolveField(rulesEntry.getKey()); if (field == null) { errorMessage = "Wrong pattern for output fields: " + rulesEntry.getKey(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } // find output fields from pattern outFields = findFields(field, targetMetadata).toArray(new String[0]); if (outFields.length == 0) { errorMessage = "There is no output field matching \"" + field + "\" pattern"; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } inFields = new String[0]; if (rule instanceof DeleteRule) { for (int i = 0; i < outFields.length; i++) { rule = transformMap.remove(outFields[i]); } continue; } if (rule instanceof FieldRule) { // find input fields from pattern ruleString = resolveField(rule.getSource()); if (ruleString == null) { errorMessage = "Wrong pattern for output fields: " + ruleString; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } inFields = findFields(ruleString, sourceMetadata).toArray(new String[0]); if (inFields.length == 0) { errorMessage = "There is no input field matching \"" + ruleString + "\" pattern"; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } if (rule instanceof FieldRule && inFields.length > 1) { // find mapping by names if (putMappingByNames(transformMap, alternativeTransformMaps, outFields, inFields, rule.getSource()) == 0) { if (!useAlternativeRules) { errorMessage = "Not found any field for mapping by names due to rule:\n" + field + " - output fields pattern\n" + ruleString + " - input fields pattern"; logger.warn(errorMessage); } } } else {// for each output field the same rule // for each output field from pattern, put rule to map for (int i = 0; i < outFields.length; i++) { if (!containsWCard(field) || !transformMap.containsKey(outFields[i])) {// check primary map transformMap.put(outFields[i], rule.duplicate()); } else if (useAlternativeRules) {// rule is in primery map --> put to alternative map putRuleInAlternativeMap(outFields[i], rule, alternativeTransformMaps); } } } } } // changing map to array transformMapArray = new Rule[targetMetadata.length][maxNumFields(targetMetadata)]; order = new int[transformMap.size()][2]; int index = 0; for (Entry<String, Rule> i : transformMap.entrySet()) { field = i.getKey(); order[index][REC_NO] = getRecNo(field); order[index][FIELD_NO] = getFieldNo(field); transformMapArray[order[index][REC_NO]][order[index][FIELD_NO]] = i.getValue(); transformMapArray[order[index][REC_NO]][order[index][FIELD_NO]].init(sourceMetadata, targetMetadata, getRecNo(field), getFieldNo(field), fieldPolicy); index++; } // create and initialize alternative rules if (useAlternativeRules && alternativeTransformMaps.size() > 0) { alternativeTransformMapArrays = new ArrayList<Rule[][]>(alternativeTransformMaps.size()); alternativeOrder = new ArrayList<Integer[][]>(alternativeTransformMaps.size()); for (Map<String, Rule> map : alternativeTransformMaps) { Rule[][] ruleArray = new Rule[targetMetadata.length][maxNumFields(targetMetadata)]; alternativeTransformMapArrays.add(ruleArray); Integer[][] orderArray = new Integer[map.size()][2]; alternativeOrder.add(orderArray); index = 0; for (Entry<String, Rule> i : map.entrySet()) { field = i.getKey(); order[index][REC_NO] = getRecNo(field); order[index][FIELD_NO] = getFieldNo(field); ruleArray[order[index][REC_NO]][order[index][FIELD_NO]] = i.getValue(); ruleArray[order[index][REC_NO]][order[index][FIELD_NO]].init(sourceMetadata, targetMetadata, getRecNo(field), getFieldNo(field), fieldPolicy); index++; } } } return true; } /** * This method puts rule to the alternative map, which doesn't contain rule for this field. If all alternative maps * contain rule for requested field, new map is created and added to list * * @param field * output field * @param rule * rule to put * @param alternativeTransformMaps * list of alternative maps * @return */ private void putRuleInAlternativeMap(String field, Rule rule, List<Map<String, Rule>> alternativeTransformMaps) { for (Map<String, Rule> map : alternativeTransformMaps) { if (!map.containsKey(field)) { map.put(field, rule.duplicate()); return; } } // all maps checked --> create new one Map<String, Rule> newMap = new LinkedHashMap<String, Rule>(); alternativeTransformMaps.add(newMap); newMap.put(field, rule.duplicate()); } /** * Method, which puts mapping rules to map. First it tries to find fields with identical names in corresponding * input and output metadata. If not all output fields were found it tries to find them in other input records. If * not all output fields were found it tries to find fields with the same names ignoring case in corresponding * record. If still there are some output fields without paire it tries to find fields with the same name ignoring * case in other records, eg.<br> * outFieldsNames:<br> * <ul> * <li>lname, fname, address, phone</li> * <li>Lname, fname, id</li> * </ul> * inFieldsNames: * <ul> * <li>Lname, fname, id, address</li> * <li>lname, fname, phone</li> * </ul> * Mapping: * <ul> * <li>0.0 <-- 1.0</li> * <li>0.1 <-- 0.1</li> * <li>0.2 <-- 0.3</li> * <li>0.3 <-- 1.2</li> * <li>1.0 <-- 0.0</li> * <li>1.1 <-- 1.1</li> * <li>1.2 <-- 0.2</li> * </ul> * * @param transformMap * map to put rules * @param alternativeMaps * list of alternative maps, used if useAlternativeRules=true and primery map contains output field * @param outFields * output fields to mapping * @param inFields * input fields for mapping * @return number of mappings put to transform map */ protected int putMappingByNames(Map<String, Rule> transformMap, List<Map<String, Rule>> alternativeMaps, String[] outFields, String[] inFields, String rule) throws ComponentNotReadyException { int count = 0; String[][] outFieldsName = new String[targetMetadata.length][maxNumFields(targetMetadata)]; for (int i = 0; i < outFields.length; i++) { outFieldsName[getRecNo(outFields[i])][getFieldNo(outFields[i])] = targetMetadata[getRecNo(outFields[i])] .getField(getFieldNo(outFields[i])).getName(); } String[][] inFieldsName = new String[sourceMetadata.length][maxNumFields(sourceMetadata)]; for (int i = 0; i < inFields.length; i++) { inFieldsName[getRecNo(inFields[i])][getFieldNo(inFields[i])] = sourceMetadata[getRecNo(inFields[i])] .getField(getFieldNo(inFields[i])).getName(); } int index; // find identical in corresponding records for (int i = 0; (i < outFieldsName.length) && (i < inFieldsName.length); i++) { for (int j = 0; j < outFieldsName[i].length; j++) { if (outFieldsName[i][j] != null) { index = StringUtils.findString(outFieldsName[i][j], inFieldsName[i]); if (index > -1) {// output field name found amoung input fields if (putMapping(i, j, i, index, rule, transformMap, alternativeMaps)) { count++; outFieldsName[i][j] = null; inFieldsName[i][index] = null; } } } } } // find identical in other records for (int i = 0; i < outFieldsName.length; i++) { for (int j = 0; j < outFieldsName[i].length; j++) { for (int k = 0; k < inFieldsName.length; k++) { if ((outFieldsName[i][j] != null) && (k != i)) { index = StringUtils.findString(outFieldsName[i][j], inFieldsName[k]); if (index > -1) {// output field name found amoung input fields if (putMapping(i, j, k, index, rule, transformMap, alternativeMaps)) { count++; outFieldsName[i][j] = null; inFieldsName[k][index] = null; } } } } } } // find ignore case in corresponding records for (int i = 0; (i < outFieldsName.length) && (i < inFieldsName.length); i++) { for (int j = 0; j < outFieldsName[i].length; j++) { if (outFieldsName[i][j] != null) { index = StringUtils.findStringIgnoreCase(outFieldsName[i][j], inFieldsName[i]); if (index > -1) {// output field name found amoung input fields if (putMapping(i, j, i, index, rule, transformMap, alternativeMaps)) { count++; outFieldsName[i][j] = null; inFieldsName[i][index] = null; } } } } } // find ignore case in other records for (int i = 0; i < outFieldsName.length; i++) { for (int j = 0; j < outFieldsName[i].length; j++) { for (int k = 0; k < inFieldsName.length; k++) { if ((outFieldsName[i][j] != null) && (k != i)) { index = StringUtils.findStringIgnoreCase(outFieldsName[i][j], inFieldsName[k]); if (index > -1) {// output field name found amoung input fields if (putMapping(i, j, k, index, rule, transformMap, alternativeMaps)) { count++; outFieldsName[i][j] = null; inFieldsName[k][index] = null; } } } } } } return count; } /** * This method puts mapping into given output and input field to transform map if theese fields have correct types * due to policy type * * @param outRecNo * number of record from output metadata * @param outFieldNo * number of field from output metadata * @param inRecNo * number of record from input metadata * @param inFieldNo * number of field from input metadata * @param transformMap * @param alternativeMaps * list of alternative maps, used if useAlternativeRules=true and primery map contains output field * @return true if mapping was put into map, false in other case */ protected boolean putMapping(int outRecNo, int outFieldNo, int inRecNo, int inFieldNo, String ruleString, Map<String, Rule> transformMap, List<Map<String, Rule>> alternativeMaps) throws ComponentNotReadyException { if (!Rule.checkTypes(targetMetadata[outRecNo].getField(outFieldNo), sourceMetadata[inRecNo].getField(inFieldNo), fieldPolicy)) { if (fieldPolicy == PolicyType.STRICT) { logger.warn("Found fields with the same names but other types: "); logger.warn(targetMetadata[outRecNo].getName() + DOT + targetMetadata[outRecNo].getField(outFieldNo).getName() + " type - " + targetMetadata[outRecNo].getFieldTypeAsString(outFieldNo) + getDecimalParams(targetMetadata[outRecNo].getField(outFieldNo))); logger.warn(sourceMetadata[inRecNo].getName() + DOT + sourceMetadata[inRecNo].getField(inFieldNo).getName() + " type - " + sourceMetadata[inRecNo].getFieldTypeAsString(inFieldNo) + getDecimalParams(sourceMetadata[inRecNo].getField(inFieldNo))); } if (fieldPolicy == PolicyType.CONTROLLED) { logger.warn("Found fields with the same names but incompatible types: "); logger.warn(targetMetadata[outRecNo].getName() + DOT + targetMetadata[outRecNo].getField(outFieldNo).getName() + " type - " + targetMetadata[outRecNo].getFieldTypeAsString(outFieldNo) + getDecimalParams(targetMetadata[outRecNo].getField(outFieldNo))); logger.warn(sourceMetadata[inRecNo].getName() + DOT + sourceMetadata[inRecNo].getField(inFieldNo).getName() + " type - " + sourceMetadata[inRecNo].getFieldTypeAsString(inFieldNo) + getDecimalParams(sourceMetadata[inRecNo].getField(inFieldNo))); } return false; } else {// map fields FieldRule rule = new FieldRule(ruleString); rule.setFieldParams(String.valueOf(inRecNo) + DOT + inFieldNo); if (!transformMap.containsKey(String.valueOf(outRecNo) + DOT + outFieldNo)) { transformMap.put(String.valueOf(outRecNo) + DOT + outFieldNo, rule); } else if (useAlternativeRules) { putRuleInAlternativeMap(String.valueOf(outRecNo) + DOT + outFieldNo, rule, alternativeMaps); } return true; } } /** * Finds fields from metadata matching given pattern * * @param pattern * @param metadata * @return list of fields matching given metadata */ public static ArrayList<String> findFields(String pattern, DataRecordMetadata[] metadata) { ArrayList<String> list = new ArrayList<String>(); String recordNoString = pattern.substring(0, pattern.indexOf(DOT)); String fieldNoString = pattern.substring(pattern.indexOf(DOT) + 1); int fieldNo; int recNo; try {// check if first part of pattern is "real" pattern or number of record recNo = Integer.parseInt(recordNoString); try {// we have one record Number // check if second part of pattern is "real" pattern or number of field fieldNo = Integer.parseInt(fieldNoString); // we have one record field number list.add(pattern); } catch (NumberFormatException e) {// second part of pattern is not a number // find matching fields for (int i = 0; i < metadata[recNo].getNumFields(); i++) { if (WcardPattern.checkName(fieldNoString, metadata[recNo].getField(i).getName())) { list.add(String.valueOf(recNo) + DOT + i); } } } } catch (NumberFormatException e) {// first part of pattern is not a number // check all matadata names if match pattern for (int i = 0; i < metadata.length; i++) { if (WcardPattern.checkName(recordNoString, metadata[i].getName())) { try {// check if second part of pattern is "real" pattern or number of field fieldNo = Integer.parseInt(fieldNoString); // we have matching metadata name and field number list.add(String.valueOf(i) + DOT + fieldNoString); } catch (NumberFormatException e1) {// second part of pattern is not a number // find matching fields for (int j = 0; j < metadata[i].getNumFields(); j++) { if (WcardPattern.checkName(fieldNoString, metadata[i].getField(j).getName())) { list.add(String.valueOf(i) + DOT + j); } } } } } } return list; } public void setGraph(TransformationGraph graph) { this.graph = graph; } public void signal(Object signalObject) { // TODO Auto-generated method stub } /** * Fills error message and throws exception * * @param ruleArray * @param recNo * @param FieldNo * @param ex * @throws TransformException */ private void throwException(Rule[][] ruleArray, int recNo, int FieldNo, Exception ex) throws TransformException { errorMessage = "TransformException caused by source: " + ruleArray[recNo][FieldNo].getSource(); logger.error(errorMessage, ex); throw new TransformException(errorMessage, ex, recNo, FieldNo); } /* * (non-Javadoc) * * @see org.jetel.component.RecordTransform#transform(org.jetel.data.DataRecord[], org.jetel.data.DataRecord[]) */ public boolean transform(DataRecord[] sources, DataRecord[] target) throws TransformException { // array "order" stores coordinates of output fields in order they will be assigned for (int i = 0; i < order.length; i++) { value = transformMapArray[order[i][REC_NO]][order[i][FIELD_NO]].getValue(sources); if (value != null || !useAlternativeRules) { try { target[order[i][REC_NO]].getField(order[i][FIELD_NO]).setValue(value); } catch (BadDataFormatException e) { // we can try to change value to String and set to output field if (value != null && fieldPolicy != PolicyType.STRICT) { try { target[order[i][REC_NO]].getField(order[i][FIELD_NO]).fromString(value.toString()); } catch (BadDataFormatException e1) { if (!useAlternativeRules || !setAlternativeValue(sources, target, order[i][REC_NO], order[i][FIELD_NO], 0, e1)) { throwException(transformMapArray, order[i][REC_NO], order[i][FIELD_NO], e1); } } } else if (!useAlternativeRules || !setAlternativeValue(sources, target, order[i][REC_NO], order[i][FIELD_NO], 0, e)) {// value // is // null // or // value // can't // be // set // to // field throwException(transformMapArray, order[i][REC_NO], order[i][FIELD_NO], e); } } } else {// value is null and useuseAlternativeRules = true setAlternativeValue(sources, target, order[i][REC_NO], order[i][FIELD_NO], 0, null); } } return true; } /** * Tries to set value due to given alternative rule * * @param sources * source records * @param target * target records * @param trgRec * target record number * @param trgField * target field number * @param alternativeRuleNumber * @param cause * why we call alternative rule * @return true if value was set, in other case throws TransformException * @throws TransformException */ private boolean setAlternativeValue(DataRecord[] sources, DataRecord[] target, int trgRec, int trgField, int alternativeRuleNumber, Exception cause) throws TransformException { Rule[][] ruleArray = alternativeTransformMapArrays.get(alternativeRuleNumber); if (ruleArray[trgRec][trgField] == null) { throwException(ruleArray, trgRec, trgField, cause); } value = ruleArray[trgRec][trgField].getValue(sources); if (value != null) { try { target[trgRec].getField(trgField).setValue(value); return true; } catch (BadDataFormatException e) { if (fieldPolicy != PolicyType.STRICT) { try { target[trgRec].getField(trgField).fromString(value.toString()); return true; } catch (BadDataFormatException e1) { if (++alternativeRuleNumber < alternativeTransformMapArrays.size()) { return setAlternativeValue(sources, target, trgRec, trgField, alternativeRuleNumber, e1); } else { throwException(ruleArray, trgRec, trgField, e1); } } } else if (++alternativeRuleNumber < alternativeTransformMapArrays.size()) { return setAlternativeValue(sources, target, trgRec, trgField, alternativeRuleNumber, e); } else { throwException(ruleArray, trgRec, trgField, e); } } } else if (++alternativeRuleNumber < alternativeTransformMapArrays.size()) { return setAlternativeValue(sources, target, trgRec, trgField, alternativeRuleNumber, cause); } else {// value is null try { target[trgRec].getField(trgField).setValue(value); return true; } catch (BadDataFormatException e) { throwException(ruleArray, trgRec, trgField, e); } } return true; } /** * Changes pattern given in one of possible format to record.field * * @param pattern * @return pattern in format record.field of null if it is not possible */ public static String resolveField(String pattern) { String[] parts = pattern.split("\\."); switch (parts.length) { case 2: if (parts[0].startsWith(Defaults.CLOVER_FIELD_INDICATOR)) {// ${recNo.field} return parts[0].substring(2) + DOT + parts[1].substring(0, parts[1].length() - 1); } else {// recNo.field return pattern; } case 3: if (parts[0].startsWith(Defaults.CLOVER_FIELD_INDICATOR)) {// ${in/out.recNo.field} return parts[1] + DOT + parts[2].substring(0, parts[2].length() - 1); } else {// in/out.recNo.field return parts[1] + DOT + parts[2]; } default: return null; } } /** * Gets rule in form they were set by user * * @return rules */ public ArrayList<String> getRulesAsStrings() { ArrayList<String> list = new ArrayList<String>(); Entry<String, ArrayList<Rule>> entry; ArrayList<Rule> subList; for (Iterator<Entry<String, ArrayList<Rule>>> iterator = rules.entrySet().iterator(); iterator.hasNext();) { entry = iterator.next(); subList = entry.getValue(); for (int i = 0; i < subList.size(); i++) { list.add(subList.get(i).getType() + ":" + entry.getKey() + "=" + subList.get(i).getSource()); } } return list; } /** * Gets rules for concrete metadata in well readable form * * @return resolved rules */ public ArrayList<String> getResolvedRules() { ArrayList<String> list = new ArrayList<String>(); String value; for (int recNo = 0; recNo < transformMapArray.length; recNo++) { for (int fieldNo = 0; fieldNo < transformMapArray[0].length; fieldNo++) { if (transformMapArray[recNo][fieldNo] != null) { value = transformMapArray[recNo][fieldNo].getCanonicalSource() != null ? transformMapArray[recNo][fieldNo] .getCanonicalSource().toString() : "null"; list.add(targetMetadata[recNo].getName() + DOT + targetMetadata[recNo].getField(fieldNo).getName() + "=" + value); } } } return list; } /** * Gets output fields, for which there wasn't set any rule * * @return indexes (output record number, output field number) of fields without rule */ public ArrayList<Integer[]> getFieldsWithoutRules() { ArrayList<Integer[]> list = new ArrayList<Integer[]>(); for (int recNo = 0; recNo < transformMapArray.length; recNo++) { for (int fieldNo = 0; fieldNo < transformMapArray[0].length; fieldNo++) { if (fieldNo < targetMetadata[recNo].getNumFields() && transformMapArray[recNo][fieldNo] == null) { list.add(new Integer[] { recNo, fieldNo }); } } } return list; } /** * Gets input fields not mapped on output fields * * @return indexes (output record number, output field number) of not used input fields */ public ArrayList<Integer[]> getNotUsedFields() { String[] inFields = findFields("*.*", sourceMetadata).toArray(new String[0]); Rule rule; int index; String field; for (int recNo = 0; recNo < transformMapArray.length; recNo++) { for (int fieldNo = 0; fieldNo < transformMapArray[0].length; fieldNo++) { rule = transformMapArray[recNo][fieldNo]; if (rule != null && rule instanceof FieldRule) { field = (String) rule.getCanonicalSource(); index = StringUtils.findString(field, inFields); if (index != -1) { inFields[index] = null; } } } } ArrayList<Integer[]> list = new ArrayList<Integer[]>(); for (int i = 0; i < inFields.length; i++) { if (inFields[i] != null) { list.add(new Integer[] { getRecNo(inFields[i]), getFieldNo(inFields[i]) }); } } return list; } /** * Gets rule for given output field * * @param recNo * output record number * @param fieldNo * output record's field number * @return rule for given output field */ public String getRule(int recNo, int fieldNo) { Rule rule = transformMapArray[recNo][fieldNo]; if (rule == null) { return null; } return (rule.getType()) + COLON + rule.getCanonicalSource(); } /** * Gets output fields, which mapped given input field * * @param inRecNo * input record number * @param inFieldNo * input record's field number * @return indexes (output record number, output field number) of fields, which mapped given input field */ public ArrayList<Integer[]> getRulesWithField(int inRecNo, int inFieldNo) { ArrayList<Integer[]> list = new ArrayList<Integer[]>(); Rule rule; for (int recNo = 0; recNo < transformMapArray.length; recNo++) { for (int fieldNo = 0; fieldNo < transformMapArray[0].length; fieldNo++) { rule = transformMapArray[recNo][fieldNo]; if (rule != null && rule instanceof FieldRule) { if (getRecNo((String) rule.getCanonicalSource()) == inRecNo && getFieldNo((String) rule.getCanonicalSource()) == inFieldNo) { list.add(new Integer[] { recNo, fieldNo }); } } } } return list; } public PolicyType getFieldPolicy() { return fieldPolicy; } /** * Sets the field policy: * <ul> * <li>PolicyType.STRICT - mapped output and input fields have to be of the same types * <li>PolicyType.CONTROLLED - mapped input fields have to be subtypes of output fields<br> * <li>PolicyType.LENIENT - field's types are not checked during initialization * </ul> * For PolicyType CONTROLLED and LENIENT method transform can work slower as for not identical types for is called * method fromString, when method setValue has failed. * * @param fieldPolicy */ public void setFieldPolicy(PolicyType fieldPolicy) { this.fieldPolicy = fieldPolicy; } /** * Finds maximal length of metadata * * @param metadata * @return maximal length of metadatas */ private int maxNumFields(DataRecordMetadata[] metadata) { int numFields = 0; for (int i = 0; i < metadata.length; i++) { if (metadata[i].getNumFields() > numFields) { numFields = metadata[i].getNumFields(); } } return numFields; } /** * Gets part of string before . and changed it to Integer * * @param recField * recNo.FieldNo * @return record number */ public static Integer getRecNo(String recField) { return Integer.valueOf(recField.substring(0, recField.indexOf(DOT))); } /** * Gets part of string after . and changed it to Integer * * @param recField * @return field number */ public static Integer getFieldNo(String recField) { return Integer.valueOf(recField.substring(recField.indexOf(DOT) + 1)); } /** * This method gets LENGTH and SCALE from decimal data field * * @param field * @return string (LENGTH,SCALE) */ public static String getDecimalParams(DataFieldMetadata field) { if (field.getType() != DataFieldMetadata.DECIMAL_FIELD) { return ""; } StringBuilder params = new StringBuilder(5); params.append('('); params.append(field.getProperty(DataFieldMetadata.LENGTH_ATTR)); params.append(','); params.append(field.getProperty(DataFieldMetadata.SCALE_ATTR)); params.append(')'); return params.toString(); } /* * (non-Javadoc) * * @see org.jetel.component.RecordTransform#reset() */ public void reset() { errorMessage = null; } public void setLogger(Log logger) { this.logger = logger; } /** * @return if transformation uses alternative rules * * @see setUseAlternativeRules */ public boolean isUseAlternativeRules() { return useAlternativeRules; } /** * Switchs on/off alternative rules. When alternative rules are switched on, more rules can be used for one field: * if value from primery rule is null or transformations failed trying to set it, there are used lternative rules. * Tranasformation fails if value of noone rule can be set to requested field. * * @param useAlternativeRules */ public void setUseAlternativeRules(boolean useAlternativeRules) { this.useAlternativeRules = useAlternativeRules; } }// class CustomizedRecordTransform /** * Private class for storing transformation rules */ abstract class Rule { Object value; String source; String errorMessage; Log logger; TransformationGraph graph; Properties parameters; Rule(String source) { this.source = source; } Rule(Object value) { this.value = value; } String getSource() { return source; } public void setLogger(Log logger) { this.logger = logger; } public void setGraph(TransformationGraph graph) { this.graph = graph; } public void setProperties(Properties parameters) { this.parameters = parameters; } abstract Rule duplicate(); abstract String getType(); abstract Object getCanonicalSource(); /** * Gets value for setting to data field * * @param sources * source data record (used only in Field rule) * @return value to be set to data field */ abstract Object getValue(DataRecord[] sources); /** * Prepares rule (source, value and check if value can be got) for getting values in transform method of * CustomizedRecordTransform class * * @param sourceMetadata * @param targetMetadata * @param recNo * output metadata number (from targetMetadata) * @param fieldNo * output field number * @param policy * field policy * @throws ComponentNotReadyException */ abstract void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException; /** * This method checks if input field is subtype of output type * * @param outRecNo * output record number * @param outFieldNo * output record's field number * @param inRecNo * input record number * @param inFieldNo * input record's field number * @return "true" if input field is subtype of output field, "false" in other cases */ public static boolean checkTypes(DataFieldMetadata outField, DataFieldMetadata inField, PolicyType policy) { boolean checkTypes; // check if both fields are of type DECIMAL, if yes inField must be subtype of outField if (outField.getType() == inField.getType()) { if (outField.getType() == DataFieldMetadata.DECIMAL_FIELD) { checkTypes = inField.isSubtype(outField); } else { checkTypes = true; } } else { checkTypes = false; } if (policy == PolicyType.STRICT && !checkTypes) { return false; } else if (policy == PolicyType.CONTROLLED && !inField.isSubtype(outField)) { return false; } return true; } } /** * Descendent of Rule class for storing field's mapping rule */ class FieldRule extends Rule { String fieldParams;// "recNo.fieldNo" = "resolved source" - it have to be set by setFieldParams method FieldRule(String source) { super(source); } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { if (fieldParams == null) { // try find ONE field in source metadata matching source fieldParams = CustomizedRecordTransform.resolveField(source); ArrayList<String> tmp = CustomizedRecordTransform.findFields(fieldParams, sourceMetadata); if (tmp.size() != 1) { throw new ComponentNotReadyException("Field parameters are " + "not set and can't be resolved from source: " + source); } fieldParams = tmp.get(0); } // check input and output fields types if (!checkTypes(targetMetadata[recNo].getField(fieldNo), sourceMetadata[CustomizedRecordTransform .getRecNo(fieldParams)].getField(CustomizedRecordTransform.getFieldNo(fieldParams)), policy)) { if (policy == PolicyType.STRICT) { errorMessage = "Output field type does not match input field " + "type:\n" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + " type - " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(targetMetadata[recNo].getField(fieldNo)) + "\n" + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getName() + CustomizedRecordTransform.DOT + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getField( CustomizedRecordTransform.getFieldNo(fieldParams)).getName() + " type - " + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getField( CustomizedRecordTransform.getFieldNo(fieldParams)).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(sourceMetadata[CustomizedRecordTransform .getRecNo(fieldParams)].getField(CustomizedRecordTransform.getFieldNo(fieldParams))); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } if (policy == PolicyType.CONTROLLED) { errorMessage = "Output field type is not compatible with input field " + "type:\n" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + " type - " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(targetMetadata[recNo].getField(fieldNo)) + "\n" + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getName() + CustomizedRecordTransform.DOT + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getField( CustomizedRecordTransform.getFieldNo(fieldParams)).getName() + " type - " + sourceMetadata[CustomizedRecordTransform.getRecNo(fieldParams)].getField( CustomizedRecordTransform.getFieldNo(fieldParams)).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(sourceMetadata[CustomizedRecordTransform .getRecNo(fieldParams)].getField(CustomizedRecordTransform.getFieldNo(fieldParams))); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } } public void setFieldParams(String fieldParams) { this.fieldParams = fieldParams; } @Override Object getCanonicalSource() { return fieldParams; } @Override String getType() { return "FIELD_RULE"; } /* * (non-Javadoc) * * @see org.jetel.component.Rule#getValue(org.jetel.data.DataRecord[]) * */ @Override Object getValue(DataRecord[] sources) { int dotIndex = fieldParams.indexOf(CustomizedRecordTransform.DOT); int recNo = dotIndex > -1 ? Integer.parseInt(fieldParams.substring(0, dotIndex)) : 0; int fieldNo = dotIndex > -1 ? Integer.parseInt(fieldParams.substring(dotIndex + 1)) : Integer .parseInt(fieldParams); return sources[recNo].getField(fieldNo).getValue(); } @Override Rule duplicate() { FieldRule duplicate = new FieldRule(source); duplicate.setFieldParams(fieldParams); duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } } /** * Descendent of Rule class for storing sequence rule */ class SequenceRule extends Rule { String method;// sequence Id with one of squence method used for // getting value from sequence eg.: // seq1.nextValueString() SequenceRule(String source) { super(source); } SequenceRule(Object value) { super(value); if (!(value instanceof Sequence)) { throw new IllegalArgumentException("Sequence rule doesn't accept " + value.getClass().getName() + " argument"); } source = ((Sequence) value).getId(); } @Override Rule duplicate() { SequenceRule duplicate; if (value != null) { duplicate = new SequenceRule(value); } else { duplicate = new SequenceRule(source); } duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } @Override String getType() { return "SEQUENCE_RULE"; } @Override Object getCanonicalSource() { return method; } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { // prepare sequence and method String sequenceID = source.indexOf(CustomizedRecordTransform.DOT) == -1 ? source : source.substring(0, source .indexOf(CustomizedRecordTransform.DOT)); if (value == null) { value = graph.getSequence(sequenceID); } if (value == null) { logger.warn("There is no sequence \"" + sequenceID + "\" in graph"); if (!(targetMetadata[recNo].getField(fieldNo).isNullable() || targetMetadata[recNo].getField(fieldNo) .isDefaultValue())) { errorMessage = "Null value not allowed to record: " + targetMetadata[recNo].getName() + " , field: " + targetMetadata[recNo].getField(fieldNo).getName(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } else { method = "null"; return; } } // check sequence method String method = source.indexOf(CustomizedRecordTransform.DOT) > -1 ? source.substring(source .indexOf(CustomizedRecordTransform.DOT) + 1) : null; char methodType = DataFieldMetadata.UNKNOWN_FIELD; if (method != null) { this.method = method; if (method.toLowerCase().startsWith("currentvaluestring") || method.toLowerCase().startsWith("currentstring") || method.toLowerCase().startsWith("nextvaluestring") || method.toLowerCase().startsWith("nextstring")) { methodType = DataFieldMetadata.STRING_FIELD; } if (method.toLowerCase().startsWith("currentvalueint") || method.toLowerCase().startsWith("currentint") || method.toLowerCase().startsWith("nextvalueint") || method.toLowerCase().startsWith("nextint")) { methodType = DataFieldMetadata.INTEGER_FIELD; } if (method.toLowerCase().startsWith("currentvaluelong") || method.toLowerCase().startsWith("currentlong") || method.toLowerCase().startsWith("nextvaluelong") || method.toLowerCase().startsWith("nextlong")) { methodType = DataFieldMetadata.LONG_FIELD; } } else {// method is not given, prepare the best switch (targetMetadata[recNo].getField(fieldNo).getType()) { case DataFieldMetadata.BYTE_FIELD: case DataFieldMetadata.BYTE_FIELD_COMPRESSED: case DataFieldMetadata.STRING_FIELD: this.method = sequenceID + CustomizedRecordTransform.DOT + "nextValueString()"; methodType = DataFieldMetadata.STRING_FIELD; break; case DataFieldMetadata.DECIMAL_FIELD: case DataFieldMetadata.LONG_FIELD: case DataFieldMetadata.NUMERIC_FIELD: this.method = sequenceID + CustomizedRecordTransform.DOT + "nextValueLong()"; methodType = DataFieldMetadata.LONG_FIELD; break; case DataFieldMetadata.INTEGER_FIELD: this.method = sequenceID + CustomizedRecordTransform.DOT + "nextValueInt()"; methodType = DataFieldMetadata.INTEGER_FIELD; break; default: errorMessage = "Can't set sequence to data field of type: " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + " (" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + ")"; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } DataFieldMetadata tmp; if (methodType == DataFieldMetadata.UNKNOWN_FIELD) { errorMessage = "Unknown sequence method: " + method; logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } else { tmp = new DataFieldMetadata("tmp", methodType, ";"); } // check if value from sequence can be set to given field if (!checkTypes(targetMetadata[recNo].getField(fieldNo), tmp, policy)) { if (policy == PolicyType.STRICT) { errorMessage = "Sequence method:" + this.method + " does not " + "match field type:\n" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + " type - " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(targetMetadata[recNo].getField(fieldNo)); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } if (policy == PolicyType.CONTROLLED) { errorMessage = "Sequence method:" + this.method + " does not " + "match field type:\n" + targetMetadata[recNo].getName() + CustomizedRecordTransform.DOT + targetMetadata[recNo].getField(fieldNo).getName() + " type - " + targetMetadata[recNo].getField(fieldNo).getTypeAsString() + CustomizedRecordTransform.getDecimalParams(targetMetadata[recNo].getField(fieldNo)); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } } } /* * (non-Javadoc) * * @see org.jetel.component.Rule#getValue(org.jetel.data.DataRecord[]) */ @Override Object getValue(DataRecord[] sources) { if (value == null) { return null; } int dotIndex = method.indexOf(CustomizedRecordTransform.DOT); String method = this.method.substring(dotIndex + 1); if (method.toLowerCase().startsWith("currentvaluestring") || method.toLowerCase().startsWith("currentstring")) { return ((Sequence) value).currentValueString(); } if (method.toLowerCase().startsWith("nextvaluestring") || method.toLowerCase().startsWith("nextstring")) { return ((Sequence) value).nextValueString(); } if (method.toLowerCase().startsWith("currentvalueint") || method.toLowerCase().startsWith("currentint")) { return ((Sequence) value).currentValueInt(); } if (method.toLowerCase().startsWith("nextvalueint") || method.toLowerCase().startsWith("nextint")) { return ((Sequence) value).nextValueInt(); } if (method.toLowerCase().startsWith("currentvaluelong") || method.toLowerCase().startsWith("currentlong")) { return ((Sequence) value).currentValueLong(); } if (method.toLowerCase().startsWith("nextvaluelong") || method.toLowerCase().startsWith("nextlong")) { return ((Sequence) value).nextValueLong(); } // in method validateRule checked, that has to be one of method above return null; } } /** * Descendent of Rule class for storing constant rule */ class ConstantRule extends Rule { /** * Constructor for setting constant as string * * @param source */ ConstantRule(String source) { super(source); } /** * Constructor for setting constant as expected Object (due to data field type) * * @param value */ ConstantRule(Object value) { super(value); } @Override Rule duplicate() { ConstantRule duplicate; if (value != null) { duplicate = new ConstantRule(value); } else { duplicate = new ConstantRule(source); } duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } @Override String getType() { return "CONSTANT_RULE"; } @Override Object getCanonicalSource() { return source != null ? source : value; } @Override Object getValue(DataRecord[] sources) { return value; } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { // used temporary data field for checking constant DataField tmp = DataFieldFactory.createDataField(targetMetadata[recNo].getField(fieldNo), false); if (source != null) { try { tmp.fromString(source); value = tmp.getValue(); } catch (BadDataFormatException e) { errorMessage = e.getLocalizedMessage(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } else { try { tmp.setValue(value); source = tmp.toString(); } catch (BadDataFormatException e) { errorMessage = e.getLocalizedMessage(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } } } /** * Descendent of Rule class for storing parameter rule */ class ParameterRule extends Rule { ParameterRule(String source) { super(source); } @Override Rule duplicate() { ParameterRule duplicate = new ParameterRule(source); duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } @Override String getType() { return "PARAMETER_RULE"; } @Override Object getCanonicalSource() { return source; } @Override Object getValue(DataRecord[] sources) { return value; } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { // get parameter value String paramValue; if (source.startsWith("${")) {// get graph parameter paramValue = graph.getGraphProperties().getProperty(source.substring(2, source.lastIndexOf('}'))); } else if (source.startsWith(String.valueOf(CustomizedRecordTransform.PARAMETER_CHAR))) { // get parameter from node properties paramValue = parameters.getProperty((source)); } else { // try to find parameter with given name in node properties paramValue = parameters.getProperty(CustomizedRecordTransform.PARAMETER_CHAR + source); if (paramValue == null) { // try to find parameter with given name among graph parameters paramValue = graph.getGraphProperties().getProperty(source); } if (paramValue == null) { errorMessage = "Not found parameter: " + source; if (!(targetMetadata[recNo].getField(fieldNo).isNullable() || targetMetadata[recNo].getField(fieldNo) .isDefaultValue())) { logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } else { logger.warn(errorMessage); } } } // use temporary field to check if the value can be set to given data field DataField tmp = DataFieldFactory.createDataField(targetMetadata[recNo].getField(fieldNo), false); try { tmp.fromString(paramValue); value = tmp.getValue(); } catch (BadDataFormatException e) { errorMessage = e.getLocalizedMessage(); logger.error(errorMessage); throw new ComponentNotReadyException(errorMessage); } } } /** * Degenerated descendent of Rule class for marking fields for deleting previous rule */ class DeleteRule extends Rule { DeleteRule() { super(null); } @Override Rule duplicate() { DeleteRule duplicate = new DeleteRule(); duplicate.setGraph(graph); duplicate.setLogger(logger); duplicate.setProperties(parameters); return duplicate; } @Override String getType() { return "DELETE_RULE"; } @Override Object getCanonicalSource() { return null; } @Override Object getValue(DataRecord[] sources) { return null; } @Override void init(DataRecordMetadata[] sourceMetadata, DataRecordMetadata[] targetMetadata, int recNo, int fieldNo, PolicyType policy) throws ComponentNotReadyException { // do nothing } }
FIX:fix of last commit git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@4501 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/src/org/jetel/component/CustomizedRecordTransform.java
FIX:fix of last commit
<ide><path>loveretl.engine/src/org/jetel/component/CustomizedRecordTransform.java <ide> import org.jetel.data.DataField; <ide> import org.jetel.data.DataFieldFactory; <ide> import org.jetel.data.DataRecord; <del>import org.jetel.data.Defaults; <ide> import org.jetel.data.primitive.Numeric; <ide> import org.jetel.data.sequence.Sequence; <ide> import org.jetel.exception.BadDataFormatException; <ide> } <ide> } else if (!useAlternativeRules <ide> || !setAlternativeValue(sources, target, order[i][REC_NO], order[i][FIELD_NO], 0, e)) {// value <del> // is <del> // null <del> // or <del> // value <del> // can't <del> // be <del> // set <del> // to <del> // field <add> // is <add> // null <add> // or <add> // value <add> // can't <add> // be <add> // set <add> // to <add> // field <ide> throwException(transformMapArray, order[i][REC_NO], order[i][FIELD_NO], e); <ide> } <ide> } <ide> String[] parts = pattern.split("\\."); <ide> switch (parts.length) { <ide> case 2: <del> if (parts[0].startsWith(Defaults.CLOVER_FIELD_INDICATOR)) {// ${recNo.field} <add> if (parts[0].startsWith("$")) {// ${recNo.field} <ide> return parts[0].substring(2) + DOT + parts[1].substring(0, parts[1].length() - 1); <ide> } else {// recNo.field <ide> return pattern; <ide> } <ide> case 3: <del> if (parts[0].startsWith(Defaults.CLOVER_FIELD_INDICATOR)) {// ${in/out.recNo.field} <add> if (parts[0].startsWith("$")) {// ${in/out.recNo.field} <ide> return parts[1] + DOT + parts[2].substring(0, parts[2].length() - 1); <ide> } else {// in/out.recNo.field <ide> return parts[1] + DOT + parts[2];
Java
apache-2.0
497dec53206be31f54294758c388b576fc331309
0
angelindayana/scsb-etl,chenchulakshmig/scsb-etl,premkumarbalu/scsb-etl,premkumarbalu/scsb-etl,chenchulakshmig/scsb-etl,angelindayana/scsb-etl,chenchulakshmig/scsb-etl,angelindayana/scsb-etl,premkumarbalu/scsb-etl
package org.recap.service.executor.datadump; import org.apache.camel.ProducerTemplate; import org.recap.ReCAPConstants; import org.recap.model.export.DataDumpRequest; import org.recap.model.jpa.BibliographicEntity; import org.recap.model.jpa.ReportDataEntity; import org.recap.model.jpa.ReportEntity; import org.recap.repository.BibliographicDetailsRepository; import org.recap.service.email.datadump.DataDumpEmailService; import org.recap.service.formatter.datadump.DataDumpFormatterService; import org.recap.service.transmission.datadump.DataDumpTransmissionService; import org.recap.util.datadump.DataDumpFailureReportUtil; import org.recap.util.datadump.DataDumpSuccessReportUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.util.StopWatch; import java.util.*; import java.util.concurrent.*; /** * Created by premkb on 27/9/16. */ public abstract class AbstractDataDumpExecutorService implements DataDumpExecutorInterface{ private static final Logger logger = LoggerFactory.getLogger(AbstractDataDumpExecutorService.class); private ExecutorService executorService; @Autowired private BibliographicDetailsRepository bibliographicDetailsRepository; @Autowired private ProducerTemplate producer; @Autowired private DataDumpFormatterService dataDumpFormatterService; @Autowired private DataDumpTransmissionService dataDumpTransmissionService; @Autowired private DataDumpSuccessReportUtil dataDumpSuccessReportUtil; @Autowired private DataDumpFailureReportUtil dataDumpFailureReportUtil; @Autowired private DataDumpEmailService dataDumpEmailService; @Value("${datadump.httpresponse.record.limit}") private String httpResonseRecordLimit; @Override public String process(DataDumpRequest dataDumpRequest) throws ExecutionException, InterruptedException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); setExecutorService(dataDumpRequest.getNoOfThreads()); int batchSize = dataDumpRequest.getBatchSize(); Long totalRecordCount = getTotalRecordsCount(dataDumpRequest); setRecordsAvailability(totalRecordCount,dataDumpRequest); int loopCount = getLoopCount(totalRecordCount,batchSize); String outputString = null; List<Map<String,Object>> successAndFailureFormattedFullList = new ArrayList<>(); List<Callable<List<BibliographicEntity>>> callables = new ArrayList<>(); boolean canProcess = canProcessRecords(totalRecordCount,dataDumpRequest.getTransmissionType()); if(logger.isInfoEnabled()) { logger.info("Total no. of records " + totalRecordCount); } if (canProcess) { for(int pageNum = 0;pageNum < loopCount;pageNum++){ Callable callable = getCallable(pageNum,batchSize,dataDumpRequest,bibliographicDetailsRepository); callables.add(callable); } List<Future<List<BibliographicEntity>>> futureList = getExecutorService().invokeAll(callables); futureList.stream() .map(future -> { try { return future.get(); } catch (InterruptedException | ExecutionException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } }); int count=0; for(Future future:futureList){ StopWatch stopWatchPerFile = new StopWatch(); stopWatchPerFile.start(); List<BibliographicEntity> bibliographicEntityList = (List<BibliographicEntity>)future.get(); Object formattedObject = dataDumpFormatterService.getFormattedObject(bibliographicEntityList,dataDumpRequest.getOutputFormat()); Map<String,Object> successAndFailureFormattedList = (Map<String,Object>) formattedObject; outputString = (String) successAndFailureFormattedList.get(ReCAPConstants.DATADUMP_FORMATTEDSTRING); dataDumpTransmissionService.starTranmission(outputString,dataDumpRequest,getRouteMap(dataDumpRequest, count)); successAndFailureFormattedFullList.add(successAndFailureFormattedList); count++; stopWatchPerFile.stop(); if(logger.isInfoEnabled()){ logger.info("Total time taken to export file no. "+(count)+" is "+stopWatchPerFile.getTotalTimeMillis()/1000+" seconds"); logger.info("File no. "+(count)+" exported"); } } //processEmail(dataDumpRequest,totalRecordCount,dataDumpRequest.getDateTimeString()); }else{ outputString = ReCAPConstants.DATADUMP_HTTP_REPONSE_RECORD_LIMIT_ERR_MSG; } generateReport(successAndFailureFormattedFullList,dataDumpRequest); getExecutorService().shutdownNow(); stopWatch.stop(); if(logger.isInfoEnabled()){ logger.info("Total time taken to export all data - "+stopWatch.getTotalTimeMillis()/1000+" seconds ("+stopWatch.getTotalTimeMillis()/60000+" minutes)"); } return outputString; } private void processEmail(DataDumpRequest dataDumpRequest,Long totalRecordCount,String dateTimeStringForFolder){ if (dataDumpRequest.getTransmissionType().equals(ReCAPConstants.DATADUMP_TRANSMISSION_TYPE_FTP) || dataDumpRequest.getTransmissionType().equals(ReCAPConstants.DATADUMP_TRANSMISSION_TYPE_FILESYSTEM)) { dataDumpEmailService.sendEmail(dataDumpRequest.getInstitutionCodes(), totalRecordCount, dataDumpRequest.getRequestingInstitutionCode(), dataDumpRequest.getTransmissionType(),dateTimeStringForFolder); } } private void setRecordsAvailability(Long totalRecordCount,DataDumpRequest dataDumpRequest){ if(totalRecordCount > 0 ){ dataDumpRequest.setRecordsAvailable(true); }else{ dataDumpRequest.setRecordsAvailable(false); } } private boolean canProcessRecords(Long totalRecordCount, String transmissionType ){ boolean canProcess = true; if(totalRecordCount > Integer.parseInt(httpResonseRecordLimit) && transmissionType.equals(ReCAPConstants.DATADUMP_TRANSMISSION_TYPE_HTTP)){ canProcess = false; } return canProcess; } private void generateReport(List<Map<String,Object>> successAndFailureFormattedFullList ,DataDumpRequest dataDumpRequest){ List<BibliographicEntity> successList = new ArrayList<>(); List<BibliographicEntity> failureList = new ArrayList<>(); int errorCount = 0; for(Map<String,Object> successAndFailureFormattedList:successAndFailureFormattedFullList){ successList.addAll((List<BibliographicEntity>)successAndFailureFormattedList.get(ReCAPConstants.DATADUMP_SUCCESSLIST)); failureList.addAll((List<BibliographicEntity>)successAndFailureFormattedList.get(ReCAPConstants.DATADUMP_FAILURELIST)); if(successAndFailureFormattedList.get(ReCAPConstants.DATADUMP_FORMATERROR) != null){ errorCount++; } } if(successList.size()>0){ generateSuccessReport(successAndFailureFormattedFullList,dataDumpRequest); } if(failureList.size()>0 || errorCount > 0){ generateFailureReport(successAndFailureFormattedFullList,dataDumpRequest); } } private void generateSuccessReport(List<Map<String,Object>> successAndFailureFormattedFullList ,DataDumpRequest dataDumpRequest){ ReportEntity reportEntity = new ReportEntity(); List<ReportDataEntity> reportDataEntities = dataDumpSuccessReportUtil.generateDataDumpSuccessReport(successAndFailureFormattedFullList,dataDumpRequest); reportEntity.setReportDataEntities(reportDataEntities); reportEntity.setFileName(ReCAPConstants.OPERATION_TYPE_DATADUMP+"-"+dataDumpRequest.getDateTimeString()); reportEntity.setCreatedDate(new Date()); reportEntity.setType(ReCAPConstants.OPERATION_TYPE_DATADUMP_SUCCESS); reportEntity.setInstitutionName(dataDumpRequest.getRequestingInstitutionCode()); producer.sendBody(ReCAPConstants.REPORT_Q, reportEntity); } private void generateFailureReport(List<Map<String,Object>> successAndFailureFormattedFullList ,DataDumpRequest dataDumpRequest){ ReportEntity reportEntity = new ReportEntity(); List<ReportDataEntity> reportDataEntities = dataDumpFailureReportUtil.generateDataDumpFailureReport(successAndFailureFormattedFullList,dataDumpRequest); reportEntity.setReportDataEntities(reportDataEntities); reportEntity.setFileName(ReCAPConstants.OPERATION_TYPE_DATADUMP+"-"+dataDumpRequest.getDateTimeString()); reportEntity.setCreatedDate(new Date()); reportEntity.setType(ReCAPConstants.OPERATION_TYPE_DATADUMP_FAILURE); reportEntity.setInstitutionName(dataDumpRequest.getRequestingInstitutionCode()); producer.sendBody(ReCAPConstants.REPORT_Q, reportEntity); } private void setExecutorService(Integer numThreads) { if (null == executorService || executorService.isShutdown()) { executorService = Executors.newFixedThreadPool(numThreads); } } public ExecutorService getExecutorService() { return executorService; } public Map<String,String> getRouteMap(DataDumpRequest dataDumpRequest, int pageNum){ Map<String,String> routeMap = new HashMap<>(); String fileName = ReCAPConstants.DATA_DUMP_FILE_NAME+ dataDumpRequest.getRequestingInstitutionCode() + (pageNum+1); routeMap.put(ReCAPConstants.FILENAME,fileName); routeMap.put(ReCAPConstants.DATETIME_FOLDER, dataDumpRequest.getDateTimeString()); routeMap.put(ReCAPConstants.REQUESTING_INST_CODE,dataDumpRequest.getRequestingInstitutionCode()); routeMap.put(ReCAPConstants.FILE_FORMAT,dataDumpRequest.getFileFormat()); return routeMap; } public int getLoopCount(Long totalRecordCount,int batchSize){ int quotient = Integer.valueOf(Long.toString(totalRecordCount)) / (batchSize); int remainder = Integer.valueOf(Long.toString(totalRecordCount)) % (batchSize); int loopCount = remainder == 0 ? quotient : quotient + 1; return loopCount; } public abstract Long getTotalRecordsCount(DataDumpRequest dataDumpRequest); public abstract Callable getCallable(int pageNum, int batchSize, DataDumpRequest dataDumpRequest, BibliographicDetailsRepository bibliographicDetailsRepository); }
src/main/java/org/recap/service/executor/datadump/AbstractDataDumpExecutorService.java
package org.recap.service.executor.datadump; import org.apache.camel.ProducerTemplate; import org.recap.ReCAPConstants; import org.recap.model.export.DataDumpRequest; import org.recap.model.jpa.BibliographicEntity; import org.recap.model.jpa.ReportDataEntity; import org.recap.model.jpa.ReportEntity; import org.recap.repository.BibliographicDetailsRepository; import org.recap.service.email.datadump.DataDumpEmailService; import org.recap.service.formatter.datadump.DataDumpFormatterService; import org.recap.service.transmission.datadump.DataDumpTransmissionService; import org.recap.util.datadump.DataDumpFailureReportUtil; import org.recap.util.datadump.DataDumpSuccessReportUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.util.StopWatch; import java.util.*; import java.util.concurrent.*; /** * Created by premkb on 27/9/16. */ public abstract class AbstractDataDumpExecutorService implements DataDumpExecutorInterface{ private static final Logger logger = LoggerFactory.getLogger(AbstractDataDumpExecutorService.class); private ExecutorService executorService; @Autowired private BibliographicDetailsRepository bibliographicDetailsRepository; @Autowired private ProducerTemplate producer; @Autowired private DataDumpFormatterService dataDumpFormatterService; @Autowired private DataDumpTransmissionService dataDumpTransmissionService; @Autowired private DataDumpSuccessReportUtil dataDumpSuccessReportUtil; @Autowired private DataDumpFailureReportUtil dataDumpFailureReportUtil; @Autowired private DataDumpEmailService dataDumpEmailService; @Value("${datadump.httpresponse.record.limit}") private String httpResonseRecordLimit; @Override public String process(DataDumpRequest dataDumpRequest) throws ExecutionException, InterruptedException { StopWatch stopWatch = new StopWatch(); stopWatch.start(); setExecutorService(dataDumpRequest.getNoOfThreads()); int batchSize = dataDumpRequest.getBatchSize(); Long totalRecordCount = getTotalRecordsCount(dataDumpRequest); setRecordsAvailability(totalRecordCount,dataDumpRequest); int loopCount = getLoopCount(totalRecordCount,batchSize); String outputString = null; List<Map<String,Object>> successAndFailureFormattedFullList = new ArrayList<>(); List<Callable<List<BibliographicEntity>>> callables = new ArrayList<>(); boolean canProcess = canProcessRecords(totalRecordCount,dataDumpRequest.getTransmissionType()); if(logger.isInfoEnabled()) { logger.info("Total no. of records " + totalRecordCount); } if (canProcess) { for(int pageNum = 0;pageNum < loopCount;pageNum++){ Callable callable = getCallable(pageNum,batchSize,dataDumpRequest,bibliographicDetailsRepository); callables.add(callable); } List<Future<List<BibliographicEntity>>> futureList = getExecutorService().invokeAll(callables); futureList.stream() .map(future -> { try { return future.get(); } catch (InterruptedException | ExecutionException e) { logger.error(e.getMessage()); throw new RuntimeException(e); } }); int count=0; for(Future future:futureList){ StopWatch stopWatchPerFile = new StopWatch(); stopWatchPerFile.start(); List<BibliographicEntity> bibliographicEntityList = (List<BibliographicEntity>)future.get(); Object formattedObject = dataDumpFormatterService.getFormattedObject(bibliographicEntityList,dataDumpRequest.getOutputFormat()); Map<String,Object> successAndFailureFormattedList = (Map<String,Object>) formattedObject; outputString = (String) successAndFailureFormattedList.get(ReCAPConstants.DATADUMP_FORMATTEDSTRING); dataDumpTransmissionService.starTranmission(outputString,dataDumpRequest,getRouteMap(dataDumpRequest, count)); successAndFailureFormattedFullList.add(successAndFailureFormattedList); count++; stopWatchPerFile.stop(); if(logger.isInfoEnabled()){ logger.info("Total time taken to export file no. "+(count)+" is "+stopWatchPerFile.getTotalTimeMillis()/1000+" seconds"); logger.info("File no. "+(count)+" exported"); } } processEmail(dataDumpRequest,totalRecordCount,dataDumpRequest.getDateTimeString()); }else{ outputString = ReCAPConstants.DATADUMP_HTTP_REPONSE_RECORD_LIMIT_ERR_MSG; } generateReport(successAndFailureFormattedFullList,dataDumpRequest); getExecutorService().shutdownNow(); stopWatch.stop(); if(logger.isInfoEnabled()){ logger.info("Total time taken to export all data - "+stopWatch.getTotalTimeMillis()/1000+" seconds ("+stopWatch.getTotalTimeMillis()/60000+" minutes)"); } return outputString; } private void processEmail(DataDumpRequest dataDumpRequest,Long totalRecordCount,String dateTimeStringForFolder){ if (dataDumpRequest.getTransmissionType().equals(ReCAPConstants.DATADUMP_TRANSMISSION_TYPE_FTP) || dataDumpRequest.getTransmissionType().equals(ReCAPConstants.DATADUMP_TRANSMISSION_TYPE_FILESYSTEM)) { dataDumpEmailService.sendEmail(dataDumpRequest.getInstitutionCodes(), totalRecordCount, dataDumpRequest.getRequestingInstitutionCode(), dataDumpRequest.getTransmissionType(),dateTimeStringForFolder); } } private void setRecordsAvailability(Long totalRecordCount,DataDumpRequest dataDumpRequest){ if(totalRecordCount > 0 ){ dataDumpRequest.setRecordsAvailable(true); }else{ dataDumpRequest.setRecordsAvailable(false); } } private boolean canProcessRecords(Long totalRecordCount, String transmissionType ){ boolean canProcess = true; if(totalRecordCount > Integer.parseInt(httpResonseRecordLimit) && transmissionType.equals(ReCAPConstants.DATADUMP_TRANSMISSION_TYPE_HTTP)){ canProcess = false; } return canProcess; } private void generateReport(List<Map<String,Object>> successAndFailureFormattedFullList ,DataDumpRequest dataDumpRequest){ List<BibliographicEntity> successList = new ArrayList<>(); List<BibliographicEntity> failureList = new ArrayList<>(); int errorCount = 0; for(Map<String,Object> successAndFailureFormattedList:successAndFailureFormattedFullList){ successList.addAll((List<BibliographicEntity>)successAndFailureFormattedList.get(ReCAPConstants.DATADUMP_SUCCESSLIST)); failureList.addAll((List<BibliographicEntity>)successAndFailureFormattedList.get(ReCAPConstants.DATADUMP_FAILURELIST)); if(successAndFailureFormattedList.get(ReCAPConstants.DATADUMP_FORMATERROR) != null){ errorCount++; } } if(successList.size()>0){ generateSuccessReport(successAndFailureFormattedFullList,dataDumpRequest); } if(failureList.size()>0 || errorCount > 0){ generateFailureReport(successAndFailureFormattedFullList,dataDumpRequest); } } private void generateSuccessReport(List<Map<String,Object>> successAndFailureFormattedFullList ,DataDumpRequest dataDumpRequest){ ReportEntity reportEntity = new ReportEntity(); List<ReportDataEntity> reportDataEntities = dataDumpSuccessReportUtil.generateDataDumpSuccessReport(successAndFailureFormattedFullList,dataDumpRequest); reportEntity.setReportDataEntities(reportDataEntities); reportEntity.setFileName(ReCAPConstants.OPERATION_TYPE_DATADUMP+"-"+dataDumpRequest.getDateTimeString()); reportEntity.setCreatedDate(new Date()); reportEntity.setType(ReCAPConstants.OPERATION_TYPE_DATADUMP_SUCCESS); reportEntity.setInstitutionName(dataDumpRequest.getRequestingInstitutionCode()); producer.sendBody(ReCAPConstants.REPORT_Q, reportEntity); } private void generateFailureReport(List<Map<String,Object>> successAndFailureFormattedFullList ,DataDumpRequest dataDumpRequest){ ReportEntity reportEntity = new ReportEntity(); List<ReportDataEntity> reportDataEntities = dataDumpFailureReportUtil.generateDataDumpFailureReport(successAndFailureFormattedFullList,dataDumpRequest); reportEntity.setReportDataEntities(reportDataEntities); reportEntity.setFileName(ReCAPConstants.OPERATION_TYPE_DATADUMP+"-"+dataDumpRequest.getDateTimeString()); reportEntity.setCreatedDate(new Date()); reportEntity.setType(ReCAPConstants.OPERATION_TYPE_DATADUMP_FAILURE); reportEntity.setInstitutionName(dataDumpRequest.getRequestingInstitutionCode()); producer.sendBody(ReCAPConstants.REPORT_Q, reportEntity); } private void setExecutorService(Integer numThreads) { if (null == executorService || executorService.isShutdown()) { executorService = Executors.newFixedThreadPool(numThreads); } } public ExecutorService getExecutorService() { return executorService; } public Map<String,String> getRouteMap(DataDumpRequest dataDumpRequest, int pageNum){ Map<String,String> routeMap = new HashMap<>(); String fileName = ReCAPConstants.DATA_DUMP_FILE_NAME+ dataDumpRequest.getRequestingInstitutionCode() + (pageNum+1); routeMap.put(ReCAPConstants.FILENAME,fileName); routeMap.put(ReCAPConstants.DATETIME_FOLDER, dataDumpRequest.getDateTimeString()); routeMap.put(ReCAPConstants.REQUESTING_INST_CODE,dataDumpRequest.getRequestingInstitutionCode()); routeMap.put(ReCAPConstants.FILE_FORMAT,dataDumpRequest.getFileFormat()); return routeMap; } public int getLoopCount(Long totalRecordCount,int batchSize){ int quotient = Integer.valueOf(Long.toString(totalRecordCount)) / (batchSize); int remainder = Integer.valueOf(Long.toString(totalRecordCount)) % (batchSize); int loopCount = remainder == 0 ? quotient : quotient + 1; return loopCount; } public abstract Long getTotalRecordsCount(DataDumpRequest dataDumpRequest); public abstract Callable getCallable(int pageNum, int batchSize, DataDumpRequest dataDumpRequest, BibliographicDetailsRepository bibliographicDetailsRepository); }
DataDump full refactor
src/main/java/org/recap/service/executor/datadump/AbstractDataDumpExecutorService.java
DataDump full refactor
<ide><path>rc/main/java/org/recap/service/executor/datadump/AbstractDataDumpExecutorService.java <ide> logger.info("File no. "+(count)+" exported"); <ide> } <ide> } <del> processEmail(dataDumpRequest,totalRecordCount,dataDumpRequest.getDateTimeString()); <add> //processEmail(dataDumpRequest,totalRecordCount,dataDumpRequest.getDateTimeString()); <ide> <ide> }else{ <ide> outputString = ReCAPConstants.DATADUMP_HTTP_REPONSE_RECORD_LIMIT_ERR_MSG;
Java
apache-2.0
992240d58c52df5a70520da1aa084549de8d998a
0
web-slinger/cordova-plugin-statusbar,web-slinger/cordova-plugin-statusbar,web-slinger/cordova-plugin-statusbar
/* * 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.cordova.statusbar; import android.app.ActivityManager; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.util.Log; import android.view.Window; import android.view.View; import android.view.WindowManager; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONException; public class StatusBar extends CordovaPlugin { private static final String TAG = "StatusBar"; /** * Sets the context of the Command. This can then be used to do things like * get file paths associated with the Activity. * * @param cordova The context of the main Activity. * @param webView The CordovaWebView Cordova is running in. */ @Override public void initialize(final CordovaInterface cordova, CordovaWebView webView) { Log.v(TAG, "StatusBar: initialization"); super.initialize(cordova, webView); this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { // Clear flag FLAG_FORCE_NOT_FULLSCREEN which is set initially // by the Cordova. Window window = cordova.getActivity().getWindow(); window.clearFlags(0x00000800); // WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN // Read 'StatusBarBackgroundColor' from config.xml, default is #000000. // Read 'MultiTaskHeaderColor' from config.xml, default is #999999. // Read 'NavBarColor' from config.xml, default is #000000. if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setNavBarColor(preferences.getString("NavBarColor", "#000000")); setMultitaskHeaderColor(preferences.getString("MultiTaskHeaderColor", "#999999")); setStatusBarBackgroundColor(preferences.getString("StatusBarBackgroundColor", "#000000")); } } }); } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false otherwise. */ @Override public boolean execute(final String action, final CordovaArgs args, final CallbackContext callbackContext) throws JSONException { Log.v(TAG, "Executing action: " + action); final Activity activity = this.cordova.getActivity(); final Window window = activity.getWindow(); if ("_ready".equals(action)) { boolean statusBarVisible = (window.getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, statusBarVisible)); return true; } if ("show".equals(action)) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } }); return true; } if ("hide".equals(action)) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } }); return true; } if ("backgroundColorByHexString".equals(action)) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { setStatusBarBackgroundColor(args.getString(0)); } catch (JSONException ignore) { Log.e(TAG, "Invalid hexString argument, use f.i. '#777777'"); } } }); return true; } return false; } private void setNavBarColor(final String colorPref) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (colorPref != null && !colorPref.isEmpty()) { colorPref = "#000000"; } Window window = cordova.getActivity().getWindow(); window.addFlags(0x80000000); // WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS window.clearFlags(0x08000000); // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION window.setNavigationBarColor(Color.parse(colorPref)); } } private void setMultitaskHeaderColor(final String colorPref) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (colorPref != null && !colorPref.isEmpty()) { colorPref = "#EEEEEE"; } ActivityManager activityManager = (ActivityManager) cordova.getActivity().getSystemService(Context.ACTIVITY_SERVICE); for(ActivityManager.AppTask appTask : activityManager.getAppTasks()) { if(appTask.getTaskInfo().id == cordova.getActivity().getTaskId()) { ActivityManager.TaskDescription description = appTask.getTaskInfo().taskDescription; cordova.getActivity().setTaskDescription(new ActivityManager.TaskDescription(description.getLabel(), description.getIcon(), Color.parse(colorPref))); } } } } private void setStatusBarBackgroundColor(final String colorPref) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (colorPref == null && colorPref.isEmpty()) { colorPref = "#000000"; } final Window window = cordova.getActivity().getWindow(); // Method and constants not available on all SDKs but we want to be able to compile this code with any SDK window.clearFlags(0x04000000); // SDK 19: WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(0x80000000); // SDK 21: WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.parseColor(colorPref)) // try { // // Using reflection makes sure any 5.0+ device will work without having to compile with SDK level 21 // window.getClass().getDeclaredMethod("setStatusBarColor", int.class).invoke(window, Color.parseColor(colorPref)); // } catch (IllegalArgumentException ignore) { // Log.e(TAG, "Invalid hexString argument, use f.i. '#999999'"); // } catch (Exception ignore) { // // this should not happen, only in case Android removes this method in a version > 21 // Log.w(TAG, "Method window.setStatusBarColor not found for SDK level " + Build.VERSION.SDK_INT); // } } } }
src/android/StatusBar.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.cordova.statusbar; import android.app.ActivityManager; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.util.Log; import android.view.Window; import android.view.View; import android.view.WindowManager; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaArgs; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONException; public class StatusBar extends CordovaPlugin { private static final String TAG = "StatusBar"; /** * Sets the context of the Command. This can then be used to do things like * get file paths associated with the Activity. * * @param cordova The context of the main Activity. * @param webView The CordovaWebView Cordova is running in. */ @Override public void initialize(final CordovaInterface cordova, CordovaWebView webView) { Log.v(TAG, "StatusBar: initialization"); super.initialize(cordova, webView); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { int color = Color.parseColor(preferences.getString("StatusBarColor", "#000000")); int headercolor = Color.parseColor(preferences.getString("MultiTaskHeaderColor", "#999999")); int navcolor = Color.parseColor(preferences.getString("NavBarColor", "#000000")); // THIS ADDS THE headercolor int to the Multi-task Header Bar 'ActivityManager.TaskDescription' ActivityManager activityManager = (ActivityManager) cordova.getActivity().getSystemService(Context.ACTIVITY_SERVICE); for(ActivityManager.AppTask appTask : activityManager.getAppTasks()) { if(appTask.getTaskInfo().id == cordova.getActivity().getTaskId()) { ActivityManager.TaskDescription description = appTask.getTaskInfo().taskDescription; cordova.getActivity().setTaskDescription(new ActivityManager.TaskDescription(description.getLabel(), description.getIcon(), headercolor)); } } Window window = cordova.getActivity().getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); window.setStatusBarColor(color); window.setNavigationBarColor(navcolor); } else { Window window = cordova.getActivity().getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); setStatusBarBackgroundColor(preferences.getString("StatusBarColor", "#000000")); } } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false otherwise. */ @Override public boolean execute(final String action, final CordovaArgs args, final CallbackContext callbackContext) throws JSONException { Log.v(TAG, "Executing action: " + action); final Activity activity = this.cordova.getActivity(); final Window window = activity.getWindow(); if ("_ready".equals(action)) { boolean statusBarVisible = (window.getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0; callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, statusBarVisible)); return true; } if ("show".equals(action)) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } }); return true; } if ("hide".equals(action)) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } }); return true; } if ("backgroundColorByHexString".equals(action)) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { setStatusBarBackgroundColor(args.getString(0)); } catch (JSONException ignore) { Log.e(TAG, "Invalid hexString argument, use f.i. '#777777'"); } } }); return true; } return false; } private void setStatusBarBackgroundColor(final String colorPref) { if (Build.VERSION.SDK_INT >= 21) { if (colorPref != null && !colorPref.isEmpty()) { final Window window = cordova.getActivity().getWindow(); // Method and constants not available on all SDKs but we want to be able to compile this code with any SDK window.clearFlags(0x04000000); // SDK 19: WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(0x80000000); // SDK 21: WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); try { // Using reflection makes sure any 5.0+ device will work without having to compile with SDK level 21 window.getClass().getDeclaredMethod("setStatusBarColor", int.class).invoke(window, Color.parseColor(colorPref)); } catch (IllegalArgumentException ignore) { Log.e(TAG, "Invalid hexString argument, use f.i. '#999999'"); } catch (Exception ignore) { // this should not happen, only in case Android removes this method in a version > 21 Log.w(TAG, "Method window.setStatusBarColor not found for SDK level " + Build.VERSION.SDK_INT); } } } } }
Update StatusBar.java
src/android/StatusBar.java
Update StatusBar.java
<ide><path>rc/android/StatusBar.java <ide> public void initialize(final CordovaInterface cordova, CordovaWebView webView) { <ide> Log.v(TAG, "StatusBar: initialization"); <ide> super.initialize(cordova, webView); <del> <del> if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { <del> int color = Color.parseColor(preferences.getString("StatusBarColor", "#000000")); <del> int headercolor = Color.parseColor(preferences.getString("MultiTaskHeaderColor", "#999999")); <del> int navcolor = Color.parseColor(preferences.getString("NavBarColor", "#000000")); <del> // THIS ADDS THE headercolor int to the Multi-task Header Bar 'ActivityManager.TaskDescription' <del> ActivityManager activityManager = (ActivityManager) cordova.getActivity().getSystemService(Context.ACTIVITY_SERVICE); <del> for(ActivityManager.AppTask appTask : activityManager.getAppTasks()) { <del> if(appTask.getTaskInfo().id == cordova.getActivity().getTaskId()) { <del> ActivityManager.TaskDescription description = appTask.getTaskInfo().taskDescription; <del> cordova.getActivity().setTaskDescription(new ActivityManager.TaskDescription(description.getLabel(), description.getIcon(), headercolor)); <del> } <add> <add> this.cordova.getActivity().runOnUiThread(new Runnable() { <add> @Override <add> public void run() { <add> // Clear flag FLAG_FORCE_NOT_FULLSCREEN which is set initially <add> // by the Cordova. <add> Window window = cordova.getActivity().getWindow(); <add> window.clearFlags(0x00000800); // WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN <add> <add> // Read 'StatusBarBackgroundColor' from config.xml, default is #000000. <add> // Read 'MultiTaskHeaderColor' from config.xml, default is #999999. <add> // Read 'NavBarColor' from config.xml, default is #000000. <add> <add> if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { <add> setNavBarColor(preferences.getString("NavBarColor", "#000000")); <add> setMultitaskHeaderColor(preferences.getString("MultiTaskHeaderColor", "#999999")); <add> setStatusBarBackgroundColor(preferences.getString("StatusBarBackgroundColor", "#000000")); <add> } <ide> } <del> Window window = cordova.getActivity().getWindow(); <del> window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); <del> window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); <del> window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); <del> window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); <del> window.setStatusBarColor(color); <del> window.setNavigationBarColor(navcolor); <del> } else { <del> Window window = cordova.getActivity().getWindow(); <del> window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); <del> setStatusBarBackgroundColor(preferences.getString("StatusBarColor", "#000000")); <del> } <add> }); <ide> } <ide> <ide> /** <ide> return false; <ide> } <ide> <del> private void setStatusBarBackgroundColor(final String colorPref) { <del> if (Build.VERSION.SDK_INT >= 21) { <add> private void setNavBarColor(final String colorPref) { <add> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { <ide> if (colorPref != null && !colorPref.isEmpty()) { <del> final Window window = cordova.getActivity().getWindow(); <del> // Method and constants not available on all SDKs but we want to be able to compile this code with any SDK <del> window.clearFlags(0x04000000); // SDK 19: WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); <del> window.addFlags(0x80000000); // SDK 21: WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); <del> try { <del> // Using reflection makes sure any 5.0+ device will work without having to compile with SDK level 21 <del> window.getClass().getDeclaredMethod("setStatusBarColor", int.class).invoke(window, Color.parseColor(colorPref)); <del> } catch (IllegalArgumentException ignore) { <del> Log.e(TAG, "Invalid hexString argument, use f.i. '#999999'"); <del> } catch (Exception ignore) { <del> // this should not happen, only in case Android removes this method in a version > 21 <del> Log.w(TAG, "Method window.setStatusBarColor not found for SDK level " + Build.VERSION.SDK_INT); <add> colorPref = "#000000"; <add> } <add> <add> Window window = cordova.getActivity().getWindow(); <add> <add> window.addFlags(0x80000000); // WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS <add> window.clearFlags(0x08000000); // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION <add> window.setNavigationBarColor(Color.parse(colorPref)); <add> } <add> } <add> private void setMultitaskHeaderColor(final String colorPref) { <add> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { <add> if (colorPref != null && !colorPref.isEmpty()) { <add> colorPref = "#EEEEEE"; <add> } <add> <add> ActivityManager activityManager = (ActivityManager) cordova.getActivity().getSystemService(Context.ACTIVITY_SERVICE); <add> for(ActivityManager.AppTask appTask : activityManager.getAppTasks()) { <add> if(appTask.getTaskInfo().id == cordova.getActivity().getTaskId()) { <add> ActivityManager.TaskDescription description = appTask.getTaskInfo().taskDescription; <add> cordova.getActivity().setTaskDescription(new ActivityManager.TaskDescription(description.getLabel(), description.getIcon(), Color.parse(colorPref))); <ide> } <ide> } <ide> } <ide> } <add> <add> private void setStatusBarBackgroundColor(final String colorPref) { <add> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { <add> if (colorPref == null && colorPref.isEmpty()) { <add> colorPref = "#000000"; <add> } <add> final Window window = cordova.getActivity().getWindow(); <add> // Method and constants not available on all SDKs but we want to be able to compile this code with any SDK <add> window.clearFlags(0x04000000); // SDK 19: WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); <add> window.addFlags(0x80000000); // SDK 21: WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); <add> window.setStatusBarColor(Color.parseColor(colorPref)) <add> <add> // try { <add> // // Using reflection makes sure any 5.0+ device will work without having to compile with SDK level 21 <add> // window.getClass().getDeclaredMethod("setStatusBarColor", int.class).invoke(window, Color.parseColor(colorPref)); <add> // } catch (IllegalArgumentException ignore) { <add> // Log.e(TAG, "Invalid hexString argument, use f.i. '#999999'"); <add> // } catch (Exception ignore) { <add> // // this should not happen, only in case Android removes this method in a version > 21 <add> // Log.w(TAG, "Method window.setStatusBarColor not found for SDK level " + Build.VERSION.SDK_INT); <add> // } <add> <add> } <add> } <ide> }
Java
mit
5c308c7287184a56fda2ebc0887c7e6f93f2840a
0
clee231/restaurant-inventory-management
/** * Restaurant Inventory Management * Group 7 */ package edu.uic.cs342.group7.rim; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; //Java 8 routines //import java.io.IOException; //import java.nio.charset.StandardCharsets; //import java.nio.file.Files; //import java.nio.file.Paths; import java.util.Scanner; /** * @authors * Adrian Pasciak, * Chase Lee, * Christopher Schultz, * Nerijus Gelezinis (no-show), * Patrick Tam * */ public class Client { static ArrayList<Ingredient> ingreds = new ArrayList<Ingredient>(); static ArrayList<Dish> dishes = new ArrayList<Dish>(); static Api connection = new Api(); static HashMap<String, String> dishSizes = new HashMap<String, String>(); /** * Constructor Stub */ public Client() { // TODO Auto-generated constructor stub // TODO We should create an instance of the RIM API in this class. } /** * This function will print out the menu for the user to select from. * There are no arguments for this function. */ private static void printMenu() { printHeader("Menu"); System.out.println("1. Order Dish"); System.out.println("2. Add Items to Inventory"); System.out.println("3. End Day"); System.out.println("4. Forecast Shopping List"); System.out.println("5. Load data from file"); System.out.println("q. Quit"); } /** * This function wll print out a header for a given text string. * @param text - A string to place within the header flag. */ public static void printHeader(String text) { int count = text.length(); String dash = "-"; for (int i = 0; i < count-1; i++) { dash = dash.concat("-"); } System.out.println("+" + dash + "+"); System.out.println("+" + text + "+"); System.out.println("+" + dash + "+"); } /** * This will determine if a ingredient is in the larger list of ingredients, identified by name. * @param haystack - The list of all ingredients * @param needle - The string you are looking for, identifying the ingredient * @return - true if the ingredient is found, false if not. */ public static boolean ingredientExists(ArrayList<Ingredient> haystack, String needle) { for (Ingredient item : haystack) { if (item.getName().equalsIgnoreCase(needle)) { return true; } } return false; } /** * This will return the Ingredient object that is in the larger list of ingredients, identified by name. * @param haystack - The list of all ingredients. * @param needle - The string you are looking for, identifying the ingredient. * @return - Returns the Ingredient instance that was found in the haystack. */ public static Ingredient getIngredient(ArrayList<Ingredient> haystack, String needle) { for (Ingredient item : haystack) { if (item.getName().equalsIgnoreCase(needle)) { return item; } } return null; } /** * Determines if a string is a number * @param str - A string to be determined to be a number or not. * @return - True if the string is parsable into a number. False if not a string parsable into a number. */ public static boolean isNumeric(String str) { return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. } /** * Loads a dishes file to be added into the running database. * @param file - the filename / filepath from the current working directory. (one directory above the src folder) */ private static void loadDishesFile(String file) { // This is Java 8... 5 lines to read the file... // try { // Files.lines(Paths.get(input), StandardCharsets.UTF_8).forEach(System.out::println); // } catch (IOException e) { // e.printStackTrace(); // } BufferedReader br = null; String line = null; try { br = new BufferedReader(new FileReader(file)); while ((line = br.readLine()) != null) { if (line.startsWith("#")) { continue; // Comment detection } String[] elements = line.split(","); ArrayList<DishIngredient> dishRecipe = new ArrayList<DishIngredient>(); /** * For each line: * - Add an Ingredient if not exists in array * - Make a dishIngredient and append to list * - Create a Dish * - Add dish to dishArray */ for (int i = 1; i < elements.length; i++) { String[] elemquant = elements[i].split(":"); Ingredient currentIngredient = new Ingredient(elemquant[0]); if(!ingredientExists(ingreds, elemquant[0])) { ingreds.add(currentIngredient); System.out.println("Added " + currentIngredient.getName()); }else { System.out.println("Skipping ingredient."); } DishIngredient currentDishIngredient = new DishIngredient(getIngredient(ingreds, elemquant[0]), Integer.parseInt(elemquant[1])); dishRecipe.add(currentDishIngredient); } Dish currentDish = new Dish(dishRecipe, elements[0]); dishes.add(currentDish); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } connection.loadIngredients(ingreds); connection.loadDishes(dishes); } /** * Loads a inventory file to be added into the running database. * @param file - the filename / filepath from the current working directory. (one directory above the src folder) */ private static void loadInventoryFile(String file) { BufferedReader br2 = null; String line2 = null; ArrayList<Ingredient> toBeAdded2 = new ArrayList<Ingredient>(); try { br2 = new BufferedReader(new FileReader(file)); while ((line2 = br2.readLine()) != null) { if (line2.startsWith("#")) { continue; // Comment detection } String[] elements = line2.split(","); String ingredientName = elements[0]; int curQuantity = Integer.parseInt(elements[1]); String[] parseDate = elements[2].split("/"); GregorianCalendar date2 = new GregorianCalendar(Integer.parseInt(parseDate[0]),Integer.parseInt(parseDate[1]),Integer.parseInt(parseDate[2])); if (ingredientExists(ingreds,ingredientName)) { Ingredient ingredientToAdd2 = new Ingredient(ingredientName); Quantity newQuantity2 = new Quantity(); newQuantity2.setCount(curQuantity); newQuantity2.setDate(date2.getTime()); ingredientToAdd2.addQuantity(newQuantity2); toBeAdded2.add(ingredientToAdd2); System.out.println("Added: " + newQuantity2.getCount() + " " + ingredientName + "(s) set to expire on " + newQuantity2.getDate().toString()); } } System.out.println("Committed " + toBeAdded2.size() + " distinct items"); connection.addItemsToInventory(toBeAdded2); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br2 != null) { try { br2.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Calls the API and determines what we need to buy. * @param api - the connection/instance of the api. */ public static void forecastApi(Api api) { ArrayList<Ingredient> list = api.getShoppingList(); api.addItemsToInventory(list); Iterator<Ingredient> itr = list.iterator(); Ingredient ingredient; System.out.println("******** Shopping List **********"); while(itr.hasNext()) { ingredient = itr.next(); System.out.println("Ingredient: " + ingredient.getName() + " Quantity: " + ingredient.getTotalQuantityOfIngredient()); } System.out.println("\n"); } /** * This function is the main driver and client for the our project. This * main function will handle all the interface logic with the user. * @param args - This parameter is not used. */ public static void main(String[] args) { String version = "1.00"; System.out.println("+------------------------------------------------------------------------------+"); System.out.format("+ Restaurant Inventory Management v%s +\n", version); System.out.println("+ Authors: Adrian Pasciak, Chase Lee, Christopher Schultz, +"); System.out.println("+ Nerijus Gelezinis (no-show), Patrick Tam +"); System.out.println("+------------------------------------------------------------------------------+"); dishSizes.put("F", "Full order"); dishSizes.put("S", "Super size order"); dishSizes.put("H", "Half order"); System.out.println("Current Status: NOT IMPLEMENTED"); printMenu(); System.out.println("\nSelect a menu option: "); boolean runflag = true; int count = 0; Scanner s = new Scanner(System.in); String input = s.nextLine(); while (!("q".equalsIgnoreCase(input))) { while (!isNumeric(input)) { input = s.nextLine(); // Grab any stay lines. } switch(Integer.parseInt(input)) { case 1: printHeader("Order Dish"); System.out.println("Please select the dish you would like to order:"); count = 0; for(Dish item : dishes) { System.out.println(count +") "+ item.getName()); count++; } input = null; input = s.nextLine(); while (Integer.parseInt(input) > dishes.size()) { System.out.println("Invalid option. Try again:"); input = s.nextLine(); } int getDish = Integer.parseInt(input); System.out.println("Please select a dish size:"); System.out.println("S) Super Size Order"); System.out.println("F) Full Size Order (Normal)"); System.out.println("H) Half Size Order"); input = null; input = s.nextLine(); while (input.length() <= 0) { input = s.nextLine(); } String dSize = input; boolean result = connection.orderDish(dishes.get(getDish).getName(), dishSizes.get(dSize.substring(0, 1).toUpperCase())); if (result) { System.out.println(dishSizes.get(dSize.substring(0, 1).toUpperCase()) + " of " + dishes.get(getDish).getName() + " ordered successfully."); }else { System.out.println(dishSizes.get(dSize.substring(0, 1).toUpperCase()) + " of " + dishes.get(getDish).getName() + " order failed."); } break; case 2: printHeader("Add Items to Inventory Quantity"); count = 0; for(Ingredient item : ingreds) { System.out.println(count + ") " + item.getName() + " - " + item.getTotalQuantityOfIngredient()); count++; } System.out.println("Please select the ingredient you would like to add quantity to:"); int ingredientToAdd = s.nextInt(); while(ingredientToAdd > ingreds.size() || ingredientToAdd < 0) { System.out.println("Invalid option, try again:"); ingredientToAdd = s.nextInt(); } System.out.println("How many would you like to add?:"); int quantityToAdd = s.nextInt(); while(quantityToAdd < 0) { System.out.println("Invalid quantity, try again:"); quantityToAdd = s.nextInt(); } input = s.nextLine(); // Eat up new line. System.out.println("When is the expiration?: yy/mm/dd"); input = s.nextLine(); String[] ymd = input.split("/"); ArrayList<Ingredient> toBeAdded = new ArrayList<Ingredient>(); Ingredient ingredientStaged = new Ingredient(ingreds.get(ingredientToAdd).getName()); Quantity newQuantity = new Quantity(); newQuantity.setCount(quantityToAdd); GregorianCalendar itemDate = new GregorianCalendar(Integer.parseInt(ymd[0]),Integer.parseInt(ymd[1]),Integer.parseInt(ymd[2])); newQuantity.setDate(itemDate.getTime()); ingredientStaged.addQuantity(newQuantity); toBeAdded.add(ingredientStaged); connection.addItemsToInventory(toBeAdded); System.out.println(newQuantity.getCount() + " " + ingreds.get(ingredientToAdd).getName() + " have been added to the inventory!"); break; case 3: printHeader("End Day"); connection.updateDate(); System.out.println("Moved on to the next day!"); break; case 4: printHeader("Forecast Shopping List"); forecastApi(connection); break; case 5: printHeader("Load Data from file"); System.out.println("Would you like to load from default files?: (Y/N)"); input = s.nextLine(); if (input.equalsIgnoreCase("Y")) { loadDishesFile("data.csv"); loadInventoryFile("inventory.csv"); }else { System.out.println("Please specify a file name to load for DISHES: "); input = s.nextLine(); loadDishesFile(input); System.out.println("Please specify a file name to load for INVENTORY: "); input = s.nextLine(); loadInventoryFile(input); } break; default: System.out.println("***Incorrect input, try again.***"); break; } printMenu(); System.out.println("\nSelect a menu option: "); input = s.nextLine(); } } }
src/edu/uic/cs342/group7/rim/Client.java
/** * Restaurant Inventory Management * Group 7 */ package edu.uic.cs342.group7.rim; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; //Java 8 routines //import java.io.IOException; //import java.nio.charset.StandardCharsets; //import java.nio.file.Files; //import java.nio.file.Paths; import java.util.Scanner; /** * @authors * Adrian Pasciak, * Chase Lee, * Christopher Schultz, * Nerijus Gelezinis (no-show), * Patrick Tam * */ public class Client { static ArrayList<Ingredient> ingreds = new ArrayList<Ingredient>(); static ArrayList<Dish> dishes = new ArrayList<Dish>(); static Api connection = new Api(); static HashMap<String, String> dishSizes = new HashMap<String, String>(); /** * Constructor Stub */ public Client() { // TODO Auto-generated constructor stub // TODO We should create an instance of the RIM API in this class. } /** * This function will print out the menu for the user to select from. * There are no arguments for this function. */ private static void printMenu() { printHeader("Menu"); System.out.println("1. Order Dish"); System.out.println("2. Add Items to Inventory"); System.out.println("3. End Day"); System.out.println("4. Forecast Shopping List"); System.out.println("5. Load Dishes from file"); System.out.println("q. Quit"); } /** * This function wll print out a header for a given text string. * @param text - A string to place within the header flag. */ public static void printHeader(String text) { int count = text.length(); String dash = "-"; for (int i = 0; i < count-1; i++) { dash = dash.concat("-"); } System.out.println("+" + dash + "+"); System.out.println("+" + text + "+"); System.out.println("+" + dash + "+"); } /** * This will determine if a ingredient is in the larger list of ingredients, identified by name. * @param haystack - The list of all ingredients * @param needle - The string you are looking for, identifying the ingredient * @return - true if the ingredient is found, false if not. */ public static boolean ingredientExists(ArrayList<Ingredient> haystack, String needle) { for (Ingredient item : haystack) { if (item.getName().equalsIgnoreCase(needle)) { return true; } } return false; } public static Ingredient getIngredient(ArrayList<Ingredient> haystack, String needle) { for (Ingredient item : haystack) { if (item.getName().equalsIgnoreCase(needle)) { return item; } } return null; } public static boolean isNumeric(String str) { return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. } private static void loadDishesFile(String file) { // This is Java 8... 5 lines to read the file... // try { // Files.lines(Paths.get(input), StandardCharsets.UTF_8).forEach(System.out::println); // } catch (IOException e) { // e.printStackTrace(); // } BufferedReader br = null; String line = null; try { br = new BufferedReader(new FileReader(file)); while ((line = br.readLine()) != null) { if (line.startsWith("#")) { continue; // Comment detection } String[] elements = line.split(","); ArrayList<DishIngredient> dishRecipe = new ArrayList<DishIngredient>(); /** * For each line: * - Add an Ingredient if not exists in array * - Make a dishIngredient and append to list * - Create a Dish * - Add dish to dishArray */ for (int i = 1; i < elements.length; i++) { String[] elemquant = elements[i].split(":"); Ingredient currentIngredient = new Ingredient(elemquant[0]); if(!ingredientExists(ingreds, elemquant[0])) { ingreds.add(currentIngredient); System.out.println("Added " + currentIngredient.getName()); }else { System.out.println("Skipping ingredient."); } DishIngredient currentDishIngredient = new DishIngredient(getIngredient(ingreds, elemquant[0]), Integer.parseInt(elemquant[1])); dishRecipe.add(currentDishIngredient); } Dish currentDish = new Dish(dishRecipe, elements[0]); dishes.add(currentDish); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } connection.loadIngredients(ingreds); connection.loadDishes(dishes); } private static void loadInventoryFile(String file) { BufferedReader br2 = null; String line2 = null; ArrayList<Ingredient> toBeAdded2 = new ArrayList<Ingredient>(); try { br2 = new BufferedReader(new FileReader(file)); while ((line2 = br2.readLine()) != null) { if (line2.startsWith("#")) { continue; // Comment detection } String[] elements = line2.split(","); String ingredientName = elements[0]; int curQuantity = Integer.parseInt(elements[1]); String[] parseDate = elements[2].split("/"); GregorianCalendar date2 = new GregorianCalendar(Integer.parseInt(parseDate[0]),Integer.parseInt(parseDate[1]),Integer.parseInt(parseDate[2])); if (ingredientExists(ingreds,ingredientName)) { Ingredient ingredientToAdd2 = new Ingredient(ingredientName); Quantity newQuantity2 = new Quantity(); newQuantity2.setCount(curQuantity); newQuantity2.setDate(date2.getTime()); ingredientToAdd2.addQuantity(newQuantity2); toBeAdded2.add(ingredientToAdd2); System.out.println("Added: " + newQuantity2.getCount() + " " + ingredientName + "(s) set to expire on " + newQuantity2.getDate().toString()); } } System.out.println("Committed " + toBeAdded2.size() + " distinct items"); connection.addItemsToInventory(toBeAdded2); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br2 != null) { try { br2.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * This function is the main driver and client for the our project. This * main function will handle all the interface logic with the user. * @param args - This parameter is not used. */ public static void main(String[] args) { String version = "1.00"; System.out.println("+------------------------------------------------------------------------------+"); System.out.format("+ Restaurant Inventory Management v%s +\n", version); System.out.println("+ Authors: Adrian Pasciak, Chase Lee, Christopher Schultz, +"); System.out.println("+ Nerijus Gelezinis (no-show), Patrick Tam +"); System.out.println("+------------------------------------------------------------------------------+"); dishSizes.put("F", "Full Size Order"); dishSizes.put("S", "Super Size Order"); dishSizes.put("H", "Half Size Order"); System.out.println("Current Status: NOT IMPLEMENTED"); printMenu(); System.out.println("\nSelect a menu option: "); boolean runflag = true; int count = 0; Scanner s = new Scanner(System.in); String input = s.nextLine(); while (!("q".equalsIgnoreCase(input))) { while (!isNumeric(input)) { input = s.nextLine(); // Grab any stay lines. } switch(Integer.parseInt(input)) { case 1: printHeader("Order Dish"); System.out.println("Please select the dish you would like to order:"); count = 0; for(Dish item : dishes) { System.out.println(count +") "+ item.getName()); count++; } input = null; input = s.nextLine(); int getDish = Integer.parseInt(input); System.out.println("Please select a dish size:"); System.out.println("S) Super Size Order"); System.out.println("F) Full Size Order (Normal)"); System.out.println("H) Half Size Order"); input = null; input = s.nextLine(); while (input.length() <= 0) { input = s.nextLine(); } String dSize = input; boolean result = connection.orderDish(dishes.get(getDish).getName(), dishSizes.get(dSize.substring(0, 1))); if (result) { System.out.println(dishSizes.get(dSize.substring(0, 1)) + " of " + dishes.get(getDish).getName() + " ordered successfully."); }else { System.out.println(dishSizes.get(dSize.substring(0, 1)) + " of " + dishes.get(getDish).getName() + " order failed."); } break; case 2: printHeader("Add Items to Inventory Quantity"); count = 0; for(Ingredient item : ingreds) { System.out.println(count + ") " + item.getName() + " - " + item.getTotalQuantityOfIngredient()); count++; } System.out.println("Please select the ingredient you would like to add quantity to:"); int ingredientToAdd = s.nextInt(); while(ingredientToAdd > ingreds.size() || ingredientToAdd < 0) { System.out.println("Invalid option, try again:"); ingredientToAdd = s.nextInt(); } System.out.println("How many would you like to add?:"); int quantityToAdd = s.nextInt(); while(quantityToAdd < 0) { System.out.println("Invalid quantity, try again:"); quantityToAdd = s.nextInt(); } input = s.nextLine(); // Eat up new line. System.out.println("When is the expiration?: yy/mm/dd"); input = s.nextLine(); String[] ymd = input.split("/"); ArrayList<Ingredient> toBeAdded = new ArrayList<Ingredient>(); Ingredient ingredientStaged = new Ingredient(ingreds.get(ingredientToAdd).getName()); Quantity newQuantity = new Quantity(); newQuantity.setCount(quantityToAdd); GregorianCalendar itemDate = new GregorianCalendar(Integer.parseInt(ymd[0]),Integer.parseInt(ymd[1]),Integer.parseInt(ymd[2])); newQuantity.setDate(itemDate.getTime()); ingredientStaged.addQuantity(newQuantity); toBeAdded.add(ingredientStaged); connection.addItemsToInventory(toBeAdded); System.out.println(newQuantity.getCount() + " " + ingreds.get(ingredientToAdd).getName() + " have been added to the inventory!"); break; case 3: printHeader("End Day"); connection.updateDate(); break; case 4: printHeader("Forecast Shopping List"); ArrayList<Ingredient> shoplist = connection.getShoppingList(); System.out.println("We are below a threshold on these ingredients. Here are the current quantities:"); for (Ingredient item : shoplist) { System.out.format("%d : %s\n", item.getTotalQuantityOfIngredient(), item.getName()); } break; case 5: printHeader("Load Dishes from file"); System.out.println("Please specify a file name to load: "); input = s.nextLine(); loadDishesFile(input); break; case 6: printHeader("Load Ingredient Quantities from file"); System.out.println("Please specify a file name to load: "); input = s.nextLine(); loadInventoryFile(input); break; default: System.out.println("***Incorrect input, try again.***"); break; } printMenu(); System.out.println("\nSelect a menu option: "); input = s.nextLine(); } } }
Bug Fixes for Client Class. I believe this is pretty much done!
src/edu/uic/cs342/group7/rim/Client.java
Bug Fixes for Client Class. I believe this is pretty much done!
<ide><path>rc/edu/uic/cs342/group7/rim/Client.java <ide> System.out.println("2. Add Items to Inventory"); <ide> System.out.println("3. End Day"); <ide> System.out.println("4. Forecast Shopping List"); <del> System.out.println("5. Load Dishes from file"); <add> System.out.println("5. Load data from file"); <ide> System.out.println("q. Quit"); <ide> } <ide> /** <ide> return false; <ide> } <ide> <add> /** <add> * This will return the Ingredient object that is in the larger list of ingredients, identified by name. <add> * @param haystack - The list of all ingredients. <add> * @param needle - The string you are looking for, identifying the ingredient. <add> * @return - Returns the Ingredient instance that was found in the haystack. <add> */ <ide> public static Ingredient getIngredient(ArrayList<Ingredient> haystack, String needle) { <ide> for (Ingredient item : haystack) { <ide> if (item.getName().equalsIgnoreCase(needle)) { <ide> return null; <ide> } <ide> <add> /** <add> * Determines if a string is a number <add> * @param str - A string to be determined to be a number or not. <add> * @return - True if the string is parsable into a number. False if not a string parsable into a number. <add> */ <ide> public static boolean isNumeric(String str) <ide> { <ide> return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal. <ide> } <ide> <add> /** <add> * Loads a dishes file to be added into the running database. <add> * @param file - the filename / filepath from the current working directory. (one directory above the src folder) <add> */ <ide> private static void loadDishesFile(String file) { <ide> // This is Java 8... 5 lines to read the file... <ide> // try { <ide> connection.loadDishes(dishes); <ide> } <ide> <add> /** <add> * Loads a inventory file to be added into the running database. <add> * @param file - the filename / filepath from the current working directory. (one directory above the src folder) <add> */ <ide> private static void loadInventoryFile(String file) { <ide> BufferedReader br2 = null; <ide> String line2 = null; <ide> } <ide> } <ide> } <add> <add> /** <add> * Calls the API and determines what we need to buy. <add> * @param api - the connection/instance of the api. <add> */ <add> public static void forecastApi(Api api) { <add> ArrayList<Ingredient> list = api.getShoppingList(); <add> api.addItemsToInventory(list); <add> Iterator<Ingredient> itr = list.iterator(); <add> Ingredient ingredient; <add> <add> System.out.println("******** Shopping List **********"); <add> while(itr.hasNext()) { <add> ingredient = itr.next(); <add> System.out.println("Ingredient: " + ingredient.getName() + " Quantity: " + ingredient.getTotalQuantityOfIngredient()); <add> } <add> System.out.println("\n"); <add> } <ide> /** <ide> * This function is the main driver and client for the our project. This <ide> * main function will handle all the interface logic with the user. <ide> System.out.println("+ Authors: Adrian Pasciak, Chase Lee, Christopher Schultz, +"); <ide> System.out.println("+ Nerijus Gelezinis (no-show), Patrick Tam +"); <ide> System.out.println("+------------------------------------------------------------------------------+"); <del> dishSizes.put("F", "Full Size Order"); <del> dishSizes.put("S", "Super Size Order"); <del> dishSizes.put("H", "Half Size Order"); <add> dishSizes.put("F", "Full order"); <add> dishSizes.put("S", "Super size order"); <add> dishSizes.put("H", "Half order"); <ide> System.out.println("Current Status: NOT IMPLEMENTED"); <ide> printMenu(); <ide> System.out.println("\nSelect a menu option: "); <ide> } <ide> input = null; <ide> input = s.nextLine(); <add> while (Integer.parseInt(input) > dishes.size()) { <add> System.out.println("Invalid option. Try again:"); <add> input = s.nextLine(); <add> } <ide> int getDish = Integer.parseInt(input); <ide> System.out.println("Please select a dish size:"); <ide> System.out.println("S) Super Size Order"); <ide> input = s.nextLine(); <ide> } <ide> String dSize = input; <del> boolean result = connection.orderDish(dishes.get(getDish).getName(), dishSizes.get(dSize.substring(0, 1))); <add> boolean result = connection.orderDish(dishes.get(getDish).getName(), dishSizes.get(dSize.substring(0, 1).toUpperCase())); <ide> if (result) { <del> System.out.println(dishSizes.get(dSize.substring(0, 1)) + " of " + dishes.get(getDish).getName() + " ordered successfully."); <add> System.out.println(dishSizes.get(dSize.substring(0, 1).toUpperCase()) + " of " + dishes.get(getDish).getName() + " ordered successfully."); <ide> }else { <del> System.out.println(dishSizes.get(dSize.substring(0, 1)) + " of " + dishes.get(getDish).getName() + " order failed."); <add> System.out.println(dishSizes.get(dSize.substring(0, 1).toUpperCase()) + " of " + dishes.get(getDish).getName() + " order failed."); <ide> } <ide> break; <ide> case 2: <ide> case 3: <ide> printHeader("End Day"); <ide> connection.updateDate(); <add> System.out.println("Moved on to the next day!"); <ide> break; <ide> case 4: <ide> printHeader("Forecast Shopping List"); <del> ArrayList<Ingredient> shoplist = connection.getShoppingList(); <del> System.out.println("We are below a threshold on these ingredients. Here are the current quantities:"); <del> for (Ingredient item : shoplist) { <del> System.out.format("%d : %s\n", item.getTotalQuantityOfIngredient(), item.getName()); <del> } <add> forecastApi(connection); <ide> break; <ide> case 5: <del> printHeader("Load Dishes from file"); <del> System.out.println("Please specify a file name to load: "); <add> printHeader("Load Data from file"); <add> System.out.println("Would you like to load from default files?: (Y/N)"); <ide> input = s.nextLine(); <del> loadDishesFile(input); <del> <del> break; <del> case 6: <del> printHeader("Load Ingredient Quantities from file"); <del> System.out.println("Please specify a file name to load: "); <del> input = s.nextLine(); <del> loadInventoryFile(input); <add> if (input.equalsIgnoreCase("Y")) { <add> loadDishesFile("data.csv"); <add> loadInventoryFile("inventory.csv"); <add> }else { <add> System.out.println("Please specify a file name to load for DISHES: "); <add> input = s.nextLine(); <add> loadDishesFile(input); <add> System.out.println("Please specify a file name to load for INVENTORY: "); <add> input = s.nextLine(); <add> loadInventoryFile(input); <add> } <ide> break; <ide> default: <ide> System.out.println("***Incorrect input, try again.***");
Java
mit
aa5dc8e4f40156df017a1f4f213facb62b105a4d
0
hotchemi/Android-Rate,cafedeaqua/Android-Rate,y-matsumoto/Android-Rate,gPinato/Android-Rate,android-gems/Android-Rate,phajduk/Android-Rate,kzganesan/Android-Rate
package hotchemi.android.rate; import android.view.View; final class DialogOptions { private boolean showNeutralButton = true; private boolean showTitle = true; private int titleResId = R.string.rate_dialog_title; private int messageResId = R.string.rate_dialog_message; private int textPositiveResId = R.string.rate_dialog_ok; private int textNeutralResId = R.string.rate_dialog_cancel; private int textNegativeResId = R.string.rate_dialog_no; private View view; private OnClickButtonListener listener; public boolean shouldShowNeutralButton() { return showNeutralButton; } public void setShowNeutralButton(boolean showNeutralButton) { this.showNeutralButton = showNeutralButton; } public boolean shouldShowTitle() { return showTitle; } public void setShowTitle(boolean showTitle) { this.showTitle = showTitle; } public int getTitleResId() { return titleResId; } public void setTitleResId(int titleResId) { this.titleResId = titleResId; } public int getMessageResId() { return messageResId; } public void setMessageResId(int messageResId) { this.messageResId = messageResId; } public int getTextPositiveResId() { return textPositiveResId; } public void setTextPositiveResId(int textPositiveResId) { this.textPositiveResId = textPositiveResId; } public int getTextNeutralResId() { return textNeutralResId; } public void setTextNeutralResId(int textNeutralResId) { this.textNeutralResId = textNeutralResId; } public int getTextNegativeResId() { return textNegativeResId; } public void setTextNegativeResId(int textNegativeResId) { this.textNegativeResId = textNegativeResId; } public View getView() { return view; } public void setView(View view) { this.view = view; } public OnClickButtonListener getListener() { return listener; } public void setListener(OnClickButtonListener listener) { this.listener = listener; } }
library/src/main/java/hotchemi/android/rate/DialogOptions.java
package hotchemi.android.rate; import android.view.View; import java.lang.ref.WeakReference; final class DialogOptions { private boolean showNeutralButton = true; private boolean showTitle = true; private int titleResId = R.string.rate_dialog_title; private int messageResId = R.string.rate_dialog_message; private int textPositiveResId = R.string.rate_dialog_ok; private int textNeutralResId = R.string.rate_dialog_cancel; private int textNegativeResId = R.string.rate_dialog_no; private WeakReference<View> view; private WeakReference<OnClickButtonListener> listener; public boolean shouldShowNeutralButton() { return showNeutralButton; } public void setShowNeutralButton(boolean showNeutralButton) { this.showNeutralButton = showNeutralButton; } public boolean shouldShowTitle() { return showTitle; } public void setShowTitle(boolean showTitle) { this.showTitle = showTitle; } public int getTitleResId() { return titleResId; } public void setTitleResId(int titleResId) { this.titleResId = titleResId; } public int getMessageResId() { return messageResId; } public void setMessageResId(int messageResId) { this.messageResId = messageResId; } public int getTextPositiveResId() { return textPositiveResId; } public void setTextPositiveResId(int textPositiveResId) { this.textPositiveResId = textPositiveResId; } public int getTextNeutralResId() { return textNeutralResId; } public void setTextNeutralResId(int textNeutralResId) { this.textNeutralResId = textNeutralResId; } public int getTextNegativeResId() { return textNegativeResId; } public void setTextNegativeResId(int textNegativeResId) { this.textNegativeResId = textNegativeResId; } public View getView() { if (view == null) { return null; } return view.get(); } public void setView(View view) { this.view = new WeakReference<>(view); } public OnClickButtonListener getListener() { if (listener == null) { return null; } return listener.get(); } public void setListener(OnClickButtonListener listener) { this.listener = new WeakReference<>(listener); } }
Delete weakreference.
library/src/main/java/hotchemi/android/rate/DialogOptions.java
Delete weakreference.
<ide><path>ibrary/src/main/java/hotchemi/android/rate/DialogOptions.java <ide> package hotchemi.android.rate; <ide> <ide> import android.view.View; <del> <del>import java.lang.ref.WeakReference; <ide> <ide> final class DialogOptions { <ide> <ide> <ide> private int textNegativeResId = R.string.rate_dialog_no; <ide> <del> private WeakReference<View> view; <add> private View view; <ide> <del> private WeakReference<OnClickButtonListener> listener; <add> private OnClickButtonListener listener; <ide> <ide> public boolean shouldShowNeutralButton() { <ide> return showNeutralButton; <ide> } <ide> <ide> public View getView() { <del> if (view == null) { <del> return null; <del> } <del> return view.get(); <add> return view; <ide> } <ide> <ide> public void setView(View view) { <del> this.view = new WeakReference<>(view); <add> this.view = view; <ide> } <ide> <ide> public OnClickButtonListener getListener() { <del> if (listener == null) { <del> return null; <del> } <del> return listener.get(); <add> return listener; <ide> } <ide> <ide> public void setListener(OnClickButtonListener listener) { <del> this.listener = new WeakReference<>(listener); <add> this.listener = listener; <ide> } <ide> <ide> }
Java
apache-2.0
ab3de717d24d7439d5bcdf66dffad50837a5cd80
0
gentics/mesh,gentics/mesh,gentics/mesh,gentics/mesh
package com.gentics.mesh.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.gentics.mesh.core.data.GenericVertex; import com.gentics.mesh.core.data.relationship.GraphPermission; import com.gentics.mesh.core.data.service.BasicObjectTestcases; import com.gentics.mesh.core.field.bool.AbstractBasicDBTest; import com.gentics.mesh.graphdb.Trx; import com.gentics.mesh.handler.InternalActionContext; import io.vertx.ext.web.RoutingContext; public abstract class AbstractBasicObjectTest extends AbstractBasicDBTest implements BasicObjectTestcases { protected void testPermission(GraphPermission perm, GenericVertex<?> node) { try (Trx tx = db.trx()) { role().grantPermissions(node, perm); tx.success(); } try (Trx tx = db.trx()) { RoutingContext rc = getMockedRoutingContext(""); InternalActionContext ac = InternalActionContext.create(rc); assertTrue(role().hasPermission(perm, node)); assertTrue(getRequestUser().hasPermission(ac, node, perm)); role().revokePermissions(node, perm); rc.data().clear(); assertFalse(role().hasPermission(perm, node)); assertFalse(getRequestUser().hasPermission(ac, node, perm)); } } }
core/src/test/java/com/gentics/mesh/test/AbstractBasicObjectTest.java
package com.gentics.mesh.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.gentics.mesh.core.data.GenericVertex; import com.gentics.mesh.core.data.relationship.GraphPermission; import com.gentics.mesh.core.data.service.BasicObjectTestcases; import com.gentics.mesh.core.field.bool.AbstractBasicDBTest; import com.gentics.mesh.graphdb.Trx; import com.gentics.mesh.handler.InternalActionContext; import io.vertx.ext.web.RoutingContext; public abstract class AbstractBasicObjectTest extends AbstractBasicDBTest implements BasicObjectTestcases { protected void testPermission(GraphPermission perm, GenericVertex<?> node) { try (Trx tx = db.trx()) { role().grantPermissions(node, perm); tx.success(); } RoutingContext rc = getMockedRoutingContext(""); InternalActionContext ac = InternalActionContext.create(rc); assertTrue(role().hasPermission(perm, node)); assertTrue(getRequestUser().hasPermission(ac, node, perm)); role().revokePermissions(node, perm); rc.data().clear(); assertFalse(role().hasPermission(perm, node)); assertFalse(getRequestUser().hasPermission(ac, node, perm)); } }
Fix permission unit tests
core/src/test/java/com/gentics/mesh/test/AbstractBasicObjectTest.java
Fix permission unit tests
<ide><path>ore/src/test/java/com/gentics/mesh/test/AbstractBasicObjectTest.java <ide> tx.success(); <ide> } <ide> <del> RoutingContext rc = getMockedRoutingContext(""); <del> InternalActionContext ac = InternalActionContext.create(rc); <del> assertTrue(role().hasPermission(perm, node)); <del> assertTrue(getRequestUser().hasPermission(ac, node, perm)); <del> role().revokePermissions(node, perm); <del> rc.data().clear(); <del> assertFalse(role().hasPermission(perm, node)); <del> assertFalse(getRequestUser().hasPermission(ac, node, perm)); <add> try (Trx tx = db.trx()) { <add> RoutingContext rc = getMockedRoutingContext(""); <add> InternalActionContext ac = InternalActionContext.create(rc); <add> assertTrue(role().hasPermission(perm, node)); <add> assertTrue(getRequestUser().hasPermission(ac, node, perm)); <add> role().revokePermissions(node, perm); <add> rc.data().clear(); <add> assertFalse(role().hasPermission(perm, node)); <add> assertFalse(getRequestUser().hasPermission(ac, node, perm)); <add> } <ide> } <ide> <ide> }
Java
apache-2.0
0fb65ccd988f0bbdaf6ac80a75f682755c32d46f
0
Nastel/tnt4j-stream-jmx,Nastel/PingJMX,Nastel/tnt4j-stream-jmx,Nastel/PingJMX,Nastel/tnt4j-stream-jmx
/* * Copyright 2015-2018 JKOOL, LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jkoolcloud.tnt4j.stream.jmx; import static com.jkoolcloud.tnt4j.stream.jmx.core.DefaultSampleListener.ListenerProperties.*; import java.io.*; import java.lang.instrument.Instrumentation; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import javax.management.*; import javax.management.remote.JMXAddressable; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import org.apache.commons.lang3.StringUtils; import com.jkoolcloud.tnt4j.config.DefaultConfigFactory; import com.jkoolcloud.tnt4j.config.TrackerConfig; import com.jkoolcloud.tnt4j.config.TrackerConfigStore; import com.jkoolcloud.tnt4j.core.OpLevel; import com.jkoolcloud.tnt4j.sink.DefaultEventSinkFactory; import com.jkoolcloud.tnt4j.sink.EventSink; import com.jkoolcloud.tnt4j.source.Source; import com.jkoolcloud.tnt4j.source.SourceFactory; import com.jkoolcloud.tnt4j.source.SourceType; import com.jkoolcloud.tnt4j.stream.jmx.core.DefaultSampleListener; import com.jkoolcloud.tnt4j.stream.jmx.core.PropertyNameBuilder; import com.jkoolcloud.tnt4j.stream.jmx.core.Sampler; import com.jkoolcloud.tnt4j.stream.jmx.factory.DefaultSamplerFactory; import com.jkoolcloud.tnt4j.stream.jmx.factory.SamplerFactory; import com.jkoolcloud.tnt4j.stream.jmx.utils.Utils; import com.jkoolcloud.tnt4j.stream.jmx.utils.VMUtils; /** * <p> * This class provides java agent implementation {@link #premain(String, Instrumentation)}, * {@link #agentmain(String, Instrumentation)} as well as {@link #main(String[])} entry point to run as a standalone * application. * </p> * * @version $Revision: 1 $ * * @see SamplerFactory */ public class SamplingAgent { private static final EventSink LOGGER = DefaultEventSinkFactory.defaultEventSink(SamplingAgent.class); public static final String SOURCE_SERVER_ADDRESS = "sjmx.serverAddress"; public static final String SOURCE_SERVER_NAME = "sjmx.serverName"; public static final String SOURCE_SERVICE_ID = "sjmx.serviceId"; protected Sampler platformJmx; protected ConcurrentHashMap<MBeanServerConnection, Sampler> STREAM_AGENTS = new ConcurrentHashMap<MBeanServerConnection, Sampler>( 89); private static Map<Thread, SamplingAgent> agents = new HashMap<Thread, SamplingAgent>(); protected static final long CONN_RETRY_INTERVAL = 10; private static final String LOG4J_PROPERTIES_KEY = "log4j.configuration"; private static final String SYS_PROP_LOG4J_CFG = "-D" + LOG4J_PROPERTIES_KEY; private static final String SYS_PROP_TNT4J_CFG = "-D" + TrackerConfigStore.TNT4J_PROPERTIES_KEY; private static final String SYS_PROP_AGENT_PATH = "-DSamplingAgent.path"; private static final String PARAM_VM_DESCRIPTOR = "-vm:"; private static final String PARAM_AGENT_LIB_PATH = "-ap:"; private static final String PARAM_AGENT_OPTIONS = "-ao:"; private static final String PARAM_AGENT_USER_LOGIN = "-ul:"; private static final String PARAM_AGENT_USER_PASS = "-up:"; private static final String PARAM_AGENT_CONN_PARAM = "-cp:"; private static final String PARAM_AGENT_CONN_RETRY_INTERVAL = "-cri:"; private static final String PARAM_AGENT_LISTENER_PARAM = "-slp:"; private static final String PARAM_AGENT_SYSTEM_PROPERTY = "-sp:"; private static final String PARAM_AGENT_CONNECTIONS_CONFIG_FILE = "-f:"; private static final String AGENT_MODE_AGENT = "-agent"; private static final String AGENT_MODE_ATTACH = "-attach"; private static final String AGENT_MODE_CONNECT = "-connect"; private static final String AGENT_MODE_LOCAL = "-local"; private static final String AGENT_ARG_MODE = "agent.mode"; private static final String AGENT_ARG_VM = "vm.descriptor"; private static final String AGENT_ARG_USER = "user.login"; private static final String AGENT_ARG_PASS = "user.password"; private static final String AGENT_ARG_CONN_RETRY_INTERVAL = "conn.retry.interval"; private static final String AGENT_ARG_LIB_PATH = "agent.lib.path"; private static final String AGENT_ARG_OPTIONS = "agent.options"; private static final String AGENT_ARG_I_FILTER = "beans.include.filter"; private static final String AGENT_ARG_E_FILTER = "beans.exclude.filter"; private static final String AGENT_ARG_S_TIME = "agent.sample.time"; private static final String AGENT_ARG_D_TIME = "agent.sample.delay.time"; private static final String AGENT_ARG_W_TIME = "agent.wait.time"; private static final String AGENT_CONN_PARAMS = "agent.connection.params"; private static final String AGENT_CONNS_CONFIG_FILE = "agent.connections.config.file"; private static final String DEFAULT_AGENT_OPTIONS = Sampler.JMX_FILTER_ALL + "!" + Sampler.JMX_FILTER_NONE + "!" + Sampler.JMX_SAMPLE_PERIOD; public static final Properties DEFAULTS = new Properties(); public static final Map<String, Object> LISTENER_PROPERTIES = new HashMap<String, Object>(5); static { initDefaults(DEFAULTS); copyProperty(FORCE_OBJECT_NAME, DEFAULTS, LISTENER_PROPERTIES, false); copyProperty(COMPOSITE_DELIMITER, DEFAULTS, LISTENER_PROPERTIES, PropertyNameBuilder.DEFAULT_COMPOSITE_DELIMITER); copyProperty(USE_OBJECT_NAME_PROPERTIES, DEFAULTS, LISTENER_PROPERTIES, true); copyProperty(FORCE_OBJECT_NAME, System.getProperties(), LISTENER_PROPERTIES); copyProperty(COMPOSITE_DELIMITER, System.getProperties(), LISTENER_PROPERTIES); copyProperty(USE_OBJECT_NAME_PROPERTIES, System.getProperties(), LISTENER_PROPERTIES); } private boolean stopSampling = false; private SamplingAgent() { } public static SamplingAgent newSamplingAgent() { SamplingAgent agent = new SamplingAgent(); agents.put(Thread.currentThread(), agent); return agent; } /** * Entry point to be loaded as {@code -javaagent:jarpath="mbean-filter!sample.ms!initDelay.ms"} command line where * {@code initDelay} is optional. Example: {@code -javaagent:tnt4j-sample-jmx.jar="*:*!30000!1000"} * * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param inst * instrumentation handle * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public static void premain(String options, Instrumentation inst) throws IOException { String incFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.include.filter", Sampler.JMX_FILTER_ALL); String excFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.exclude.filter", Sampler.JMX_FILTER_NONE); int period = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.period", Sampler.JMX_SAMPLE_PERIOD); int initDelay = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.init.delay", period); if (options != null) { String[] args = options.split("!"); if (args.length > 0) { incFilter = args[0]; } if (args.length > 1) { excFilter = args.length > 2 ? args[1] : excFilter; period = Integer.parseInt(args.length > 2 ? args[2] : args[1]); } if (args.length > 2) { initDelay = Integer.parseInt(args.length > 3 ? args[3] : args[2]); } } SamplingAgent agent = newSamplingAgent(); agent.sample(incFilter, excFilter, initDelay, period, TimeUnit.MILLISECONDS); LOGGER.log(OpLevel.INFO, "SamplingAgent.premain: include.filter={0}, exclude.filter={1}, sample.ms={2}, initDelay.ms={3}, listener.properties={4}, tnt4j.config={5}, jmx.sample.list={6}", incFilter, excFilter, period, initDelay, LISTENER_PROPERTIES, System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY), agent.STREAM_AGENTS); } /** * Entry point to be loaded as JVM agent. Does same as {@link #premain(String, Instrumentation)}. * * @param agentArgs * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param inst * instrumentation handle * @throws IOException * if any I/O exception occurs while starting agent * * @see #premain(String, Instrumentation) */ public static void agentmain(String agentArgs, Instrumentation inst) throws Exception { LOGGER.log(OpLevel.INFO, "SamplingAgent.agentmain(): agentArgs={0}", agentArgs); String agentParams = ""; String tnt4jProp = System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY); String log4jProp = System.getProperty(LOG4J_PROPERTIES_KEY); String agentLibPath = ""; if (!Utils.isEmpty(agentArgs)) { String[] args = agentArgs.split("!"); for (String arg : args) { if (arg.startsWith(SYS_PROP_TNT4J_CFG)) { if (Utils.isEmpty(tnt4jProp)) { String[] prop = arg.split("=", 2); tnt4jProp = prop.length > 1 ? prop[1] : null; System.setProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY, tnt4jProp); } } else if (arg.startsWith(SYS_PROP_AGENT_PATH)) { String[] prop = arg.split("=", 2); agentLibPath = prop.length > 1 ? prop[1] : null; } if (arg.startsWith(SYS_PROP_LOG4J_CFG)) { if (Utils.isEmpty(log4jProp)) { String[] prop = arg.split("=", 2); log4jProp = prop.length > 1 ? prop[1] : null; System.setProperty(LOG4J_PROPERTIES_KEY, log4jProp); } } else if (arg.startsWith(FORCE_OBJECT_NAME.pName() + "=")) { String[] prop = arg.split("=", 2); if (prop.length > 1) { LISTENER_PROPERTIES.put(FORCE_OBJECT_NAME.pName(), prop[1]); } } else if (arg.startsWith(COMPOSITE_DELIMITER.pName() + "=")) { String[] prop = arg.split("=", 2); if (prop.length > 1) { LISTENER_PROPERTIES.put(COMPOSITE_DELIMITER.pName(), prop[1]); } } else if (arg.startsWith(USE_OBJECT_NAME_PROPERTIES.pName() + "=")) { String[] prop = arg.split("=", 2); if (prop.length > 1) { LISTENER_PROPERTIES.put(USE_OBJECT_NAME_PROPERTIES.pName(), prop[1]); } } else { agentParams += agentParams.isEmpty() ? arg : "!" + arg; } } } LOGGER.log(OpLevel.INFO, "SamplingAgent.agentmain: agent.params={0}, agent.lib.path={1}, listener.properties={2}, tnt4j.config={3}", agentParams, agentLibPath, LISTENER_PROPERTIES, System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY)); File agentPath = new File(agentLibPath); String[] classPathEntries = agentPath.list(new JarFilter()); if (classPathEntries != null) { File pathFile; for (String classPathEntry : classPathEntries) { pathFile = new File(classPathEntry); LOGGER.log(OpLevel.INFO, "SamplingAgent.agentmain: extending classpath with: {0}", pathFile.getAbsolutePath()); extendClasspath(pathFile.toURI().toURL()); } } premain(agentParams, inst); } /** * Loads required classpath entries to running JVM. * * @param classPathEntriesURL * classpath entries URLs to attach to JVM * @throws Exception * if exception occurs while extending system class loader's classpath */ private static void extendClasspath(URL... classPathEntriesURL) throws Exception { URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); for (URL classPathEntryURL : classPathEntriesURL) { try { method.invoke(classLoader, classPathEntryURL); } catch (Exception e) { LOGGER.log(OpLevel.ERROR, "SamplingAgent.extendClasspath: could not load lib {0}", classPathEntryURL); LOGGER.log(OpLevel.ERROR, " Exception: {0}", Utils.getExceptionMessages(e)); } } } /** * Main entry point for running as a standalone application (test only). * * @param args * argument list: [sampling-mode vm-descriptor] [mbean-filter sample_time_ms] * * @throws Exception * if exception occurs while initializing MBeans sampling */ public static void main(String[] args) throws Exception { Properties props = new Properties(); boolean argsValid = parseArgs(props, args); if (argsValid) { SamplerFactory sFactory = DefaultSamplerFactory .getInstance(Utils.getConfProperty(DEFAULTS, "com.jkoolcloud.tnt4j.stream.jmx.sampler.factory")); sFactory.initialize(); String am = props.getProperty(AGENT_ARG_MODE); if (AGENT_MODE_CONNECT.equalsIgnoreCase(am)) { String fileName = props.getProperty(AGENT_CONNS_CONFIG_FILE); if (StringUtils.isEmpty(fileName)) { List<ConnectionParams> allVMs = getAllVMs(props); connectAll(allVMs, props); } else { List<ConnectionParams> allVMs = getConnectionParamsFromFile(fileName); if (allVMs == null || allVMs.isEmpty()) { LOGGER.log(OpLevel.CRITICAL, "No JVM connections loaded from configuration file ''{0}''", fileName); } else { connectAll(allVMs, props); } } } else if (AGENT_MODE_ATTACH.equalsIgnoreCase(am)) { String vmDescr = props.getProperty(AGENT_ARG_VM); String jarPath = props.getProperty(AGENT_ARG_LIB_PATH); String agentOptions = props.getProperty(AGENT_ARG_OPTIONS, DEFAULT_AGENT_OPTIONS); attach(vmDescr, jarPath, agentOptions); } else if (AGENT_MODE_LOCAL.equalsIgnoreCase(am)) { String agentOptions = props.getProperty(AGENT_ARG_OPTIONS, DEFAULT_AGENT_OPTIONS); sampleLocalVM(agentOptions, true); } else { try { String inclF = props.getProperty(AGENT_ARG_I_FILTER, Sampler.JMX_FILTER_ALL); String exclF = props.getProperty(AGENT_ARG_E_FILTER, Sampler.JMX_FILTER_NONE); long sample_time = Integer .parseInt(props.getProperty(AGENT_ARG_S_TIME, String.valueOf(Sampler.JMX_SAMPLE_PERIOD))); long delay_time = Integer .parseInt(props.getProperty(AGENT_ARG_D_TIME, String.valueOf(sample_time))); long wait_time = Integer.parseInt(props.getProperty(AGENT_ARG_W_TIME, "0")); SamplingAgent samplingAgent = newSamplingAgent(); samplingAgent.sample(inclF, exclF, delay_time, sample_time, TimeUnit.MILLISECONDS, null); LOGGER.log(OpLevel.INFO, "SamplingAgent.main: include.filter={0}, exclude.filter={1}, sample.ms={2}, delay.ms={3}, wait.ms={4}, listener.properties={5}, tnt4j.config={6}, jmx.sample.list={7}", inclF, exclF, sample_time, delay_time, wait_time, LISTENER_PROPERTIES, System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY), samplingAgent.STREAM_AGENTS); synchronized (samplingAgent.platformJmx) { samplingAgent.platformJmx.wait(wait_time); } } catch (Throwable ex) { LOGGER.log(OpLevel.ERROR, "SamplingAgent.main: failed to configure and run JMX sampling..."); LOGGER.log(OpLevel.ERROR, " Exception: {0}", Utils.getExceptionMessages(ex)); } } } else { LOGGER.log(OpLevel.INFO, "Printing usage instructions before exit!.."); String usageStr = "Usage: mbean-filter exclude-filter sample-ms [wait-ms] (e.g \"*:*\" \"\" 10000 60000)\n" + " or: -attach -vm:vmName/vmId -ap:agentJarPath -ao:agentOptions (e.g -attach -vm:activemq -ap:[ENV_PATH]/tnt-stream-jmx.jar -ao:*:*!!10000)\n" + " or: -connect -vm:vmName/vmId/JMX_URL -ao:agentOptions (e.g -connect -vm:activemq -ao:*:*!!10000\n" + " or: -connect -vm:vmName/vmId/JMX_URL -cri:connRetryIntervalSec -ao:agentOptions (e.g -connect -vm:activemq -cri:30 -ao:*:*!!10000\n" + " or: -connect -vm:vmName/vmId/JMX_URL -ul:userLogin -up:userPassword -ao:agentOptions (e.g -connect -vm:activemq -ul:admin -up:admin -ao:*:*!!10000\n" + " or: -connect -vm:vmName/vmId/JMX_URL -ul:userLogin -up:userPassword -ao:agentOptions -cp:jmcConnParam1 -cp:jmcConnParam2 -cp:... (e.g -connect -vm:activemq -ul:admin -up:admin -ao:*:*!!10000 -cp:javax.net.ssl.trustStorePassword=trustPass\n" + " or: -local -ao:agentOptions (e.g -local -ao:*:*!!10000\n" + " \n" + "Arguments definition: \n" + " -vm: - virtual machine descriptor. It can be PID or JVM process name fragment.\n" + " -ao: - agent options string using '!' symbol as delimiter. Options format: mbean-filter!exclude-filter!sample-ms!init-delay-ms\n" + " mbean-filter - MBean include name filter defined using object name pattern: domainName:keysSet\n" + " exclude-filter - MBean exclude name filter defined using object name pattern: domainName:keysSet\n" + " sample-ms - MBeans sampling rate in milliseconds\n" + " init-delay-ms - MBeans sampling initial delay in milliseconds. Optional, by default it is equal to 'sample-ms' value.\n" + " -cp: - JMX connection parameter string using '=' symbol as delimiter. Defines only one parameter, to define more than one use this argument multiple times. Argument format: -cp:key=value\n" + " see https://docs.oracle.com/javase/7/docs/technotes/guides/management/agent.html for more details\n" + " -slp: - sampler parameter string using '=' symbol as delimiter. Defines only one parameter, to define more than one use this argument multiple times. Argument format: -slp:key=value\n" + " trace - flag indicating whether the sample listener should print trace entries to print stream. Default value - 'false'\n" + " forceObjectName - flag indicating to forcibly add 'objectName' attribute if such is not present for a MBean. Default value - 'false'\n" + " compositeDelimiter - delimiter used to tokenize composite/tabular type MBean properties keys. Default value - '\\'\n" + " useObjectNameProperties - flag indicating to copy MBean ObjectName contained properties into sample snapshot properties. Default value - 'true'\n" + " -sp: - sampler system property string using '=' symbol as delimiter. Defines only one system property, to define more than one use this argument multiple times. Argument format: -sp:key=value"; System.out.println(usageStr); System.exit(1); } } private static List<ConnectionParams> getConnectionParamsFromFile(String fileName) throws IOException { File file = new File(fileName); if (!file.exists()) { LOGGER.log(OpLevel.CRITICAL, "JVM connections configuration file does not exist: {0}", fileName); return null; } LineNumberReader reader = new LineNumberReader(new FileReader(file)); String line; String ao = null; String user = null; String pass = null; String sourceDescriptor = null; List<ConnectionParams> allVMs = new ArrayList<ConnectionParams>(); while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("#") || line.isEmpty()) { continue; } String[] split = line.split("\\s+"); // vm if (!(split.length == 5 || split.length == 1)) { LOGGER.log(OpLevel.WARNING, "JVM connections configuration file line {0} has invalid syntax: {1}", reader.getLineNumber(), line); continue; } String vm = split[0]; ao = split.length > 1 ? split[1] : ao; user = split.length > 2 ? split[2] : user; pass = split.length > 3 ? split[3] : pass; sourceDescriptor = split.length > 4 ? split[4] : sourceDescriptor; ConnectionParams connectionParams = new ConnectionParams(getJmxServiceURLs(vm).get(0), user, pass, ao, sourceDescriptor); allVMs.add(connectionParams); } return allVMs; } private static void connectAll(List<ConnectionParams> allVMs, Properties props) throws Exception { @SuppressWarnings("unchecked") final Map<String, ?> connParams = (Map<String, ?>) props.get(AGENT_CONN_PARAMS); final long cri = Long .parseLong(props.getProperty(AGENT_ARG_CONN_RETRY_INTERVAL, String.valueOf(CONN_RETRY_INTERVAL))); for (final ConnectionParams cp : allVMs) { final SamplingAgent samplingAgent = SamplingAgent.newSamplingAgent(); Thread connect = new SamplingAgentThread(new Runnable() { @Override public void run() { try { samplingAgent.connect(cp.serviceURL, cp.user, cp.pass, cp.agentOptions, connParams, cri); samplingAgent.stopSampler(); } catch (Exception ex) { throw new RuntimeException(ex); } } }, samplingAgent, cp.additionalSourceFQN); connect.start(); } } private static List<ConnectionParams> getAllVMs(Properties props) throws IOException { String vmDescr = props.getProperty(AGENT_ARG_VM); String user = props.getProperty(AGENT_ARG_USER) == null ? null : props.getProperty(AGENT_ARG_USER); String pass = props.getProperty(AGENT_ARG_PASS) == null ? null : props.getProperty(AGENT_ARG_PASS); String agentOptions = props.getProperty(AGENT_ARG_OPTIONS, DEFAULT_AGENT_OPTIONS); List<ConnectionParams> connectionParamsList = new ArrayList<ConnectionParams>(); List<JMXServiceURL> jmxServiceURLs = getJmxServiceURLs(vmDescr); for (JMXServiceURL jmxServiceURL : jmxServiceURLs) { connectionParamsList.add(new ConnectionParams(jmxServiceURL, user, pass, agentOptions, null)); } return connectionParamsList; } public static Map<MBeanServerConnection, Sampler> getAllSamplers() { Map<MBeanServerConnection, Sampler> samplers = new HashMap<MBeanServerConnection, Sampler>(); for (SamplingAgent agent : agents.values()) { if (agent != null) { samplers.putAll(agent.getSamplers()); } } return samplers; } static class ConnectionParams { JMXServiceURL serviceURL; String user; String pass; String agentOptions; String additionalSourceFQN; public ConnectionParams(JMXServiceURL serviceURL, String user, String pass, String agentOptions, String additionalSourceFQN) throws IOException { this.serviceURL = serviceURL; this.user = user; this.pass = pass; this.agentOptions = agentOptions; this.additionalSourceFQN = additionalSourceFQN; } } private static void resolveServer(String host) { String serverAddress; String serverName; if (StringUtils.isEmpty(host)) { serverAddress = Utils.getLocalHostAddress(); serverName = Utils.getLocalHostName(); } else { serverAddress = Utils.resolveHostNameToAddress(host); serverName = Utils.resolveAddressToHostName(host); } System.setProperty(SOURCE_SERVER_ADDRESS, serverAddress); System.setProperty(SOURCE_SERVER_NAME, serverName); } private static boolean parseArgs(Properties props, String... args) { LOGGER.log(OpLevel.INFO, "SamplingAgent.parseArgs(): args={0}", Arrays.toString(args)); boolean ac = StringUtils.equalsAnyIgnoreCase(args[0], AGENT_MODE_ATTACH, AGENT_MODE_CONNECT); boolean local = AGENT_MODE_LOCAL.equalsIgnoreCase(args[0]); boolean external = false; if (ac || local) { props.setProperty(AGENT_ARG_MODE, args[0]); try { for (int ai = 1; ai < args.length; ai++) { String arg = args[ai]; if (StringUtils.isEmpty(arg)) { continue; } if (arg.startsWith(PARAM_VM_DESCRIPTOR)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_VM))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: JVM descriptor already defined. Can not use argument [{0}] multiple times.", PARAM_VM_DESCRIPTOR); return false; } setProperty(props, arg, PARAM_VM_DESCRIPTOR, AGENT_ARG_VM); } else if (arg.startsWith(PARAM_AGENT_LIB_PATH)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_LIB_PATH))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: agent library path already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_LIB_PATH); return false; } setProperty(props, arg, PARAM_AGENT_LIB_PATH, AGENT_ARG_LIB_PATH); } else if (arg.startsWith(PARAM_AGENT_OPTIONS)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_OPTIONS))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: agent options already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_OPTIONS); return false; } setProperty(props, arg, PARAM_AGENT_OPTIONS, AGENT_ARG_OPTIONS); } else if (arg.startsWith(PARAM_AGENT_USER_LOGIN)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_USER))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: user login already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_USER_LOGIN); return false; } setProperty(props, arg, PARAM_AGENT_USER_LOGIN, AGENT_ARG_USER); } else if (arg.startsWith(PARAM_AGENT_USER_PASS)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_PASS))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: user password already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_USER_PASS); return false; } setProperty(props, arg, PARAM_AGENT_USER_PASS, AGENT_ARG_PASS); } else if (arg.startsWith(PARAM_AGENT_CONN_PARAM)) { String[] cp = parseCompositeArg(arg, PARAM_AGENT_CONN_PARAM); if (cp == null) { return false; } @SuppressWarnings("unchecked") Map<String, Object> connParams = (Map<String, Object>) props.get(AGENT_CONN_PARAMS); if (connParams == null) { connParams = new HashMap<String, Object>(5); props.put(AGENT_CONN_PARAMS, connParams); } connParams.put(cp[0], cp[1]); } else if (arg.startsWith(PARAM_AGENT_CONN_RETRY_INTERVAL)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_CONN_RETRY_INTERVAL))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: connection retry interval already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_CONN_RETRY_INTERVAL); return false; } setProperty(props, arg, PARAM_AGENT_CONN_RETRY_INTERVAL, AGENT_ARG_CONN_RETRY_INTERVAL); } else if (arg.startsWith(PARAM_AGENT_LISTENER_PARAM)) { String[] slp = parseCompositeArg(arg, PARAM_AGENT_LISTENER_PARAM); if (slp == null) { return false; } LISTENER_PROPERTIES.put(slp[0], slp[1]); } else if (arg.startsWith(PARAM_AGENT_SYSTEM_PROPERTY)) { String[] slp = parseCompositeArg(arg, PARAM_AGENT_SYSTEM_PROPERTY); if (slp == null) { return false; } System.setProperty(slp[0], slp[1]); } else if (arg.startsWith(PARAM_AGENT_CONNECTIONS_CONFIG_FILE)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_CONNS_CONFIG_FILE))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: JVM connections configuration file already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_CONNECTIONS_CONFIG_FILE); return false; } external = true; setProperty(props, arg, PARAM_AGENT_CONNECTIONS_CONFIG_FILE, AGENT_CONNS_CONFIG_FILE); } else { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: invalid argument [{0}]", arg); return false; } } } catch (IllegalArgumentException exc) { LOGGER.log(OpLevel.ERROR, "SamplingAgent.parseArgs: arguments parsing failed..."); LOGGER.log(OpLevel.ERROR, " Exception: {0}", Utils.getExceptionMessages(exc)); return false; } if (StringUtils.isEmpty(props.getProperty(AGENT_ARG_VM)) && ac && !external) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: missing mandatory argument [{0}] defining JVM descriptor.", PARAM_VM_DESCRIPTOR); return false; } // if (AGENT_MODE_ATTACH.equalsIgnoreCase(props.getProperty(AGENT_ARG_MODE)) // && StringUtils.isEmpty(props.getProperty(AGENT_ARG_LIB_PATH))) { // LOGGER.log(OpLevel.WARNING, // "SamplingAgent.parseArgs: missing mandatory argument [{0}] defining agent library path.", // PARAM_AGENT_LIB_PATH); // return false; // } } else { props.setProperty(AGENT_ARG_MODE, AGENT_MODE_AGENT); props.setProperty(AGENT_ARG_I_FILTER, args[0]); props.setProperty(AGENT_ARG_E_FILTER, args[1]); props.setProperty(AGENT_ARG_S_TIME, args[2]); if (args.length > 3) { props.setProperty(AGENT_ARG_W_TIME, args[3]); } if (args.length > 4) { props.setProperty(AGENT_ARG_D_TIME, args[4]); } } return true; } private static String[] parseCompositeArg(String arg, String argName) { String argValue = arg.substring(argName.length()); if (StringUtils.isEmpty(argValue)) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: missing argument [{0}] value", argName); return null; } String[] slp = argValue.split("=", 2); if (slp.length < 2) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: malformed argument [{0}] value [{1}]", argName, argValue); return null; } return slp; } private static void setProperty(Properties props, String arg, String argName, String agentArgName) throws IllegalArgumentException { String pValue = arg.substring(argName.length()); if (StringUtils.isEmpty(pValue)) { throw new IllegalArgumentException("Missing argument [" + argName + "] value"); } props.setProperty(agentArgName, pValue); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample() throws IOException { String incFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.include.filter", Sampler.JMX_FILTER_ALL); String excFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.exclude.filter", Sampler.JMX_FILTER_NONE); int period = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.period", Sampler.JMX_SAMPLE_PERIOD); int initDelay = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.init.delay", period); sample(incFilter, excFilter, initDelay, period); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @param incFilter * semicolon separated include filter list * @param period * sampling in milliseconds. * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, long period) throws IOException { sample(incFilter, null, period); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @param incFilter * semicolon separated include filter list * @param excFilter * semicolon separated exclude filter list (null if empty) * @param period * sampling in milliseconds. * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, String excFilter, long period) throws IOException { sample(incFilter, excFilter, period, period); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @param incFilter * semicolon separated include filter list * @param excFilter * semicolon separated exclude filter list (null if empty) * @param initDelay * initial delay before first sampling * @param period * sampling in milliseconds. * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, String excFilter, long initDelay, long period) throws IOException { sample(incFilter, excFilter, initDelay, period, TimeUnit.MILLISECONDS); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @param incFilter * semicolon separated include filter list * @param excFilter * semicolon separated exclude filter list (null if empty) * @param initDelay * initial delay before first sampling * @param period * sampling time * @param tUnit * time units for sampling period * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, String excFilter, long initDelay, long period, TimeUnit tUnit) throws IOException { resolveServer(null); SamplerFactory sFactory = initPlatformJMX(incFilter, excFilter, initDelay, period, tUnit, null); // find other registered MBean servers and initiate sampling for all ArrayList<MBeanServer> mbsList = MBeanServerFactory.findMBeanServer(null); for (MBeanServer server : mbsList) { Sampler jmxSampler = STREAM_AGENTS.get(server); if (jmxSampler == null) { jmxSampler = sFactory.newInstance(server); scheduleSampler(incFilter, excFilter, initDelay, period, tUnit, sFactory, jmxSampler, STREAM_AGENTS); } } } private Source getSource() { TrackerConfig config = DefaultConfigFactory.getInstance().getConfig(getClass().getName()); SourceFactory instance = config.getSourceFactory(); String sourceDescriptor = null; Thread thread = Thread.currentThread(); if (thread instanceof SamplingAgentThread) { sourceDescriptor = ((SamplingAgentThread) thread).getVMSourceFQN(); } if (sourceDescriptor == null) { return instance.getRootSource(); } Source source; try { source = instance.fromFQN(sourceDescriptor); } catch (IllegalArgumentException e) { // TODO placeholders doesn't fill right LOGGER.log(OpLevel.WARNING, "SamplingAgent.getSource: source descriptor ''{1}'' doesn't match FQN pattern 'SourceType=SourceValue'. Erroneous source type. Valid types ''{0}''. Cause: {2}", Arrays.toString(SourceType.values()), sourceDescriptor, e.getMessage()); throw new RuntimeException("Invalid Source configuration"); } catch (IndexOutOfBoundsException e) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.getSource: source descriptor ''{0}'' doesn't match FQN pattern 'SourceType=SourceValue'. Defaulting to ''SERVICE={0}''", sourceDescriptor); source = instance.newSource(sourceDescriptor, SourceType.SERVICE); } return source; } /** * Schedule sample using defined JMX connector to get MBean server connection instance to monitored JVM. * * @param incFilter * semicolon separated include filter list * @param excFilter * semicolon separated exclude filter list (null if empty) * @param initDelay * initial delay before first sampling * @param period * sampling time * @param tUnit * time units for sampling period * @param conn * JMX connector to get MBean server connection instance * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, String excFilter, long initDelay, long period, TimeUnit tUnit, JMXConnector conn) throws IOException { // get MBeanServerConnection from JMX RMI connector if (conn instanceof JMXAddressable) { JMXServiceURL url = ((JMXAddressable) conn).getAddress(); resolveServer(url == null ? null : url.getHost()); } MBeanServerConnection mbSrvConn = conn.getMBeanServerConnection(); initPlatformJMX(incFilter, excFilter, initDelay, period, tUnit, mbSrvConn); } private SamplerFactory initPlatformJMX(String incFilter, String excFilter, long initDelay, long period, TimeUnit tUnit, MBeanServerConnection mbSrvConn) throws IOException { // obtain a default sample factory SamplerFactory sFactory = DefaultSamplerFactory .getInstance(Utils.getConfProperty(DEFAULTS, "com.jkoolcloud.tnt4j.stream.jmx.sampler.factory")); if (platformJmx == null) { synchronized (STREAM_AGENTS) { // create new sampler with default MBeanServer instance platformJmx = mbSrvConn == null ? sFactory.newInstance() : sFactory.newInstance(mbSrvConn); // schedule sample with a given filter and sampling period scheduleSampler(incFilter, excFilter, initDelay, period, tUnit, sFactory, platformJmx, STREAM_AGENTS); } } return sFactory; } private void scheduleSampler(String incFilter, String excFilter, long initDelay, long period, TimeUnit tUnit, SamplerFactory sFactory, Sampler sampler, Map<MBeanServerConnection, Sampler> agents) throws IOException { agents.put(sampler.getMBeanServer(), sampler); sampler.setSchedule(incFilter, excFilter, initDelay, period, tUnit, sFactory, getSource()) .addListener(sFactory.newListener(LISTENER_PROPERTIES)).run(); } /** * Attaches to {@code vmDescr} defined JVM as agent. * * @param vmDescr * JVM descriptor: name fragment or pid * @param agentJarPath * agent JAR path * @param agentOptions * agent options * @throws Exception * if any exception occurs while attaching to JVM */ public static void attach(String vmDescr, String agentJarPath, String agentOptions) throws Exception { LOGGER.log(OpLevel.INFO, "SamplingAgent.attach(): vmDescr={0}, agentJarPath={1}, agentOptions={2}", vmDescr, agentJarPath, agentOptions); if (Utils.isEmpty(vmDescr)) { throw new RuntimeException("Java VM descriptor must be not empty!.."); } File pathFile; if (StringUtils.isEmpty(agentJarPath)) { LOGGER.log(OpLevel.INFO, "SamplingAgent.attach: no agent jar defined"); pathFile = getSAPath(); } else { pathFile = new File(agentJarPath); if (!pathFile.exists()) { LOGGER.log(OpLevel.INFO, "SamplingAgent.attach: non-existing argument defined agent jar: {0}", agentJarPath); LOGGER.log(OpLevel.INFO, " absolute agent jar path: {0}", pathFile.getAbsolutePath()); pathFile = getSAPath(); } } String agentPath = pathFile.getAbsolutePath(); for (Map.Entry<String, Object> lpe : LISTENER_PROPERTIES.entrySet()) { agentOptions += "!" + lpe.getKey() + "=" + String.valueOf(lpe.getValue()); } agentOptions += "!" + SYS_PROP_AGENT_PATH + "=" + agentPath; String tnt4jConf = System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY); if (!Utils.isEmpty(tnt4jConf)) { String tnt4jPropPath = new File(tnt4jConf).getAbsolutePath(); agentOptions += "!" + SYS_PROP_TNT4J_CFG + "=" + tnt4jPropPath; } String log4jConf = System.getProperty(LOG4J_PROPERTIES_KEY); if (!Utils.isEmpty(log4jConf)) { String log4jPropPath = new File(log4jConf).getAbsolutePath(); agentOptions += "!" + SYS_PROP_LOG4J_CFG + "=" + log4jPropPath; } LOGGER.log(OpLevel.INFO, "SamplingAgent.attach: attaching JVM using vmDescr={0}, agentJarPath={1}, agentOptions={2}", vmDescr, agentJarPath, agentOptions); VMUtils.attachVM(vmDescr, agentPath, agentOptions); } private static File getSAPath() throws URISyntaxException { String saPath = SamplingAgent.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); LOGGER.log(OpLevel.INFO, "SamplingAgent.attach: using SamplingAgent class referenced jar path: {0}", saPath); File agentFile = new File(saPath); if (!agentFile.exists()) { throw new RuntimeException("Could not find agent jar: " + agentFile.getAbsolutePath()); } return agentFile; } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String,String,long) */ public void connect(String vmDescr, String options) throws Exception { connect(vmDescr, options, CONN_RETRY_INTERVAL); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String,String,Map,long) */ public void connect(String vmDescr, String options, long connRetryInterval) throws Exception { connect(vmDescr, options, null, connRetryInterval); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connParams * map of JMX connection parameters, defined by {@link javax.naming.Context} * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String, String, java.util.Map, long) */ public void connect(String vmDescr, String options, Map<String, ?> connParams) throws Exception { connect(vmDescr, options, connParams, CONN_RETRY_INTERVAL); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connParams * map of JMX connection parameters, defined by {@link javax.naming.Context} * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String, String, String, String, java.util.Map, long) */ public void connect(String vmDescr, String options, Map<String, ?> connParams, long connRetryInterval) throws Exception { connect(vmDescr, null, null, options, connParams, connRetryInterval); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param user * user login used by JMX service connection * @param pass * user password used by JMX service connection * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String, String, String, String, long) */ public void connect(String vmDescr, String user, String pass, String options) throws Exception { connect(vmDescr, user, pass, options, CONN_RETRY_INTERVAL); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param user * user login used by JMX service connection * @param pass * user password used by JMX service connection * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String, String, String, String, java.util.Map, long) */ public void connect(String vmDescr, String user, String pass, String options, long connRetryInterval) throws Exception { connect(vmDescr, user, pass, options, null, connRetryInterval); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param user * user login used by JMX service connection * @param pass * user password used by JMX service connection * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connParams * map of JMX connection parameters, defined by {@link javax.naming.Context} * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(javax.management.remote.JMXServiceURL, String, String, String, java.util.Map, long) */ public void connect(String vmDescr, String user, String pass, String options, Map<String, ?> connParams, long connRetryInterval) throws Exception { connect(getJmxServiceURLs(vmDescr).get(0), user, pass, options, connParams, connRetryInterval); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param url * JMX service URL * @param user * user login used by JMX service connection * @param pass * user password used by JMX service connection * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connParams * map of JMX connection parameters, defined by {@link javax.naming.Context} * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see JMXConnectorFactory#connect(javax.management.remote.JMXServiceURL, java.util.Map) * @see javax.naming.Context */ public void connect(JMXServiceURL url, String user, String pass, String options, Map<String, ?> connParams, long connRetryInterval) throws Exception { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect(): url={0}, user={1}, pass={2}, options={3}, connParams={4}, connRetryInterval={5}", url, user, Utils.hideEnd(pass, "x", 0), options, connParams, connRetryInterval); if (url == null) { throw new RuntimeException("JMX service URL is null!.."); } Map<String, Object> params = new HashMap<String, Object>(connParams == null ? 1 : connParams.size() + 1); if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(pass)) { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect: adding user login and password to connection credentials..."); String[] credentials = new String[] { user, pass }; params.put(JMXConnector.CREDENTIALS, credentials); } if (connParams != null) { params.putAll(connParams); } do { try { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect: connecting JMX service using URL={0}", url); JMXConnector connector = JMXConnectorFactory.connect(url, params); try { NotificationListener cnl = new NotificationListener() { @Override public void handleNotification(Notification notification, Object key) { if (notification.getType().contains("closed") || notification.getType().contains("failed") || notification.getType().contains("lost")) { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect: JMX connection status change: {0}", notification.getType()); stopSampler(); } } }; connector.addConnectionNotificationListener(cnl, null, null); startSamplerAndWait(options, connector); shutdownSamplers(); connector.removeConnectionNotificationListener(cnl); } finally { Utils.close(connector); } } catch (IOException exc) { LOGGER.log(OpLevel.ERROR, "SamplingAgent.connect: failed to connect JMX service"); LOGGER.log(OpLevel.ERROR, " Exception: {0}", Utils.getExceptionMessages(exc)); if (connRetryInterval < 0) { stopSampling = true; } if (!stopSampling && connRetryInterval > 0) { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect: will retry connect attempt in {0} seconds...", connRetryInterval); Thread.sleep(TimeUnit.SECONDS.toMillis(connRetryInterval)); } } } while (!stopSampling); } private static List<JMXServiceURL> getJmxServiceURLs(String vmDescr) throws IOException { if (Utils.isEmpty(vmDescr)) { throw new RuntimeException("Java VM descriptor must be not empty!.."); } List<JMXServiceURL> returnList = new ArrayList<JMXServiceURL>(); if (vmDescr.startsWith("service:jmx:")) { returnList.add(new JMXServiceURL(vmDescr)); LOGGER.log(OpLevel.INFO, "SamplingAgent.getJmxServiceURLs: making JMX service URL from address={0}", vmDescr); } else { List<String> connAddresses = VMUtils.getVMConnAddresses(vmDescr); for (String connAddress : connAddresses) { returnList.add(new JMXServiceURL(connAddress)); LOGGER.log(OpLevel.INFO, "SamplingAgent.getJmxServiceURLs: making JVM ''{0}'' JMX service URL from address={1}", vmDescr, connAddress); } } return returnList; } protected void stopSampler() { LOGGER.log(OpLevel.INFO, "SamplingAgent.stopSampler: releasing sampler lock..."); if (platformJmx != null) { synchronized (platformJmx) { platformJmx.notifyAll(); } } } /** * Initiates MBeans attributes sampling on local process runner JVM. * * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param wait * flag indicating whether to wait for a runner process to complete * @throws Exception * if any exception occurs while initializing local JVM sampler or stopping sampling process */ public static void sampleLocalVM(String options, boolean wait) throws Exception { LOGGER.log(OpLevel.INFO, "SamplingAgent.sampleLocalVM(): options={0}, wait={1}", options, wait); SamplingAgent samplingAgent = newSamplingAgent(); if (wait) { samplingAgent.startSamplerAndWait(options); } else { samplingAgent.startSampler(options); } } private void startSamplerAndWait(String options) throws Exception { startSamplerAndWait(options, null); } private void startSamplerAndWait(String options, JMXConnector connector) throws Exception { startSampler(options, connector); final Thread mainThread = Thread.currentThread(); // Reference to the current thread. Thread shutdownHook = new Thread(new Runnable() { @Override public void run() { stopSampling = true; stopSampler(); long startTime = System.currentTimeMillis(); try { mainThread.join(TimeUnit.SECONDS.toMillis(2)); } catch (Exception exc) { } LOGGER.log(OpLevel.INFO, "SamplingAgent.startSamplerAndWait: waited {0}ms. on Stream-JMX to complete...", (System.currentTimeMillis() - startTime)); } }); Runtime.getRuntime().addShutdownHook(shutdownHook); LOGGER.log(OpLevel.INFO, "SamplingAgent.startSamplerAndWait: locking on sampler: {0}...", platformJmx); if (platformJmx != null) { synchronized (platformJmx) { platformJmx.wait(); } } LOGGER.log(OpLevel.INFO, "SamplingAgent.startSamplerAndWait: stopping Stream-JMX..."); try { Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (IllegalStateException exc) { } } private void startSampler(String options) throws Exception { startSampler(options, null); } private void startSampler(String options, JMXConnector connector) throws Exception { String incFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.include.filter", Sampler.JMX_FILTER_ALL); String excFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.exclude.filter", Sampler.JMX_FILTER_NONE); int period = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.period", Sampler.JMX_SAMPLE_PERIOD); int initDelay = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.init.delay", period); if (options != null) { String[] args = options.split("!"); if (args.length > 0) { incFilter = args[0]; } if (args.length > 1) { excFilter = args.length > 2 ? args[1] : Sampler.JMX_FILTER_NONE; period = Integer.parseInt(args.length > 2 ? args[2] : args[1]); } if (args.length > 2) { initDelay = Integer.parseInt(args.length > 3 ? args[3] : args[2]); } } if (connector == null) { sample(incFilter, excFilter, initDelay, period, TimeUnit.MILLISECONDS); } else { sample(incFilter, excFilter, initDelay, period, TimeUnit.MILLISECONDS, connector); } LOGGER.log(OpLevel.INFO, "SamplingAgent.startSampler: include.filter={0}, exclude.filter={1}, sample.ms={2}, initDelay.ms={3}, listener.properties={4}, tnt4j.config={5}, jmx.sample.list={6}", incFilter, excFilter, period, initDelay, LISTENER_PROPERTIES, System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY), STREAM_AGENTS); } /** * Obtain a map of all scheduled MBeanServerConnections and associated sample references. * * @return map of all scheduled MBeanServerConnections and associated sample references. */ public Map<MBeanServerConnection, Sampler> getSamplers() { HashMap<MBeanServerConnection, Sampler> copy = new HashMap<MBeanServerConnection, Sampler>(89); copy.putAll(STREAM_AGENTS); return copy; } /** * Cancel and close all outstanding {@link Sampler} instances and stop all sampling for all {@link MBeanServer} * instances. */ public void cancel() { for (Sampler sampler : STREAM_AGENTS.values()) { sampler.cancel(); } STREAM_AGENTS.clear(); } /** * Cancel and close all sampling for a given {@link MBeanServer} instance. * * @param mServerConn * MBeanServerConnection instance */ public void cancel(MBeanServerConnection mServerConn) { Sampler sampler = STREAM_AGENTS.remove(mServerConn); if (sampler != null) { sampler.cancel(); } } /** * Stops platform JMX sampler, cancels and close all outstanding {@link Sampler} instances and stop all sampling for * all {@link MBeanServer} instances. * * @see #cancel() */ public static void destroy() { for (SamplingAgent agent : agents.values()) { synchronized (agent.STREAM_AGENTS) { agent.stopSampler(); agent.shutdownSamplers(); } } DefaultEventSinkFactory.shutdownAll(); } private void shutdownSamplers() { cancel(); platformJmx = null; } private static void initDefaults(Properties defProps) { Map<String, Properties> defPropsMap = new HashMap<String, Properties>(); String dPropsKey = null; int apiLevel = 0; try { Properties p = Utils.loadPropertiesResources("sjmx-defaults.properties"); String key; String pKey; for (Map.Entry<?, ?> pe : p.entrySet()) { pKey = (String) pe.getKey(); int di = pKey.indexOf("/"); if (di >= 0) { key = pKey.substring(0, di); pKey = pKey.substring(di + 1); } else { key = ""; } if ("api.level".equals(pKey)) { int peApiLevel = 0; try { peApiLevel = Integer.parseInt((String) pe.getValue()); } catch (NumberFormatException exc) { } if (peApiLevel > apiLevel) { apiLevel = peApiLevel; dPropsKey = key; } continue; } Properties dpe = defPropsMap.get(key); if (dpe == null) { dpe = new Properties(); defPropsMap.put(key, dpe); } dpe.setProperty(pKey, (String) pe.getValue()); } } catch (Exception exc) { } if (dPropsKey != null) { defProps.putAll(defPropsMap.get(dPropsKey)); } } private static void copyProperty(DefaultSampleListener.ListenerProperties lProp, Map<?, ?> sProperties, Map<String, Object> tProperties) { Utils.copyProperty(lProp.apName(), sProperties, lProp.pName(), tProperties); } private static void copyProperty(DefaultSampleListener.ListenerProperties lProp, Map<?, ?> sProperties, Map<String, Object> tProperties, Object defValue) { Utils.copyProperty(lProp.apName(), sProperties, lProp.pName(), tProperties, defValue); } private static class JarFilter implements FilenameFilter { JarFilter() { } @Override public boolean accept(File dir, String name) { String nfn = name.toLowerCase(); return nfn.endsWith(".jar") || nfn.endsWith(".zip"); } } }
tnt4j-stream-jmx-core/src/main/java/com/jkoolcloud/tnt4j/stream/jmx/SamplingAgent.java
/* * Copyright 2015-2018 JKOOL, LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jkoolcloud.tnt4j.stream.jmx; import static com.jkoolcloud.tnt4j.stream.jmx.core.DefaultSampleListener.ListenerProperties.*; import java.io.*; import java.lang.instrument.Instrumentation; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import javax.management.*; import javax.management.remote.JMXAddressable; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import org.apache.commons.lang3.StringUtils; import com.jkoolcloud.tnt4j.config.DefaultConfigFactory; import com.jkoolcloud.tnt4j.config.TrackerConfig; import com.jkoolcloud.tnt4j.config.TrackerConfigStore; import com.jkoolcloud.tnt4j.core.OpLevel; import com.jkoolcloud.tnt4j.sink.DefaultEventSinkFactory; import com.jkoolcloud.tnt4j.sink.EventSink; import com.jkoolcloud.tnt4j.source.Source; import com.jkoolcloud.tnt4j.source.SourceFactory; import com.jkoolcloud.tnt4j.source.SourceFactoryImpl; import com.jkoolcloud.tnt4j.source.SourceType; import com.jkoolcloud.tnt4j.stream.jmx.core.DefaultSampleListener; import com.jkoolcloud.tnt4j.stream.jmx.core.PropertyNameBuilder; import com.jkoolcloud.tnt4j.stream.jmx.core.Sampler; import com.jkoolcloud.tnt4j.stream.jmx.factory.DefaultSamplerFactory; import com.jkoolcloud.tnt4j.stream.jmx.factory.SamplerFactory; import com.jkoolcloud.tnt4j.stream.jmx.utils.Utils; import com.jkoolcloud.tnt4j.stream.jmx.utils.VMUtils; /** * <p> * This class provides java agent implementation {@link #premain(String, Instrumentation)}, * {@link #agentmain(String, Instrumentation)} as well as {@link #main(String[])} entry point to run as a standalone * application. * </p> * * @version $Revision: 1 $ * * @see SamplerFactory */ public class SamplingAgent { private static final EventSink LOGGER = DefaultEventSinkFactory.defaultEventSink(SamplingAgent.class); public static final String SOURCE_SERVER_ADDRESS = "sjmx.serverAddress"; public static final String SOURCE_SERVER_NAME = "sjmx.serverName"; public static final String SOURCE_SERVICE_ID = "sjmx.serviceId"; protected Sampler platformJmx; protected ConcurrentHashMap<MBeanServerConnection, Sampler> STREAM_AGENTS = new ConcurrentHashMap<MBeanServerConnection, Sampler>( 89); private static Map<Thread, SamplingAgent> agents = new HashMap<Thread, SamplingAgent>(); protected static final long CONN_RETRY_INTERVAL = 10; private static final String LOG4J_PROPERTIES_KEY = "log4j.configuration"; private static final String SYS_PROP_LOG4J_CFG = "-D" + LOG4J_PROPERTIES_KEY; private static final String SYS_PROP_TNT4J_CFG = "-D" + TrackerConfigStore.TNT4J_PROPERTIES_KEY; private static final String SYS_PROP_AGENT_PATH = "-DSamplingAgent.path"; private static final String PARAM_VM_DESCRIPTOR = "-vm:"; private static final String PARAM_AGENT_LIB_PATH = "-ap:"; private static final String PARAM_AGENT_OPTIONS = "-ao:"; private static final String PARAM_AGENT_USER_LOGIN = "-ul:"; private static final String PARAM_AGENT_USER_PASS = "-up:"; private static final String PARAM_AGENT_CONN_PARAM = "-cp:"; private static final String PARAM_AGENT_CONN_RETRY_INTERVAL = "-cri:"; private static final String PARAM_AGENT_LISTENER_PARAM = "-slp:"; private static final String PARAM_AGENT_SYSTEM_PROPERTY = "-sp:"; private static final String PARAM_AGENT_CONNECTIONS_CONFIG_FILE = "-f:"; private static final String AGENT_MODE_AGENT = "-agent"; private static final String AGENT_MODE_ATTACH = "-attach"; private static final String AGENT_MODE_CONNECT = "-connect"; private static final String AGENT_MODE_LOCAL = "-local"; private static final String AGENT_ARG_MODE = "agent.mode"; private static final String AGENT_ARG_VM = "vm.descriptor"; private static final String AGENT_ARG_USER = "user.login"; private static final String AGENT_ARG_PASS = "user.password"; private static final String AGENT_ARG_CONN_RETRY_INTERVAL = "conn.retry.interval"; private static final String AGENT_ARG_LIB_PATH = "agent.lib.path"; private static final String AGENT_ARG_OPTIONS = "agent.options"; private static final String AGENT_ARG_I_FILTER = "beans.include.filter"; private static final String AGENT_ARG_E_FILTER = "beans.exclude.filter"; private static final String AGENT_ARG_S_TIME = "agent.sample.time"; private static final String AGENT_ARG_D_TIME = "agent.sample.delay.time"; private static final String AGENT_ARG_W_TIME = "agent.wait.time"; private static final String AGENT_CONN_PARAMS = "agent.connection.params"; private static final String AGENT_CONNS_CONFIG_FILE = "agent.connections.config.file"; private static final String DEFAULT_AGENT_OPTIONS = Sampler.JMX_FILTER_ALL + "!" + Sampler.JMX_FILTER_NONE + "!" + Sampler.JMX_SAMPLE_PERIOD; public static final Properties DEFAULTS = new Properties(); public static final Map<String, Object> LISTENER_PROPERTIES = new HashMap<String, Object>(5); static { initDefaults(DEFAULTS); copyProperty(FORCE_OBJECT_NAME, DEFAULTS, LISTENER_PROPERTIES, false); copyProperty(COMPOSITE_DELIMITER, DEFAULTS, LISTENER_PROPERTIES, PropertyNameBuilder.DEFAULT_COMPOSITE_DELIMITER); copyProperty(USE_OBJECT_NAME_PROPERTIES, DEFAULTS, LISTENER_PROPERTIES, true); copyProperty(FORCE_OBJECT_NAME, System.getProperties(), LISTENER_PROPERTIES); copyProperty(COMPOSITE_DELIMITER, System.getProperties(), LISTENER_PROPERTIES); copyProperty(USE_OBJECT_NAME_PROPERTIES, System.getProperties(), LISTENER_PROPERTIES); } private boolean stopSampling = false; private SamplingAgent() { } public static SamplingAgent newSamplingAgent() { SamplingAgent agent = new SamplingAgent(); agents.put(Thread.currentThread(), agent); return agent; } /** * Entry point to be loaded as {@code -javaagent:jarpath="mbean-filter!sample.ms!initDelay.ms"} command line where * {@code initDelay} is optional. Example: {@code -javaagent:tnt4j-sample-jmx.jar="*:*!30000!1000"} * * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param inst * instrumentation handle * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public static void premain(String options, Instrumentation inst) throws IOException { String incFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.include.filter", Sampler.JMX_FILTER_ALL); String excFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.exclude.filter", Sampler.JMX_FILTER_NONE); int period = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.period", Sampler.JMX_SAMPLE_PERIOD); int initDelay = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.init.delay", period); if (options != null) { String[] args = options.split("!"); if (args.length > 0) { incFilter = args[0]; } if (args.length > 1) { excFilter = args.length > 2 ? args[1] : excFilter; period = Integer.parseInt(args.length > 2 ? args[2] : args[1]); } if (args.length > 2) { initDelay = Integer.parseInt(args.length > 3 ? args[3] : args[2]); } } SamplingAgent agent = newSamplingAgent(); agent.sample(incFilter, excFilter, initDelay, period, TimeUnit.MILLISECONDS); LOGGER.log(OpLevel.INFO, "SamplingAgent.premain: include.filter={0}, exclude.filter={1}, sample.ms={2}, initDelay.ms={3}, listener.properties={4}, tnt4j.config={5}, jmx.sample.list={6}", incFilter, excFilter, period, initDelay, LISTENER_PROPERTIES, System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY), agent.STREAM_AGENTS); } /** * Entry point to be loaded as JVM agent. Does same as {@link #premain(String, Instrumentation)}. * * @param agentArgs * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param inst * instrumentation handle * @throws IOException * if any I/O exception occurs while starting agent * * @see #premain(String, Instrumentation) */ public static void agentmain(String agentArgs, Instrumentation inst) throws Exception { LOGGER.log(OpLevel.INFO, "SamplingAgent.agentmain(): agentArgs={0}", agentArgs); String agentParams = ""; String tnt4jProp = System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY); String log4jProp = System.getProperty(LOG4J_PROPERTIES_KEY); String agentLibPath = ""; if (!Utils.isEmpty(agentArgs)) { String[] args = agentArgs.split("!"); for (String arg : args) { if (arg.startsWith(SYS_PROP_TNT4J_CFG)) { if (Utils.isEmpty(tnt4jProp)) { String[] prop = arg.split("=", 2); tnt4jProp = prop.length > 1 ? prop[1] : null; System.setProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY, tnt4jProp); } } else if (arg.startsWith(SYS_PROP_AGENT_PATH)) { String[] prop = arg.split("=", 2); agentLibPath = prop.length > 1 ? prop[1] : null; } if (arg.startsWith(SYS_PROP_LOG4J_CFG)) { if (Utils.isEmpty(log4jProp)) { String[] prop = arg.split("=", 2); log4jProp = prop.length > 1 ? prop[1] : null; System.setProperty(LOG4J_PROPERTIES_KEY, log4jProp); } } else if (arg.startsWith(FORCE_OBJECT_NAME.pName() + "=")) { String[] prop = arg.split("=", 2); if (prop.length > 1) { LISTENER_PROPERTIES.put(FORCE_OBJECT_NAME.pName(), prop[1]); } } else if (arg.startsWith(COMPOSITE_DELIMITER.pName() + "=")) { String[] prop = arg.split("=", 2); if (prop.length > 1) { LISTENER_PROPERTIES.put(COMPOSITE_DELIMITER.pName(), prop[1]); } } else if (arg.startsWith(USE_OBJECT_NAME_PROPERTIES.pName() + "=")) { String[] prop = arg.split("=", 2); if (prop.length > 1) { LISTENER_PROPERTIES.put(USE_OBJECT_NAME_PROPERTIES.pName(), prop[1]); } } else { agentParams += agentParams.isEmpty() ? arg : "!" + arg; } } } LOGGER.log(OpLevel.INFO, "SamplingAgent.agentmain: agent.params={0}, agent.lib.path={1}, listener.properties={2}, tnt4j.config={3}", agentParams, agentLibPath, LISTENER_PROPERTIES, System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY)); File agentPath = new File(agentLibPath); String[] classPathEntries = agentPath.list(new JarFilter()); if (classPathEntries != null) { File pathFile; for (String classPathEntry : classPathEntries) { pathFile = new File(classPathEntry); LOGGER.log(OpLevel.INFO, "SamplingAgent.agentmain: extending classpath with: {0}", pathFile.getAbsolutePath()); extendClasspath(pathFile.toURI().toURL()); } } premain(agentParams, inst); } /** * Loads required classpath entries to running JVM. * * @param classPathEntriesURL * classpath entries URLs to attach to JVM * @throws Exception * if exception occurs while extending system class loader's classpath */ private static void extendClasspath(URL... classPathEntriesURL) throws Exception { URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); for (URL classPathEntryURL : classPathEntriesURL) { try { method.invoke(classLoader, classPathEntryURL); } catch (Exception e) { LOGGER.log(OpLevel.ERROR, "SamplingAgent.extendClasspath: could not load lib {0}", classPathEntryURL); LOGGER.log(OpLevel.ERROR, " Exception: {0}", Utils.getExceptionMessages(e)); } } } /** * Main entry point for running as a standalone application (test only). * * @param args * argument list: [sampling-mode vm-descriptor] [mbean-filter sample_time_ms] * * @throws Exception * if exception occurs while initializing MBeans sampling */ public static void main(String[] args) throws Exception { Properties props = new Properties(); boolean argsValid = parseArgs(props, args); if (argsValid) { SamplerFactory sFactory = DefaultSamplerFactory .getInstance(Utils.getConfProperty(DEFAULTS, "com.jkoolcloud.tnt4j.stream.jmx.sampler.factory")); sFactory.initialize(); String am = props.getProperty(AGENT_ARG_MODE); if (AGENT_MODE_CONNECT.equalsIgnoreCase(am)) { String fileName = props.getProperty(AGENT_CONNS_CONFIG_FILE); if (StringUtils.isEmpty(fileName)) { List<ConnectionParams> allVMs = getAllVMs(props); connectAll(allVMs, props); } else { List<ConnectionParams> allVMs = getConnectionParamsFromFile(fileName); if (allVMs == null || allVMs.isEmpty()) { LOGGER.log(OpLevel.CRITICAL, "No JVM connections loaded from configuration file ''{0}''", fileName); } else { connectAll(allVMs, props); } } } else if (AGENT_MODE_ATTACH.equalsIgnoreCase(am)) { String vmDescr = props.getProperty(AGENT_ARG_VM); String jarPath = props.getProperty(AGENT_ARG_LIB_PATH); String agentOptions = props.getProperty(AGENT_ARG_OPTIONS, DEFAULT_AGENT_OPTIONS); attach(vmDescr, jarPath, agentOptions); } else if (AGENT_MODE_LOCAL.equalsIgnoreCase(am)) { String agentOptions = props.getProperty(AGENT_ARG_OPTIONS, DEFAULT_AGENT_OPTIONS); sampleLocalVM(agentOptions, true); } else { try { String inclF = props.getProperty(AGENT_ARG_I_FILTER, Sampler.JMX_FILTER_ALL); String exclF = props.getProperty(AGENT_ARG_E_FILTER, Sampler.JMX_FILTER_NONE); long sample_time = Integer .parseInt(props.getProperty(AGENT_ARG_S_TIME, String.valueOf(Sampler.JMX_SAMPLE_PERIOD))); long delay_time = Integer .parseInt(props.getProperty(AGENT_ARG_D_TIME, String.valueOf(sample_time))); long wait_time = Integer.parseInt(props.getProperty(AGENT_ARG_W_TIME, "0")); SamplingAgent samplingAgent = newSamplingAgent(); samplingAgent.sample(inclF, exclF, delay_time, sample_time, TimeUnit.MILLISECONDS, null); LOGGER.log(OpLevel.INFO, "SamplingAgent.main: include.filter={0}, exclude.filter={1}, sample.ms={2}, delay.ms={3}, wait.ms={4}, listener.properties={5}, tnt4j.config={6}, jmx.sample.list={7}", inclF, exclF, sample_time, delay_time, wait_time, LISTENER_PROPERTIES, System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY), samplingAgent.STREAM_AGENTS); synchronized (samplingAgent.platformJmx) { samplingAgent.platformJmx.wait(wait_time); } } catch (Throwable ex) { LOGGER.log(OpLevel.ERROR, "SamplingAgent.main: failed to configure and run JMX sampling..."); LOGGER.log(OpLevel.ERROR, " Exception: {0}", Utils.getExceptionMessages(ex)); } } } else { LOGGER.log(OpLevel.INFO, "Printing usage instructions before exit!.."); String usageStr = "Usage: mbean-filter exclude-filter sample-ms [wait-ms] (e.g \"*:*\" \"\" 10000 60000)\n" + " or: -attach -vm:vmName/vmId -ap:agentJarPath -ao:agentOptions (e.g -attach -vm:activemq -ap:[ENV_PATH]/tnt-stream-jmx.jar -ao:*:*!!10000)\n" + " or: -connect -vm:vmName/vmId/JMX_URL -ao:agentOptions (e.g -connect -vm:activemq -ao:*:*!!10000\n" + " or: -connect -vm:vmName/vmId/JMX_URL -cri:connRetryIntervalSec -ao:agentOptions (e.g -connect -vm:activemq -cri:30 -ao:*:*!!10000\n" + " or: -connect -vm:vmName/vmId/JMX_URL -ul:userLogin -up:userPassword -ao:agentOptions (e.g -connect -vm:activemq -ul:admin -up:admin -ao:*:*!!10000\n" + " or: -connect -vm:vmName/vmId/JMX_URL -ul:userLogin -up:userPassword -ao:agentOptions -cp:jmcConnParam1 -cp:jmcConnParam2 -cp:... (e.g -connect -vm:activemq -ul:admin -up:admin -ao:*:*!!10000 -cp:javax.net.ssl.trustStorePassword=trustPass\n" + " or: -local -ao:agentOptions (e.g -local -ao:*:*!!10000\n" + " \n" + "Arguments definition: \n" + " -vm: - virtual machine descriptor. It can be PID or JVM process name fragment.\n" + " -ao: - agent options string using '!' symbol as delimiter. Options format: mbean-filter!exclude-filter!sample-ms!init-delay-ms\n" + " mbean-filter - MBean include name filter defined using object name pattern: domainName:keysSet\n" + " exclude-filter - MBean exclude name filter defined using object name pattern: domainName:keysSet\n" + " sample-ms - MBeans sampling rate in milliseconds\n" + " init-delay-ms - MBeans sampling initial delay in milliseconds. Optional, by default it is equal to 'sample-ms' value.\n" + " -cp: - JMX connection parameter string using '=' symbol as delimiter. Defines only one parameter, to define more than one use this argument multiple times. Argument format: -cp:key=value\n" + " see https://docs.oracle.com/javase/7/docs/technotes/guides/management/agent.html for more details\n" + " -slp: - sampler parameter string using '=' symbol as delimiter. Defines only one parameter, to define more than one use this argument multiple times. Argument format: -slp:key=value\n" + " trace - flag indicating whether the sample listener should print trace entries to print stream. Default value - 'false'\n" + " forceObjectName - flag indicating to forcibly add 'objectName' attribute if such is not present for a MBean. Default value - 'false'\n" + " compositeDelimiter - delimiter used to tokenize composite/tabular type MBean properties keys. Default value - '\\'\n" + " useObjectNameProperties - flag indicating to copy MBean ObjectName contained properties into sample snapshot properties. Default value - 'true'\n" + " -sp: - sampler system property string using '=' symbol as delimiter. Defines only one system property, to define more than one use this argument multiple times. Argument format: -sp:key=value"; System.out.println(usageStr); System.exit(1); } } private static List<ConnectionParams> getConnectionParamsFromFile(String fileName) throws IOException { File file = new File(fileName); if (!file.exists()) { LOGGER.log(OpLevel.CRITICAL, "JVM connections configuration file does not exist: {0}", fileName); return null; } LineNumberReader reader = new LineNumberReader(new FileReader(file)); String line; String ao = null; String user = null; String pass = null; String sourceDescriptor = getSingleSourceDescriptor(); List<ConnectionParams> allVMs = new ArrayList<ConnectionParams>(); while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("#") || line.isEmpty()) { continue; } String[] split = line.split("\\s+"); // vm if (!(split.length == 5 || split.length == 1)) { LOGGER.log(OpLevel.WARNING, "JVM connections configuration file line {0} has invalid syntax: {1}", reader.getLineNumber(), line); continue; } String vm = split[0]; ao = split.length > 1 ? split[1] : ao; user = split.length > 2 ? split[2] : user; pass = split.length > 3 ? split[3] : pass; sourceDescriptor = split.length > 4 ? split[4] : sourceDescriptor; ConnectionParams connectionParams = new ConnectionParams(getJmxServiceURLs(vm).get(0), user, pass, ao, sourceDescriptor); allVMs.add(connectionParams); } return allVMs; } private static void connectAll(List<ConnectionParams> allVMs, Properties props) throws Exception { @SuppressWarnings("unchecked") final Map<String, ?> connParams = (Map<String, ?>) props.get(AGENT_CONN_PARAMS); final long cri = Long .parseLong(props.getProperty(AGENT_ARG_CONN_RETRY_INTERVAL, String.valueOf(CONN_RETRY_INTERVAL))); for (final ConnectionParams cp : allVMs) { final SamplingAgent samplingAgent = SamplingAgent.newSamplingAgent(); Thread connect = new SamplingAgentThread(new Runnable() { @Override public void run() { try { samplingAgent.connect(cp.serviceURL, cp.user, cp.pass, cp.agentOptions, connParams, cri); samplingAgent.stopSampler(); } catch (Exception ex) { throw new RuntimeException(ex); } } }, samplingAgent, cp.additionalSourceFQN); connect.start(); } } private static List<ConnectionParams> getAllVMs(Properties props) throws IOException { String vmDescr = props.getProperty(AGENT_ARG_VM); String user = props.getProperty(AGENT_ARG_USER) == null ? null : props.getProperty(AGENT_ARG_USER); String pass = props.getProperty(AGENT_ARG_PASS) == null ? null : props.getProperty(AGENT_ARG_PASS); String agentOptions = props.getProperty(AGENT_ARG_OPTIONS, DEFAULT_AGENT_OPTIONS); String sourcesDescriptor = getSingleSourceDescriptor(); List<ConnectionParams> connectionParamsList = new ArrayList<ConnectionParams>(); List<JMXServiceURL> jmxServiceURLs = getJmxServiceURLs(vmDescr); for (JMXServiceURL jmxServiceURL : jmxServiceURLs) { connectionParamsList.add(new ConnectionParams(jmxServiceURL, user, pass, agentOptions, sourcesDescriptor)); } return connectionParamsList; } private static String getSingleSourceDescriptor() { return System.getProperty(SOURCE_SERVICE_ID, SourceFactoryImpl.UNKNOWN_SOURCE); } public static Map<MBeanServerConnection, Sampler> getAllSamplers() { Map<MBeanServerConnection, Sampler> samplers = new HashMap<MBeanServerConnection, Sampler>(); for (SamplingAgent agent : agents.values()) { if (agent != null) { samplers.putAll(agent.getSamplers()); } } return samplers; } static class ConnectionParams { JMXServiceURL serviceURL; String user; String pass; String agentOptions; String additionalSourceFQN; public ConnectionParams(JMXServiceURL serviceURL, String user, String pass, String agentOptions, String additionalSourceFQN) throws IOException { this.serviceURL = serviceURL; this.user = user; this.pass = pass; this.agentOptions = agentOptions; this.additionalSourceFQN = additionalSourceFQN; } } private static void resolveServer(String host) { String serverAddress; String serverName; if (StringUtils.isEmpty(host)) { serverAddress = Utils.getLocalHostAddress(); serverName = Utils.getLocalHostName(); } else { serverAddress = Utils.resolveHostNameToAddress(host); serverName = Utils.resolveAddressToHostName(host); } System.setProperty(SOURCE_SERVER_ADDRESS, serverAddress); System.setProperty(SOURCE_SERVER_NAME, serverName); } private static boolean parseArgs(Properties props, String... args) { LOGGER.log(OpLevel.INFO, "SamplingAgent.parseArgs(): args={0}", Arrays.toString(args)); boolean ac = StringUtils.equalsAnyIgnoreCase(args[0], AGENT_MODE_ATTACH, AGENT_MODE_CONNECT); boolean local = AGENT_MODE_LOCAL.equalsIgnoreCase(args[0]); boolean external = false; if (ac || local) { props.setProperty(AGENT_ARG_MODE, args[0]); try { for (int ai = 1; ai < args.length; ai++) { String arg = args[ai]; if (StringUtils.isEmpty(arg)) { continue; } if (arg.startsWith(PARAM_VM_DESCRIPTOR)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_VM))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: JVM descriptor already defined. Can not use argument [{0}] multiple times.", PARAM_VM_DESCRIPTOR); return false; } setProperty(props, arg, PARAM_VM_DESCRIPTOR, AGENT_ARG_VM); } else if (arg.startsWith(PARAM_AGENT_LIB_PATH)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_LIB_PATH))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: agent library path already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_LIB_PATH); return false; } setProperty(props, arg, PARAM_AGENT_LIB_PATH, AGENT_ARG_LIB_PATH); } else if (arg.startsWith(PARAM_AGENT_OPTIONS)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_OPTIONS))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: agent options already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_OPTIONS); return false; } setProperty(props, arg, PARAM_AGENT_OPTIONS, AGENT_ARG_OPTIONS); } else if (arg.startsWith(PARAM_AGENT_USER_LOGIN)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_USER))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: user login already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_USER_LOGIN); return false; } setProperty(props, arg, PARAM_AGENT_USER_LOGIN, AGENT_ARG_USER); } else if (arg.startsWith(PARAM_AGENT_USER_PASS)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_PASS))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: user password already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_USER_PASS); return false; } setProperty(props, arg, PARAM_AGENT_USER_PASS, AGENT_ARG_PASS); } else if (arg.startsWith(PARAM_AGENT_CONN_PARAM)) { String[] cp = parseCompositeArg(arg, PARAM_AGENT_CONN_PARAM); if (cp == null) { return false; } @SuppressWarnings("unchecked") Map<String, Object> connParams = (Map<String, Object>) props.get(AGENT_CONN_PARAMS); if (connParams == null) { connParams = new HashMap<String, Object>(5); props.put(AGENT_CONN_PARAMS, connParams); } connParams.put(cp[0], cp[1]); } else if (arg.startsWith(PARAM_AGENT_CONN_RETRY_INTERVAL)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_ARG_CONN_RETRY_INTERVAL))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: connection retry interval already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_CONN_RETRY_INTERVAL); return false; } setProperty(props, arg, PARAM_AGENT_CONN_RETRY_INTERVAL, AGENT_ARG_CONN_RETRY_INTERVAL); } else if (arg.startsWith(PARAM_AGENT_LISTENER_PARAM)) { String[] slp = parseCompositeArg(arg, PARAM_AGENT_LISTENER_PARAM); if (slp == null) { return false; } LISTENER_PROPERTIES.put(slp[0], slp[1]); } else if (arg.startsWith(PARAM_AGENT_SYSTEM_PROPERTY)) { String[] slp = parseCompositeArg(arg, PARAM_AGENT_SYSTEM_PROPERTY); if (slp == null) { return false; } System.setProperty(slp[0], slp[1]); } else if (arg.startsWith(PARAM_AGENT_CONNECTIONS_CONFIG_FILE)) { if (StringUtils.isNotEmpty(props.getProperty(AGENT_CONNS_CONFIG_FILE))) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: JVM connections configuration file already defined. Can not use argument [{0}] multiple times.", PARAM_AGENT_CONNECTIONS_CONFIG_FILE); return false; } external = true; setProperty(props, arg, PARAM_AGENT_CONNECTIONS_CONFIG_FILE, AGENT_CONNS_CONFIG_FILE); } else { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: invalid argument [{0}]", arg); return false; } } } catch (IllegalArgumentException exc) { LOGGER.log(OpLevel.ERROR, "SamplingAgent.parseArgs: arguments parsing failed..."); LOGGER.log(OpLevel.ERROR, " Exception: {0}", Utils.getExceptionMessages(exc)); return false; } if (StringUtils.isEmpty(props.getProperty(AGENT_ARG_VM)) && ac && !external) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: missing mandatory argument [{0}] defining JVM descriptor.", PARAM_VM_DESCRIPTOR); return false; } // if (AGENT_MODE_ATTACH.equalsIgnoreCase(props.getProperty(AGENT_ARG_MODE)) // && StringUtils.isEmpty(props.getProperty(AGENT_ARG_LIB_PATH))) { // LOGGER.log(OpLevel.WARNING, // "SamplingAgent.parseArgs: missing mandatory argument [{0}] defining agent library path.", // PARAM_AGENT_LIB_PATH); // return false; // } } else { props.setProperty(AGENT_ARG_MODE, AGENT_MODE_AGENT); props.setProperty(AGENT_ARG_I_FILTER, args[0]); props.setProperty(AGENT_ARG_E_FILTER, args[1]); props.setProperty(AGENT_ARG_S_TIME, args[2]); if (args.length > 3) { props.setProperty(AGENT_ARG_W_TIME, args[3]); } if (args.length > 4) { props.setProperty(AGENT_ARG_D_TIME, args[4]); } } return true; } private static String[] parseCompositeArg(String arg, String argName) { String argValue = arg.substring(argName.length()); if (StringUtils.isEmpty(argValue)) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: missing argument [{0}] value", argName); return null; } String[] slp = argValue.split("=", 2); if (slp.length < 2) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.parseArgs: malformed argument [{0}] value [{1}]", argName, argValue); return null; } return slp; } private static void setProperty(Properties props, String arg, String argName, String agentArgName) throws IllegalArgumentException { String pValue = arg.substring(argName.length()); if (StringUtils.isEmpty(pValue)) { throw new IllegalArgumentException("Missing argument [" + argName + "] value"); } props.setProperty(agentArgName, pValue); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample() throws IOException { String incFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.include.filter", Sampler.JMX_FILTER_ALL); String excFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.exclude.filter", Sampler.JMX_FILTER_NONE); int period = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.period", Sampler.JMX_SAMPLE_PERIOD); int initDelay = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.init.delay", period); sample(incFilter, excFilter, initDelay, period); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @param incFilter * semicolon separated include filter list * @param period * sampling in milliseconds. * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, long period) throws IOException { sample(incFilter, null, period); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @param incFilter * semicolon separated include filter list * @param excFilter * semicolon separated exclude filter list (null if empty) * @param period * sampling in milliseconds. * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, String excFilter, long period) throws IOException { sample(incFilter, excFilter, period, period); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @param incFilter * semicolon separated include filter list * @param excFilter * semicolon separated exclude filter list (null if empty) * @param initDelay * initial delay before first sampling * @param period * sampling in milliseconds. * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, String excFilter, long initDelay, long period) throws IOException { sample(incFilter, excFilter, initDelay, period, TimeUnit.MILLISECONDS); } /** * Schedule sample with default MBean server instance as well as all registered MBean servers within the JVM. * * @param incFilter * semicolon separated include filter list * @param excFilter * semicolon separated exclude filter list (null if empty) * @param initDelay * initial delay before first sampling * @param period * sampling time * @param tUnit * time units for sampling period * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, String excFilter, long initDelay, long period, TimeUnit tUnit) throws IOException { resolveServer(null); SamplerFactory sFactory = initPlatformJMX(incFilter, excFilter, initDelay, period, tUnit, null); // find other registered MBean servers and initiate sampling for all ArrayList<MBeanServer> mbsList = MBeanServerFactory.findMBeanServer(null); for (MBeanServer server : mbsList) { Sampler jmxSampler = STREAM_AGENTS.get(server); if (jmxSampler == null) { jmxSampler = sFactory.newInstance(server); scheduleSampler(incFilter, excFilter, initDelay, period, tUnit, sFactory, jmxSampler, STREAM_AGENTS); } } } private Source getSource() { TrackerConfig config = DefaultConfigFactory.getInstance().getConfig(getClass().getName()); SourceFactory instance = config.getSourceFactory(); String sourceDescriptor = null; Thread thread = Thread.currentThread(); if (thread instanceof SamplingAgentThread) { sourceDescriptor = ((SamplingAgentThread) thread).getVMSourceFQN(); } if (sourceDescriptor == null) { return instance.getRootSource(); } Source source; try { source = instance.fromFQN(sourceDescriptor); } catch (IllegalArgumentException e) { // TODO placeholders doesn't fill right LOGGER.log(OpLevel.WARNING, "SamplingAgent.getSource: source descriptor ''{1}'' doesn't match FQN pattern 'SourceType=SourceValue'. Erroneous source type. Valid types ''{0}''. Cause: {2}", Arrays.toString(SourceType.values()), sourceDescriptor, e.getMessage()); throw new RuntimeException("Invalid Source configuration"); } catch (IndexOutOfBoundsException e) { LOGGER.log(OpLevel.WARNING, "SamplingAgent.getSource: source descriptor ''{0}'' doesn't match FQN pattern 'SourceType=SourceValue'. Defaulting to ''SERVICE={0}''", sourceDescriptor); source = instance.newSource(sourceDescriptor, SourceType.SERVICE); } return source; } /** * Schedule sample using defined JMX connector to get MBean server connection instance to monitored JVM. * * @param incFilter * semicolon separated include filter list * @param excFilter * semicolon separated exclude filter list (null if empty) * @param initDelay * initial delay before first sampling * @param period * sampling time * @param tUnit * time units for sampling period * @param conn * JMX connector to get MBean server connection instance * * @throws IOException * if IO exception occurs while initializing MBeans sampling */ public void sample(String incFilter, String excFilter, long initDelay, long period, TimeUnit tUnit, JMXConnector conn) throws IOException { // get MBeanServerConnection from JMX RMI connector if (conn instanceof JMXAddressable) { JMXServiceURL url = ((JMXAddressable) conn).getAddress(); resolveServer(url == null ? null : url.getHost()); } MBeanServerConnection mbSrvConn = conn.getMBeanServerConnection(); initPlatformJMX(incFilter, excFilter, initDelay, period, tUnit, mbSrvConn); } private SamplerFactory initPlatformJMX(String incFilter, String excFilter, long initDelay, long period, TimeUnit tUnit, MBeanServerConnection mbSrvConn) throws IOException { // obtain a default sample factory SamplerFactory sFactory = DefaultSamplerFactory .getInstance(Utils.getConfProperty(DEFAULTS, "com.jkoolcloud.tnt4j.stream.jmx.sampler.factory")); if (platformJmx == null) { synchronized (STREAM_AGENTS) { // create new sampler with default MBeanServer instance platformJmx = mbSrvConn == null ? sFactory.newInstance() : sFactory.newInstance(mbSrvConn); // schedule sample with a given filter and sampling period scheduleSampler(incFilter, excFilter, initDelay, period, tUnit, sFactory, platformJmx, STREAM_AGENTS); } } return sFactory; } private void scheduleSampler(String incFilter, String excFilter, long initDelay, long period, TimeUnit tUnit, SamplerFactory sFactory, Sampler sampler, Map<MBeanServerConnection, Sampler> agents) throws IOException { agents.put(sampler.getMBeanServer(), sampler); sampler.setSchedule(incFilter, excFilter, initDelay, period, tUnit, sFactory, getSource()) .addListener(sFactory.newListener(LISTENER_PROPERTIES)).run(); } /** * Attaches to {@code vmDescr} defined JVM as agent. * * @param vmDescr * JVM descriptor: name fragment or pid * @param agentJarPath * agent JAR path * @param agentOptions * agent options * @throws Exception * if any exception occurs while attaching to JVM */ public static void attach(String vmDescr, String agentJarPath, String agentOptions) throws Exception { LOGGER.log(OpLevel.INFO, "SamplingAgent.attach(): vmDescr={0}, agentJarPath={1}, agentOptions={2}", vmDescr, agentJarPath, agentOptions); if (Utils.isEmpty(vmDescr)) { throw new RuntimeException("Java VM descriptor must be not empty!.."); } File pathFile; if (StringUtils.isEmpty(agentJarPath)) { LOGGER.log(OpLevel.INFO, "SamplingAgent.attach: no agent jar defined"); pathFile = getSAPath(); } else { pathFile = new File(agentJarPath); if (!pathFile.exists()) { LOGGER.log(OpLevel.INFO, "SamplingAgent.attach: non-existing argument defined agent jar: {0}", agentJarPath); LOGGER.log(OpLevel.INFO, " absolute agent jar path: {0}", pathFile.getAbsolutePath()); pathFile = getSAPath(); } } String agentPath = pathFile.getAbsolutePath(); for (Map.Entry<String, Object> lpe : LISTENER_PROPERTIES.entrySet()) { agentOptions += "!" + lpe.getKey() + "=" + String.valueOf(lpe.getValue()); } agentOptions += "!" + SYS_PROP_AGENT_PATH + "=" + agentPath; String tnt4jConf = System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY); if (!Utils.isEmpty(tnt4jConf)) { String tnt4jPropPath = new File(tnt4jConf).getAbsolutePath(); agentOptions += "!" + SYS_PROP_TNT4J_CFG + "=" + tnt4jPropPath; } String log4jConf = System.getProperty(LOG4J_PROPERTIES_KEY); if (!Utils.isEmpty(log4jConf)) { String log4jPropPath = new File(log4jConf).getAbsolutePath(); agentOptions += "!" + SYS_PROP_LOG4J_CFG + "=" + log4jPropPath; } LOGGER.log(OpLevel.INFO, "SamplingAgent.attach: attaching JVM using vmDescr={0}, agentJarPath={1}, agentOptions={2}", vmDescr, agentJarPath, agentOptions); VMUtils.attachVM(vmDescr, agentPath, agentOptions); } private static File getSAPath() throws URISyntaxException { String saPath = SamplingAgent.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); LOGGER.log(OpLevel.INFO, "SamplingAgent.attach: using SamplingAgent class referenced jar path: {0}", saPath); File agentFile = new File(saPath); if (!agentFile.exists()) { throw new RuntimeException("Could not find agent jar: " + agentFile.getAbsolutePath()); } return agentFile; } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String,String,long) */ public void connect(String vmDescr, String options) throws Exception { connect(vmDescr, options, CONN_RETRY_INTERVAL); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String,String,Map,long) */ public void connect(String vmDescr, String options, long connRetryInterval) throws Exception { connect(vmDescr, options, null, connRetryInterval); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connParams * map of JMX connection parameters, defined by {@link javax.naming.Context} * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String, String, java.util.Map, long) */ public void connect(String vmDescr, String options, Map<String, ?> connParams) throws Exception { connect(vmDescr, options, connParams, CONN_RETRY_INTERVAL); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connParams * map of JMX connection parameters, defined by {@link javax.naming.Context} * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String, String, String, String, java.util.Map, long) */ public void connect(String vmDescr, String options, Map<String, ?> connParams, long connRetryInterval) throws Exception { connect(vmDescr, null, null, options, connParams, connRetryInterval); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param user * user login used by JMX service connection * @param pass * user password used by JMX service connection * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String, String, String, String, long) */ public void connect(String vmDescr, String user, String pass, String options) throws Exception { connect(vmDescr, user, pass, options, CONN_RETRY_INTERVAL); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param user * user login used by JMX service connection * @param pass * user password used by JMX service connection * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(String, String, String, String, java.util.Map, long) */ public void connect(String vmDescr, String user, String pass, String options, long connRetryInterval) throws Exception { connect(vmDescr, user, pass, options, null, connRetryInterval); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param vmDescr * JVM descriptor: JMX service URI, local JVM name fragment or pid * @param user * user login used by JMX service connection * @param pass * user password used by JMX service connection * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connParams * map of JMX connection parameters, defined by {@link javax.naming.Context} * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see #connect(javax.management.remote.JMXServiceURL, String, String, String, java.util.Map, long) */ public void connect(String vmDescr, String user, String pass, String options, Map<String, ?> connParams, long connRetryInterval) throws Exception { connect(getJmxServiceURLs(vmDescr).get(0), user, pass, options, connParams, connRetryInterval); } /** * Connects to {@code vmDescr} defined JVM over {@link JMXConnector} an uses {@link MBeanServerConnection} to * collect samples. * * @param url * JMX service URL * @param user * user login used by JMX service connection * @param pass * user password used by JMX service connection * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param connParams * map of JMX connection parameters, defined by {@link javax.naming.Context} * @param connRetryInterval * connect reattempt interval value in seconds, {@code -1} - do not retry * @throws Exception * if any exception occurs while connecting to JVM * * @see JMXConnectorFactory#connect(javax.management.remote.JMXServiceURL, java.util.Map) * @see javax.naming.Context */ public void connect(JMXServiceURL url, String user, String pass, String options, Map<String, ?> connParams, long connRetryInterval) throws Exception { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect(): url={0}, user={1}, pass={2}, options={3}, connParams={4}, connRetryInterval={5}", url, user, Utils.hideEnd(pass, "x", 0), options, connParams, connRetryInterval); if (url == null) { throw new RuntimeException("JMX service URL is null!.."); } Map<String, Object> params = new HashMap<String, Object>(connParams == null ? 1 : connParams.size() + 1); if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(pass)) { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect: adding user login and password to connection credentials..."); String[] credentials = new String[] { user, pass }; params.put(JMXConnector.CREDENTIALS, credentials); } if (connParams != null) { params.putAll(connParams); } do { try { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect: connecting JMX service using URL={0}", url); JMXConnector connector = JMXConnectorFactory.connect(url, params); try { NotificationListener cnl = new NotificationListener() { @Override public void handleNotification(Notification notification, Object key) { if (notification.getType().contains("closed") || notification.getType().contains("failed") || notification.getType().contains("lost")) { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect: JMX connection status change: {0}", notification.getType()); stopSampler(); } } }; connector.addConnectionNotificationListener(cnl, null, null); startSamplerAndWait(options, connector); shutdownSamplers(); connector.removeConnectionNotificationListener(cnl); } finally { Utils.close(connector); } } catch (IOException exc) { LOGGER.log(OpLevel.ERROR, "SamplingAgent.connect: failed to connect JMX service"); LOGGER.log(OpLevel.ERROR, " Exception: {0}", Utils.getExceptionMessages(exc)); if (connRetryInterval < 0) { stopSampling = true; } if (!stopSampling && connRetryInterval > 0) { LOGGER.log(OpLevel.INFO, "SamplingAgent.connect: will retry connect attempt in {0} seconds...", connRetryInterval); Thread.sleep(TimeUnit.SECONDS.toMillis(connRetryInterval)); } } } while (!stopSampling); } private static List<JMXServiceURL> getJmxServiceURLs(String vmDescr) throws IOException { if (Utils.isEmpty(vmDescr)) { throw new RuntimeException("Java VM descriptor must be not empty!.."); } List<JMXServiceURL> returnList = new ArrayList<JMXServiceURL>(); if (vmDescr.startsWith("service:jmx:")) { returnList.add(new JMXServiceURL(vmDescr)); LOGGER.log(OpLevel.INFO, "SamplingAgent.getJmxServiceURLs: making JMX service URL from address={0}", vmDescr); } else { List<String> connAddresses = VMUtils.getVMConnAddresses(vmDescr); for (String connAddress : connAddresses) { returnList.add(new JMXServiceURL(connAddress)); LOGGER.log(OpLevel.INFO, "SamplingAgent.getJmxServiceURLs: making JVM ''{0}'' JMX service URL from address={1}", vmDescr, connAddress); } } return returnList; } protected void stopSampler() { LOGGER.log(OpLevel.INFO, "SamplingAgent.stopSampler: releasing sampler lock..."); if (platformJmx != null) { synchronized (platformJmx) { platformJmx.notifyAll(); } } } /** * Initiates MBeans attributes sampling on local process runner JVM. * * @param options * '!' separated list of options mbean-filter!sample.ms!initDelay.ms, where mbean-filter is semicolon * separated list of mbean filters and {@code initDelay} is optional * @param wait * flag indicating whether to wait for a runner process to complete * @throws Exception * if any exception occurs while initializing local JVM sampler or stopping sampling process */ public static void sampleLocalVM(String options, boolean wait) throws Exception { LOGGER.log(OpLevel.INFO, "SamplingAgent.sampleLocalVM(): options={0}, wait={1}", options, wait); SamplingAgent samplingAgent = newSamplingAgent(); if (wait) { samplingAgent.startSamplerAndWait(options); } else { samplingAgent.startSampler(options); } } private void startSamplerAndWait(String options) throws Exception { startSamplerAndWait(options, null); } private void startSamplerAndWait(String options, JMXConnector connector) throws Exception { startSampler(options, connector); final Thread mainThread = Thread.currentThread(); // Reference to the current thread. Thread shutdownHook = new Thread(new Runnable() { @Override public void run() { stopSampling = true; stopSampler(); long startTime = System.currentTimeMillis(); try { mainThread.join(TimeUnit.SECONDS.toMillis(2)); } catch (Exception exc) { } LOGGER.log(OpLevel.INFO, "SamplingAgent.startSamplerAndWait: waited {0}ms. on Stream-JMX to complete...", (System.currentTimeMillis() - startTime)); } }); Runtime.getRuntime().addShutdownHook(shutdownHook); LOGGER.log(OpLevel.INFO, "SamplingAgent.startSamplerAndWait: locking on sampler: {0}...", platformJmx); if (platformJmx != null) { synchronized (platformJmx) { platformJmx.wait(); } } LOGGER.log(OpLevel.INFO, "SamplingAgent.startSamplerAndWait: stopping Stream-JMX..."); try { Runtime.getRuntime().removeShutdownHook(shutdownHook); } catch (IllegalStateException exc) { } } private void startSampler(String options) throws Exception { startSampler(options, null); } private void startSampler(String options, JMXConnector connector) throws Exception { String incFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.include.filter", Sampler.JMX_FILTER_ALL); String excFilter = System.getProperty("com.jkoolcloud.tnt4j.stream.jmx.exclude.filter", Sampler.JMX_FILTER_NONE); int period = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.period", Sampler.JMX_SAMPLE_PERIOD); int initDelay = Integer.getInteger("com.jkoolcloud.tnt4j.stream.jmx.init.delay", period); if (options != null) { String[] args = options.split("!"); if (args.length > 0) { incFilter = args[0]; } if (args.length > 1) { excFilter = args.length > 2 ? args[1] : Sampler.JMX_FILTER_NONE; period = Integer.parseInt(args.length > 2 ? args[2] : args[1]); } if (args.length > 2) { initDelay = Integer.parseInt(args.length > 3 ? args[3] : args[2]); } } if (connector == null) { sample(incFilter, excFilter, initDelay, period, TimeUnit.MILLISECONDS); } else { sample(incFilter, excFilter, initDelay, period, TimeUnit.MILLISECONDS, connector); } LOGGER.log(OpLevel.INFO, "SamplingAgent.startSampler: include.filter={0}, exclude.filter={1}, sample.ms={2}, initDelay.ms={3}, listener.properties={4}, tnt4j.config={5}, jmx.sample.list={6}", incFilter, excFilter, period, initDelay, LISTENER_PROPERTIES, System.getProperty(TrackerConfigStore.TNT4J_PROPERTIES_KEY), STREAM_AGENTS); } /** * Obtain a map of all scheduled MBeanServerConnections and associated sample references. * * @return map of all scheduled MBeanServerConnections and associated sample references. */ public Map<MBeanServerConnection, Sampler> getSamplers() { HashMap<MBeanServerConnection, Sampler> copy = new HashMap<MBeanServerConnection, Sampler>(89); copy.putAll(STREAM_AGENTS); return copy; } /** * Cancel and close all outstanding {@link Sampler} instances and stop all sampling for all {@link MBeanServer} * instances. */ public void cancel() { for (Sampler sampler : STREAM_AGENTS.values()) { sampler.cancel(); } STREAM_AGENTS.clear(); } /** * Cancel and close all sampling for a given {@link MBeanServer} instance. * * @param mServerConn * MBeanServerConnection instance */ public void cancel(MBeanServerConnection mServerConn) { Sampler sampler = STREAM_AGENTS.remove(mServerConn); if (sampler != null) { sampler.cancel(); } } /** * Stops platform JMX sampler, cancels and close all outstanding {@link Sampler} instances and stop all sampling for * all {@link MBeanServer} instances. * * @see #cancel() */ public static void destroy() { for (SamplingAgent agent : agents.values()) { synchronized (agent.STREAM_AGENTS) { agent.stopSampler(); agent.shutdownSamplers(); } } DefaultEventSinkFactory.shutdownAll(); } private void shutdownSamplers() { cancel(); platformJmx = null; } private static void initDefaults(Properties defProps) { Map<String, Properties> defPropsMap = new HashMap<String, Properties>(); String dPropsKey = null; int apiLevel = 0; try { Properties p = Utils.loadPropertiesResources("sjmx-defaults.properties"); String key; String pKey; for (Map.Entry<?, ?> pe : p.entrySet()) { pKey = (String) pe.getKey(); int di = pKey.indexOf("/"); if (di >= 0) { key = pKey.substring(0, di); pKey = pKey.substring(di + 1); } else { key = ""; } if ("api.level".equals(pKey)) { int peApiLevel = 0; try { peApiLevel = Integer.parseInt((String) pe.getValue()); } catch (NumberFormatException exc) { } if (peApiLevel > apiLevel) { apiLevel = peApiLevel; dPropsKey = key; } continue; } Properties dpe = defPropsMap.get(key); if (dpe == null) { dpe = new Properties(); defPropsMap.put(key, dpe); } dpe.setProperty(pKey, (String) pe.getValue()); } } catch (Exception exc) { } if (dPropsKey != null) { defProps.putAll(defPropsMap.get(dPropsKey)); } } private static void copyProperty(DefaultSampleListener.ListenerProperties lProp, Map<?, ?> sProperties, Map<String, Object> tProperties) { Utils.copyProperty(lProp.apName(), sProperties, lProp.pName(), tProperties); } private static void copyProperty(DefaultSampleListener.ListenerProperties lProp, Map<?, ?> sProperties, Map<String, Object> tProperties, Object defValue) { Utils.copyProperty(lProp.apName(), sProperties, lProp.pName(), tProperties, defValue); } private static class JarFilter implements FilenameFilter { JarFilter() { } @Override public boolean accept(File dir, String name) { String nfn = name.toLowerCase(); return nfn.endsWith(".jar") || nfn.endsWith(".zip"); } } }
Multi VM monitoring reviewed and completed.
tnt4j-stream-jmx-core/src/main/java/com/jkoolcloud/tnt4j/stream/jmx/SamplingAgent.java
Multi VM monitoring reviewed and completed.
<ide><path>nt4j-stream-jmx-core/src/main/java/com/jkoolcloud/tnt4j/stream/jmx/SamplingAgent.java <ide> import com.jkoolcloud.tnt4j.sink.EventSink; <ide> import com.jkoolcloud.tnt4j.source.Source; <ide> import com.jkoolcloud.tnt4j.source.SourceFactory; <del>import com.jkoolcloud.tnt4j.source.SourceFactoryImpl; <ide> import com.jkoolcloud.tnt4j.source.SourceType; <ide> import com.jkoolcloud.tnt4j.stream.jmx.core.DefaultSampleListener; <ide> import com.jkoolcloud.tnt4j.stream.jmx.core.PropertyNameBuilder; <ide> String ao = null; <ide> String user = null; <ide> String pass = null; <del> String sourceDescriptor = getSingleSourceDescriptor(); <add> String sourceDescriptor = null; <ide> <ide> List<ConnectionParams> allVMs = new ArrayList<ConnectionParams>(); <ide> <ide> String user = props.getProperty(AGENT_ARG_USER) == null ? null : props.getProperty(AGENT_ARG_USER); <ide> String pass = props.getProperty(AGENT_ARG_PASS) == null ? null : props.getProperty(AGENT_ARG_PASS); <ide> String agentOptions = props.getProperty(AGENT_ARG_OPTIONS, DEFAULT_AGENT_OPTIONS); <del> String sourcesDescriptor = getSingleSourceDescriptor(); <ide> <ide> List<ConnectionParams> connectionParamsList = new ArrayList<ConnectionParams>(); <ide> <ide> List<JMXServiceURL> jmxServiceURLs = getJmxServiceURLs(vmDescr); <ide> for (JMXServiceURL jmxServiceURL : jmxServiceURLs) { <del> connectionParamsList.add(new ConnectionParams(jmxServiceURL, user, pass, agentOptions, sourcesDescriptor)); <add> connectionParamsList.add(new ConnectionParams(jmxServiceURL, user, pass, agentOptions, null)); <ide> } <ide> <ide> return connectionParamsList; <del> } <del> <del> private static String getSingleSourceDescriptor() { <del> return System.getProperty(SOURCE_SERVICE_ID, SourceFactoryImpl.UNKNOWN_SOURCE); <ide> } <ide> <ide> public static Map<MBeanServerConnection, Sampler> getAllSamplers() {
Java
mit
7fdbaf8fd8d6e5fcb6b92c051327816ea24f2293
0
e16din/RequestManager
package com.e16din.requestmanager.retrofit; import android.support.annotation.NonNull; import android.text.TextUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.Cache; import com.squareup.okhttp.OkHttpClient; import java.util.Map; import java.util.concurrent.TimeUnit; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.converter.GsonConverter; /** * Created by e16din on 20.08.15. */ public class RetrofitAdapter extends BaseRetrofitAdapter { public static Object getService(Class requestManagerInterface, String endpoint, Map<String, String> headers) { return getService(requestManagerInterface, endpoint, headers, new GsonBuilder().create(), null, null); } public static Object getService(Class requestManagerInterface, String endpoint, Map<String, String> headers, Gson gson, Cache cache) { return getService(requestManagerInterface, endpoint, headers, gson, cache, null); } public static Object getService(Class requestManagerInterface, String endpoint, Map<String, String> headers, RestAdapter.Log log) { return getService(requestManagerInterface, endpoint, headers, new GsonBuilder().create(), null, log); } public static Object getService(Class requestManagerInterface, String endpoint, Map<String, String> headers, Gson gson, Cache cache, RestAdapter.Log log) { OkHttpClient client = new OkHttpClient(); if (cache != null) client.setCache(cache); client.setConnectTimeout(30, TimeUnit.SECONDS); client.setReadTimeout(30, TimeUnit.SECONDS); RestAdapter.Builder builder = new RestAdapter.Builder() .setEndpoint(endpoint) .setErrorHandler(new StaticErrorHandler()) .setLogLevel(RestAdapter.LogLevel.FULL) .setRequestInterceptor(getRequestInterceptor(headers)) .setConverter(new GsonConverter(gson)) .setClient(new OkClient(client)); if (log != null) builder.setLog(log); return builder.build().create(requestManagerInterface); } public static Object getService(Class requestManagerInterface, RestAdapter.Builder builder, Map<String, String> headers, Cache cache) { OkHttpClient client = new OkHttpClient(); if (cache != null) client.setCache(cache); client.setConnectTimeout(30, TimeUnit.SECONDS); client.setReadTimeout(30, TimeUnit.SECONDS); builder.setErrorHandler(new StaticErrorHandler()) .setRequestInterceptor(getRequestInterceptor(headers)) .setClient(new OkClient(client)); return builder.build().create(requestManagerInterface); } public static Object getService(Class requestManagerInterface, RestAdapter.Builder builder) { return builder.build().create(requestManagerInterface); } @NonNull private static RequestInterceptor getRequestInterceptor(final Map<String, String> headers) { return new RequestInterceptor() { @Override public void intercept(RequestFacade request) { for (String key : headers.keySet()) { request.addHeader(key, headers.get(key)); } if (!TextUtils.isEmpty(getCookies())) request.addHeader("Cookie", getCookies()); } }; } }
src/main/java/com/e16din/requestmanager/retrofit/RetrofitAdapter.java
package com.e16din.requestmanager.retrofit; import android.support.annotation.NonNull; import android.text.TextUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.squareup.okhttp.Cache; import com.squareup.okhttp.OkHttpClient; import java.util.Map; import java.util.concurrent.TimeUnit; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.client.OkClient; import retrofit.converter.GsonConverter; /** * Created by e16din on 20.08.15. */ public class RetrofitAdapter extends BaseRetrofitAdapter { public static Object getService(Class requestManagerInterface, String endpoint, Map<String, String> headers) { return getService(requestManagerInterface, endpoint, headers, new GsonBuilder().create(), null, null); } public static Object getService(Class requestManagerInterface, String endpoint, Map<String, String> headers, Gson gson, Cache cache) { return getService(requestManagerInterface, endpoint, headers, gson, cache, null); } public static Object getService(Class requestManagerInterface, String endpoint, Map<String, String> headers, RestAdapter.Log log) { return getService(requestManagerInterface, endpoint, headers, new GsonBuilder().create(), null, log); } public static Object getService(Class requestManagerInterface, String endpoint, Map<String, String> headers, Gson gson, Cache cache, RestAdapter.Log log) { OkHttpClient client = new OkHttpClient(); if (cache != null) client.setCache(cache); client.setConnectTimeout(30, TimeUnit.SECONDS); client.setReadTimeout(30, TimeUnit.SECONDS); RestAdapter.Builder builder = new RestAdapter.Builder() .setEndpoint(endpoint) .setErrorHandler(new StaticErrorHandler()) .setLogLevel(RestAdapter.LogLevel.FULL) .setRequestInterceptor(getRequestInterceptor(headers)) .setConverter(new GsonConverter(gson)) .setClient(new OkClient(client)); if (log != null) builder.setLog(log); return builder.build().create(requestManagerInterface); } public static Object getService(Class requestManagerInterface, RestAdapter.Builder builder) { return builder.build().create(requestManagerInterface); } @NonNull private static RequestInterceptor getRequestInterceptor(final Map<String, String> headers) { return new RequestInterceptor() { @Override public void intercept(RequestFacade request) { for (String key : headers.keySet()) { request.addHeader(key, headers.get(key)); } if (!TextUtils.isEmpty(getCookies())) request.addHeader("Cookie", getCookies()); } }; } }
added getService with builder
src/main/java/com/e16din/requestmanager/retrofit/RetrofitAdapter.java
added getService with builder
<ide><path>rc/main/java/com/e16din/requestmanager/retrofit/RetrofitAdapter.java <ide> return builder.build().create(requestManagerInterface); <ide> } <ide> <add> public static Object getService(Class requestManagerInterface, RestAdapter.Builder builder, Map<String, String> headers, Cache cache) { <add> OkHttpClient client = new OkHttpClient(); <add> if (cache != null) <add> client.setCache(cache); <add> client.setConnectTimeout(30, TimeUnit.SECONDS); <add> client.setReadTimeout(30, TimeUnit.SECONDS); <add> <add> builder.setErrorHandler(new StaticErrorHandler()) <add> .setRequestInterceptor(getRequestInterceptor(headers)) <add> .setClient(new OkClient(client)); <add> <add> return builder.build().create(requestManagerInterface); <add> } <add> <ide> public static Object getService(Class requestManagerInterface, RestAdapter.Builder builder) { <ide> return builder.build().create(requestManagerInterface); <ide> }
Java
apache-2.0
f07c1e9e9fb109d1013219d00d0667af4e74b601
0
dido/bptdb,dido/bptdb
/* * Copyright (c) 2013 Rafael R. Sevilla (http://games.stormwyrm.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.stormwyrm.bptdb; import java.io.IOException; import java.io.InputStream; import com.badlogic.gdx.files.FileHandle; /** * B+ Tree database. Should be able to read the same database files generated by the Ruby bptree.rb program * in the main directory. * * @author Rafael R. Sevilla * @see BPTDBPB */ public class BPTDB { public static final int IPAGE = 0; public static final int LPAGE = 1; public static final int INFIMUM_KEY = -2147483648; public static final int PAGESIZE = 256; public static final int DATASIZE = 4; public static final int MAXKEYS = (PAGESIZE/(DATASIZE*2)) - 2; /** * Abstract class representing a B+ tree page. Used for both leaf pages and internal pages. * * @author Rafael R. Sevilla * @see BPTDB */ abstract class Page { public int[] keys, values; public int nkeys; public int parent; private Integer[] findret; /** * Creates a new page. */ public Page() { keys = new int[MAXKEYS]; values = new int[MAXKEYS]; parent = -1; findret = new Integer[2]; } /** * Find the nearest keys to <code>k</code> stored in the page. It will return an array of two integers, * the first of which is the closest key less than <code>k</code>, and the second the closest key greater * than <code>k</code>. If the key is present in the page, both elements of the array will be equal. If * <code>k</code> is less than all the keys stored in the page, the first element will be null and the second * element will contain the smallest key in the page. Similarly, if <code>k</code> is greater than all the * keys in the page, the first element will contain the largest key in the page, and the second * element will be null. * * @param <code>k</code> - the key to search for * @return the key(s) closest to <code>k</code>. **/ protected Integer[] find(int k) { int first = 0, last = nkeys-1; if (keys[first] > k) { findret[0] = null; findret[1] = first; return(findret); } if (keys[last] < k) { findret[0] = last; findret[1] = null; return(findret); } while (last - first > 1) { int mid = (first + last)/2; if (keys[mid] == k) { findret[0] = findret[1] = mid; return(findret); } if (keys[mid] < k) { first = mid; continue; } last = mid; } if (keys[first] == k) { last = first; } else if (keys[last] == k) { first = last; } findret[0] = first; findret[1] = last; return(findret); } /** * Get the value of the key <code>k</code>. What this returns depends on the type of page. * @param <code>k</code> The key to search for */ public abstract Integer get(int k); } /** * A B+ Tree leaf page. The values inside leaf pages are file offsets to the actual data * pointed to by their keys. */ public class LPage extends Page { /** * Get the file offset value of the key <code>k</code>. Returns null if the key is not present in the page requested. * @param <code>k</code> the key to search for * @return the corresponding value, or null if the key was not found. */ @Override public Integer get(int k) { Integer[] bounds = find(k); if (bounds[0] == null || bounds[0] != bounds[1]) { return(null); } return(values[bounds[0]]); } } /** * A B+ Tree Internal Page. Internal pages can point to other internal pages or data pages. */ public class IPage extends Page { /** * Get the file offset value of the closest key in the page less than <code>k</code>. * If <code>k</code> is less than all values in the page, returns the value of the smallest element * (the infimum). * @param <code>k</code> the key to search for */ @Override public Integer get(int k) { Integer[] bounds = find(k); if (bounds[0] == null) return(values[bounds[1]]); return(values[bounds[0]]); } } /** * Class to load pages. */ public class PageLoader { private FileHandle dbfile; private InputStream dbis; private IPage ipage; private LPage lpage; /** * Creates a new page loader given a libgdx <code>FileHandle</code>. There are no restrictions on * the file handle, and it may be of any type supported by libgdx. * @param <code>fh</code> The file handle to use for the page loader. */ public PageLoader(FileHandle fh) { dbfile = fh; dbis = fh.read(); if (dbis.markSupported()) dbis.mark(0); ipage = new IPage(); lpage = new LPage(); } /** * Reset the DB input stream. Uses reset if the stream allows it, else rereads the file so that * its offset returns to the beginning. */ private void resetDBIS() { try { if (dbis.markSupported()) dbis.reset(); else throw new IOException("mark not supported"); } catch (IOException e) { dbis = dbfile.read(); } } /** * Load an integer from an <code>InputStream</code>. Integers are encoded as big-endian two's complement * signed integers. * @param <code>fp</code> The input stream to read from * @throws <code>IOException</code> if there was an error reading the stream. */ private int loadInt(InputStream fp) throws IOException { int ret = 0; for (int i=0; i<4; i++) { ret <<= 8; int b = fp.read() & 0xff; ret |= b; } return(ret); } /** * Load a page from the stream at the file offset <code>offset</code>. Returns <code>null</code> if a page cannot * be decoded at that location. * @param <code>offset</code> The file offset at which to load a page. */ public Page loadPage(int offset) { Page page = null; try { resetDBIS(); dbis.skip(offset); int t = loadInt(dbis); int len = t >> 1; page = ((t & 1) == IPAGE) ? ipage : lpage; page.nkeys = len; page.parent = loadInt(dbis); // This assumes the saved keys are sorted. If the data were generated // by the Ruby code, this is always true. for (int i=0; i<len; i++) { int k, v; k = loadInt(dbis); v = loadInt(dbis); page.keys[i] = k; page.values[i] = v; } } catch (IOException ex) { } return(page); } } private PageLoader pageloader; /** * Create a new BPTDB instance, given the libgdx <code>FileHandle fh</code>. * @param <code>fh</code> file handle on which this instance is based. */ public BPTDB(FileHandle fh) { pageloader = new PageLoader(fh); } /** * Search for the key <code>key</code> inside the database. Returns the offset corresponding to the key if it * exists, or <code>null</code> if the key is not present in the database. * @param <code>key</code> the key to search for */ public Integer search(int key) { int offset = 0; Page page; for (;;) { page = pageloader.loadPage(offset); if (page == null) return(null); if (page instanceof LPage) { return(page.get(key)); } offset = page.get(key); } } }
src/com/stormwyrm/bptdb/BPTDB.java
/* * Copyright (c) 2013 Rafael R. Sevilla (http://games.stormwyrm.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.stormwyrm.bptdb; import java.io.IOException; import java.io.InputStream; import com.badlogic.gdx.files.FileHandle; /** * B+ Tree database. Should be able to read the same database files generated by the Ruby BPTDB class in misc */ public class BPTDB { public static final int IPAGE = 0; public static final int LPAGE = 1; public static final int INFIMUM_KEY = -2147483648; public static final int PAGESIZE = 256; public static final int DATASIZE = 4; public static final int MAXKEYS = (PAGESIZE/(DATASIZE*2)) - 2; abstract class Page { public int[] keys, values; public int nkeys; public int parent; private Integer[] findret; public Page() { keys = new int[MAXKEYS]; values = new int[MAXKEYS]; parent = -1; findret = new Integer[2]; } /** find the nearest keys to k */ protected Integer[] find(int k) { int first = 0, last = nkeys-1; if (keys[first] > k) { findret[0] = null; findret[1] = first; return(findret); } if (keys[last] < k) { findret[0] = last; findret[1] = null; return(findret); } while (last - first > 1) { int mid = (first + last)/2; if (keys[mid] == k) { findret[0] = findret[1] = mid; return(findret); } if (keys[mid] < k) { first = mid; continue; } last = mid; } if (keys[first] == k) { last = first; } else if (keys[last] == k) { first = last; } findret[0] = first; findret[1] = last; return(findret); } public abstract Integer get(int k); } public class LPage extends Page { @Override public Integer get(int k) { Integer[] bounds = find(k); if (bounds[0] == null || bounds[0] != bounds[1]) { return(null); } return(values[bounds[0]]); } } public class IPage extends Page { @Override public Integer get(int k) { Integer[] bounds = find(k); return(values[bounds[0]]); } } public class PageLoader { private FileHandle dbfile; private InputStream dbis; private IPage ipage; private LPage lpage; public PageLoader(FileHandle fh) { dbfile = fh; dbis = fh.read(); if (dbis.markSupported()) dbis.mark(0); ipage = new IPage(); lpage = new LPage(); } private void resetDBIS() { try { if (dbis.markSupported()) dbis.reset(); else throw new IOException("mark not supported"); } catch (IOException e) { dbis = dbfile.read(); } } public int loadInt(InputStream fp) throws IOException { int ret = 0; for (int i=0; i<4; i++) { ret <<= 8; int b = fp.read() & 0xff; ret |= b; } return(ret); } public Page loadPage(int offset) { Page page = null; try { resetDBIS(); dbis.skip(offset); int t = loadInt(dbis); int len = t >> 1; page = ((t & 1) == IPAGE) ? ipage : lpage; page.nkeys = len; page.parent = loadInt(dbis); // This assumes the saved keys are sorted. If the data were generated // by the Ruby code, this is always true. for (int i=0; i<len; i++) { int k, v; k = loadInt(dbis); v = loadInt(dbis); page.keys[i] = k; page.values[i] = v; } } catch (IOException ex) { } return(page); } } PageLoader pageloader; public BPTDB(FileHandle fh) { pageloader = new PageLoader(fh); } public Integer search(int key) { int offset = 0; Page page; for (;;) { page = pageloader.loadPage(offset); if (page == null) return(null); if (page instanceof LPage) { return(page.get(key)); } offset = page.get(key); } } }
add some javadocs
src/com/stormwyrm/bptdb/BPTDB.java
add some javadocs
<ide><path>rc/com/stormwyrm/bptdb/BPTDB.java <ide> import com.badlogic.gdx.files.FileHandle; <ide> <ide> /** <del> * B+ Tree database. Should be able to read the same database files generated by the Ruby BPTDB class in misc <add> * B+ Tree database. Should be able to read the same database files generated by the Ruby bptree.rb program <add> * in the main directory. <add> * <add> * @author Rafael R. Sevilla <add> * @see BPTDBPB <ide> */ <ide> public class BPTDB <ide> { <ide> public static final int DATASIZE = 4; <ide> public static final int MAXKEYS = (PAGESIZE/(DATASIZE*2)) - 2; <ide> <add> /** <add> * Abstract class representing a B+ tree page. Used for both leaf pages and internal pages. <add> * <add> * @author Rafael R. Sevilla <add> * @see BPTDB <add> */ <ide> abstract class Page <ide> { <ide> public int[] keys, values; <ide> public int parent; <ide> private Integer[] findret; <ide> <add> /** <add> * Creates a new page. <add> */ <ide> public Page() <ide> { <ide> keys = new int[MAXKEYS]; <ide> findret = new Integer[2]; <ide> } <ide> <del> /** find the nearest keys to k */ <add> /** <add> * Find the nearest keys to <code>k</code> stored in the page. It will return an array of two integers, <add> * the first of which is the closest key less than <code>k</code>, and the second the closest key greater <add> * than <code>k</code>. If the key is present in the page, both elements of the array will be equal. If <add> * <code>k</code> is less than all the keys stored in the page, the first element will be null and the second <add> * element will contain the smallest key in the page. Similarly, if <code>k</code> is greater than all the <add> * keys in the page, the first element will contain the largest key in the page, and the second <add> * element will be null. <add> * <add> * @param <code>k</code> - the key to search for <add> * @return the key(s) closest to <code>k</code>. <add> **/ <ide> protected Integer[] find(int k) <ide> { <ide> int first = 0, last = nkeys-1; <ide> return(findret); <ide> } <ide> <add> /** <add> * Get the value of the key <code>k</code>. What this returns depends on the type of page. <add> * @param <code>k</code> The key to search for <add> */ <ide> public abstract Integer get(int k); <ide> } <ide> <add> /** <add> * A B+ Tree leaf page. The values inside leaf pages are file offsets to the actual data <add> * pointed to by their keys. <add> */ <ide> public class LPage extends Page <ide> { <add> /** <add> * Get the file offset value of the key <code>k</code>. Returns null if the key is not present in the page requested. <add> * @param <code>k</code> the key to search for <add> * @return the corresponding value, or null if the key was not found. <add> */ <ide> @Override <ide> public Integer get(int k) <ide> { <ide> } <ide> } <ide> <add> /** <add> * A B+ Tree Internal Page. Internal pages can point to other internal pages or data pages. <add> */ <ide> public class IPage extends Page <ide> { <add> /** <add> * Get the file offset value of the closest key in the page less than <code>k</code>. <add> * If <code>k</code> is less than all values in the page, returns the value of the smallest element <add> * (the infimum). <add> * @param <code>k</code> the key to search for <add> */ <ide> @Override <ide> public Integer get(int k) <ide> { <ide> Integer[] bounds = find(k); <add> if (bounds[0] == null) <add> return(values[bounds[1]]); <ide> return(values[bounds[0]]); <ide> } <ide> } <ide> <add> /** <add> * Class to load pages. <add> */ <ide> public class PageLoader <ide> { <ide> private FileHandle dbfile; <ide> private IPage ipage; <ide> private LPage lpage; <ide> <add> /** <add> * Creates a new page loader given a libgdx <code>FileHandle</code>. There are no restrictions on <add> * the file handle, and it may be of any type supported by libgdx. <add> * @param <code>fh</code> The file handle to use for the page loader. <add> */ <ide> public PageLoader(FileHandle fh) <ide> { <ide> dbfile = fh; <ide> lpage = new LPage(); <ide> } <ide> <add> /** <add> * Reset the DB input stream. Uses reset if the stream allows it, else rereads the file so that <add> * its offset returns to the beginning. <add> */ <ide> private void resetDBIS() <ide> { <ide> try { <ide> } <ide> } <ide> <del> public int loadInt(InputStream fp) throws IOException <add> /** <add> * Load an integer from an <code>InputStream</code>. Integers are encoded as big-endian two's complement <add> * signed integers. <add> * @param <code>fp</code> The input stream to read from <add> * @throws <code>IOException</code> if there was an error reading the stream. <add> */ <add> private int loadInt(InputStream fp) throws IOException <ide> { <ide> int ret = 0; <ide> <ide> return(ret); <ide> } <ide> <add> /** <add> * Load a page from the stream at the file offset <code>offset</code>. Returns <code>null</code> if a page cannot <add> * be decoded at that location. <add> * @param <code>offset</code> The file offset at which to load a page. <add> */ <ide> public Page loadPage(int offset) <ide> { <ide> Page page = null; <ide> } <ide> } <ide> <del> PageLoader pageloader; <del> <add> private PageLoader pageloader; <add> <add> /** <add> * Create a new BPTDB instance, given the libgdx <code>FileHandle fh</code>. <add> * @param <code>fh</code> file handle on which this instance is based. <add> */ <ide> public BPTDB(FileHandle fh) <ide> { <ide> pageloader = new PageLoader(fh); <ide> } <ide> <add> /** <add> * Search for the key <code>key</code> inside the database. Returns the offset corresponding to the key if it <add> * exists, or <code>null</code> if the key is not present in the database. <add> * @param <code>key</code> the key to search for <add> */ <ide> public Integer search(int key) <ide> { <ide> int offset = 0;
JavaScript
mit
5d14a19926328cee89ee5508c1b3fd0682487791
0
generate/generate,generate/generate
'use strict'; var exists = require('fs-exists-sync'); var fs = require('fs'); /** * Run the given generators and tasks. This flag is unnecessary when * used with [base-runner][]. * * ```sh * # run task 'foo' * $ app --tasks foo * # => {task: ['foo']} * # run generator 'foo', task 'bar' * $ app --tasks foo:bar * # => {task: ['foo:bar']} * ``` * @name tasks * @api public * @cli public */ module.exports = function(app, options) { return function(val, key, config, next) { var tasks = setTasks(app, options.env.configFile, val); app.generate(tasks, next); }; }; /** * Determine the task to run */ function setTasks(app, configFile, tasks) { if (tasks.length === 1 && tasks[0] === 'default') { // if a `generator.js` does not exist, return an empty array if (!exists(configFile)) { return ['help']; } } return tasks; }
lib/commands/tasks.js
'use strict'; var exists = require('fs-exists-sync'); var fs = require('fs'); /** * Run the given generators and tasks. This flag is unnecessary when * used with [base-runner][]. * * ```sh * # run task 'foo' * $ app --tasks foo * # => {task: ['foo']} * # run generator 'foo', task 'bar' * $ app --tasks foo:bar * # => {task: ['foo:bar']} * ``` * @name tasks * @api public * @cli public */ module.exports = function(app, options) { return function(val, key, config, next) { app.debug('command > %s: "%j"', key, val); var tasks = setTasks(app, options.env.configfile, val); app.generateEach(tasks, next); }; }; /** * Determine the task to run */ function setTasks(app, configfile, tasks) { if (tasks.length === 1 && tasks[0] === 'default') { // if a `generator.js` does not exist, return an empty array if (!exists(configfile)) { return ['help']; } } return tasks; }
fix variable, call `.generate` instead of `.generateEach`
lib/commands/tasks.js
fix variable, call `.generate` instead of `.generateEach`
<ide><path>ib/commands/tasks.js <ide> <ide> module.exports = function(app, options) { <ide> return function(val, key, config, next) { <del> app.debug('command > %s: "%j"', key, val); <del> var tasks = setTasks(app, options.env.configfile, val); <del> app.generateEach(tasks, next); <add> var tasks = setTasks(app, options.env.configFile, val); <add> app.generate(tasks, next); <ide> }; <ide> }; <ide> <ide> * Determine the task to run <ide> */ <ide> <del>function setTasks(app, configfile, tasks) { <add>function setTasks(app, configFile, tasks) { <ide> if (tasks.length === 1 && tasks[0] === 'default') { <ide> <ide> // if a `generator.js` does not exist, return an empty array <del> if (!exists(configfile)) { <add> if (!exists(configFile)) { <ide> return ['help']; <ide> } <ide> }
Java
apache-2.0
017a40c3bece40e2d4651e5bd513aa1726993269
0
jzmq/pinot,jzmq/pinot,jzmq/pinot,jzmq/pinot,jzmq/pinot,jzmq/pinot
/** * Copyright (C) 2014-2015 LinkedIn Corp. ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.controller.helix; import com.linkedin.pinot.controller.helix.core.UAutoRebalancer; import org.apache.helix.*; import org.apache.helix.controller.pipeline.StageException; import org.apache.helix.controller.stages.CurrentStateOutput; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZNRecordSerializer; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.manager.zk.ZkClient; import org.apache.helix.model.*; import org.apache.helix.util.HelixUtil; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.TimeUnit; /** * In this class , we rebuild many env parameters for UAutoRebalancer to calculate new idealstate */ public class Rebalancer { private static Logger logger = Logger.getLogger(Rebalancer.class); private static ZkClient _zkClient; private static UAutoRebalancer _rebalancer; public Rebalancer(String zkAddress){ _zkClient = new ZkClient(zkAddress, 30 * 1000); _zkClient.setZkSerializer(new ZNRecordSerializer()); _zkClient.waitUntilConnected(30, TimeUnit.SECONDS); _rebalancer = new UAutoRebalancer(); // Here no need to init especially helixmanager } public void rebalance(String clusterName, String resourceName, int replica) { rebalance(clusterName, resourceName, replica, resourceName, ""); } public void rebalance(String clusterName, String resourceName, int replica, String keyPrefix, String group) { List<String> instanceNames = new LinkedList<String>(); if (keyPrefix == null || keyPrefix.length() == 0) { keyPrefix = resourceName; } if (group != null && group.length() > 0) { instanceNames = getInstancesInClusterWithTag(clusterName, group); } if (instanceNames.size() == 0) { logger.info("No tags found for resource " + resourceName + ", use all instances"); instanceNames = getInstancesInCluster(clusterName); group = ""; } else { logger.info("Found instances with tag for " + resourceName + " " + instanceNames); } rebalance(clusterName, resourceName, replica, keyPrefix, instanceNames, group); } public void rebalance(String clusterName, String resourceName, int replica, List<String> instances) { rebalance(clusterName, resourceName, replica, resourceName, instances, ""); } void rebalance(String clusterName, String resourceName, int replica, String keyPrefix, List<String> instanceNames, String groupId) { // ensure we get the same idealState with the same set of instances Collections.sort(instanceNames); IdealState idealState = getResourceIdealState(clusterName, resourceName); if (idealState == null) { throw new HelixException("Resource: " + resourceName + " has NOT been added yet"); } // logger.info("###ideal state is : "+idealState.toString()); if (groupId != null && groupId.length() > 0) { idealState.setInstanceGroupTag(groupId); } idealState.setReplicas(Integer.toString(replica)); int partitions = idealState.getNumPartitions(); String stateModelName = idealState.getStateModelDefRef(); StateModelDefinition stateModDef = getStateModelDef(clusterName, stateModelName); if (stateModDef == null) { throw new HelixException("cannot find state model: " + stateModelName); } // StateModelDefinition def = new StateModelDefinition(stateModDef); List<String> statePriorityList = stateModDef.getStatesPriorityList(); String masterStateValue = null; String slaveStateValue = null; replica--; for (String state : statePriorityList) { String count = stateModDef.getNumInstancesPerState(state); if (count.equals("1")) { if (masterStateValue != null) { throw new HelixException("Invalid or unsupported state model definition"); } masterStateValue = state; } else if (count.equalsIgnoreCase("R")) { if (slaveStateValue != null) { throw new HelixException("Invalid or unsupported state model definition"); } slaveStateValue = state; } else if (count.equalsIgnoreCase("N")) { if (!(masterStateValue == null && slaveStateValue == null)) { throw new HelixException("Invalid or unsupported state model definition"); } replica = instanceNames.size() - 1; masterStateValue = slaveStateValue = state; } } if (masterStateValue == null && slaveStateValue == null) { throw new HelixException("Invalid or unsupported state model definition"); } if (masterStateValue == null) { masterStateValue = slaveStateValue; } IdealState newIdealState = null; if (idealState.getRebalanceMode() != IdealState.RebalanceMode.FULL_AUTO && idealState.getRebalanceMode() != IdealState.RebalanceMode.USER_DEFINED) { // logger.info("#### Into rebalance mode"); // logger.info("get live instance :"+getLiveInstances(clusterName)); // logger.info("get instance config map :"+getInstanceConfigMap(clusterName)); // logger.info("get current state output "+ computeCurrentStateOutput(clusterName)); newIdealState = _rebalancer.computeNewIdealState(resourceName,idealState,stateModDef, getLiveInstances(clusterName),getInstanceConfigMap(clusterName),computeCurrentStateOutput(clusterName)); } else { for (int i = 0; i < partitions; i++) { String partitionName = keyPrefix + "_" + i; newIdealState.getRecord().setMapField(partitionName, new HashMap<String, String>()); newIdealState.getRecord().setListField(partitionName, new ArrayList<String>()); } } // logger.info("new ideal state is : "+ newIdealState.toString()); setResourceIdealState(clusterName, resourceName, newIdealState); } /** * Get LiveInstances by clusterName * @param clusterName * @return */ public Map<String,LiveInstance> getLiveInstances(String clusterName){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.liveInstances()); } /** * Get Instance Configs * @param clusterName * @return */ public Map<String,InstanceConfig> getInstanceConfigMap(String clusterName){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.instanceConfigs()); } /** * Get IdealState * @param clusterName * @return */ public Map<String,IdealState> getIdealStates(String clusterName){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.idealStates()); } /** * Get Resource IdealState * @param clusterName * @param resourceName * @return */ public IdealState getResourceIdealState(String clusterName, String resourceName) { HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getProperty(keyBuilder.idealStates(resourceName)); } /** * Set Resource IdealState * @param clusterName * @param resourceName * @param idealState */ public void setResourceIdealState(String clusterName, String resourceName, IdealState idealState) { HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); accessor.setProperty(keyBuilder.idealStates(resourceName), idealState); } /** * Get State model Def * @param clusterName * @param stateModelName * @return */ public StateModelDefinition getStateModelDef(String clusterName, String stateModelName) { HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getProperty(keyBuilder.stateModelDef(stateModelName)); } /** * Get Instances with Tag * @param clusterName * @param tag * @return */ public List<String> getInstancesInClusterWithTag(String clusterName, String tag) { String memberInstancesPath = HelixUtil.getMemberInstancesPath(clusterName); List<String> instances = _zkClient.getChildren(memberInstancesPath); List<String> result = new ArrayList<String>(); HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); for (String instanceName : instances) { InstanceConfig config = accessor.getProperty(keyBuilder.instanceConfig(instanceName)); if (config.containsTag(tag)) { result.add(instanceName); } } return result; } /** * Get all instances * @param clusterName * @return */ public List<String> getInstancesInCluster(String clusterName) { String memberInstancesPath = HelixUtil.getMemberInstancesPath(clusterName); return _zkClient.getChildren(memberInstancesPath); } /** * Get Instance Message * @param clusterName * @param instanceName * @return */ public Map<String, Message> getInstanceMessage (String clusterName,String instanceName){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.messages(instanceName)); } /** * Get Instance CurrentState * @param clusterName * @param instanceName * @param clientSessionId * @return */ public Map<String, CurrentState> getCurrentState (String clusterName,String instanceName,String clientSessionId){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.currentStates(instanceName, clientSessionId)); } /** * Get Resource Map * @param clusterName * @return */ public Map<String,Resource> getResourceMap(String clusterName){ Map<String, IdealState> idealStates = getIdealStates(clusterName); Map<String, Resource> resourceMap = new LinkedHashMap<String, Resource>(); if (idealStates != null && idealStates.size() > 0) { for (IdealState idealState : idealStates.values()) { Set<String> partitionSet = idealState.getPartitionSet(); String resourceName = idealState.getResourceName(); if (!resourceMap.containsKey(resourceName)) { Resource resource = new Resource(resourceName); resourceMap.put(resourceName, resource); resource.setStateModelDefRef(idealState.getStateModelDefRef()); resource.setStateModelFactoryName(idealState.getStateModelFactoryName()); resource.setBucketSize(idealState.getBucketSize()); resource.setBatchMessageMode(idealState.getBatchMessageMode()); } for (String partition : partitionSet) { addPartition(partition, resourceName, resourceMap); } } } Map<String, LiveInstance> availableInstances = getLiveInstances(clusterName); if (availableInstances != null && availableInstances.size() > 0) { for (LiveInstance instance : availableInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getSessionId(); Map<String, CurrentState> currentStateMap = getCurrentState(clusterName, instanceName, clientSessionId); if (currentStateMap == null || currentStateMap.size() == 0) { continue; } for (CurrentState currentState : currentStateMap.values()) { String resourceName = currentState.getResourceName(); Map<String, String> resourceStateMap = currentState.getPartitionStateMap(); if (resourceStateMap.keySet().isEmpty()) { // don't include empty current state for dropped resource continue; } // don't overwrite ideal state settings if (!resourceMap.containsKey(resourceName)) { addResource(resourceName, resourceMap); Resource resource = resourceMap.get(resourceName); resource.setStateModelDefRef(currentState.getStateModelDefRef()); resource.setStateModelFactoryName(currentState.getStateModelFactoryName()); resource.setBucketSize(currentState.getBucketSize()); resource.setBatchMessageMode(currentState.getBatchMessageMode()); } if (currentState.getStateModelDefRef() == null) { logger.error("state model def is null." + "resource:" + currentState.getResourceName() + ", partitions: " + currentState.getPartitionStateMap().keySet() + ", states: " + currentState.getPartitionStateMap().values()); try { throw new StageException("State model def is null for resource:" + currentState.getResourceName()); } catch (StageException e) { e.printStackTrace(); } } for (String partition : resourceStateMap.keySet()) { addPartition(partition, resourceName, resourceMap); } } } } return resourceMap; } private void addResource(String resource, Map<String, Resource> resourceMap) { if (resource == null || resourceMap == null) { return; } if (!resourceMap.containsKey(resource)) { resourceMap.put(resource, new Resource(resource)); } } private void addPartition(String partition, String resourceName, Map<String, Resource> resourceMap) { if (resourceName == null || partition == null || resourceMap == null) { return; } if (!resourceMap.containsKey(resourceName)) { resourceMap.put(resourceName, new Resource(resourceName)); } Resource resource = resourceMap.get(resourceName); resource.addPartition(partition); } /** * Compute CurrentStateOutput , the same as CurrentStateComputationStage.java * @param clusterName * @return */ public CurrentStateOutput computeCurrentStateOutput(String clusterName){ Map<String, Resource> resourceMap = getResourceMap(clusterName); Map<String, LiveInstance> liveInstances = getLiveInstances(clusterName); CurrentStateOutput currentStateOutput = new CurrentStateOutput(); for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); Map<String, Message> instanceMessages = getInstanceMessage(clusterName,instanceName); for (Message message : instanceMessages.values()) { if (!Message.MessageType.STATE_TRANSITION.toString().equalsIgnoreCase(message.getMsgType())) { continue; } if (!instance.getSessionId().equals(message.getTgtSessionId())) { continue; } String resourceName = message.getResourceName(); Resource resource = resourceMap.get(resourceName); if (resource == null) { continue; } if (!message.getBatchMessageMode()) { String partitionName = message.getPartitionName(); Partition partition = resource.getPartition(partitionName); if (partition != null) { currentStateOutput.setPendingState(resourceName, partition, instanceName, message); } else { // log } } else { List<String> partitionNames = message.getPartitionNames(); if (!partitionNames.isEmpty()) { for (String partitionName : partitionNames) { Partition partition = resource.getPartition(partitionName); if (partition != null) { currentStateOutput.setPendingState(resourceName, partition, instanceName, message); } else { // log } } } } } } for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getSessionId(); Map<String, CurrentState> currentStateMap =getCurrentState(clusterName,instanceName,clientSessionId); for (CurrentState currentState : currentStateMap.values()) { if (!instance.getSessionId().equals(currentState.getSessionId())) { continue; } String resourceName = currentState.getResourceName(); String stateModelDefName = currentState.getStateModelDefRef(); Resource resource = resourceMap.get(resourceName); if (resource == null) { continue; } if (stateModelDefName != null) { currentStateOutput.setResourceStateModelDef(resourceName, stateModelDefName); } currentStateOutput.setBucketSize(resourceName, currentState.getBucketSize()); Map<String, String> partitionStateMap = currentState.getPartitionStateMap(); for (String partitionName : partitionStateMap.keySet()) { Partition partition = resource.getPartition(partitionName); if (partition != null) { currentStateOutput.setCurrentState(resourceName, partition, instanceName, currentState.getState(partitionName)); currentStateOutput.setRequestedState(resourceName, partition, instanceName, currentState.getRequestedState(partitionName)); currentStateOutput.setInfo(resourceName, partition, instanceName, currentState.getInfo(partitionName)); } } } } return currentStateOutput; } }
pinot-controller/src/main/java/com/linkedin/pinot/controller/helix/Rebalancer.java
/** * Copyright (C) 2014-2015 LinkedIn Corp. ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.controller.helix; import com.linkedin.pinot.controller.helix.core.UAutoRebalancer; import org.apache.helix.*; import org.apache.helix.controller.pipeline.StageException; import org.apache.helix.controller.stages.CurrentStateOutput; import org.apache.helix.manager.zk.ZKHelixDataAccessor; import org.apache.helix.manager.zk.ZNRecordSerializer; import org.apache.helix.manager.zk.ZkBaseDataAccessor; import org.apache.helix.manager.zk.ZkClient; import org.apache.helix.model.*; import org.apache.helix.util.HelixUtil; import org.apache.log4j.Logger; import java.util.*; import java.util.concurrent.TimeUnit; /** * */ public class Rebalancer { private static Logger logger = Logger.getLogger(Rebalancer.class); private static ZkClient _zkClient; private static UAutoRebalancer _rebalancer; public Rebalancer(String zkAddress){ _zkClient = new ZkClient(zkAddress, 30 * 1000); _zkClient.setZkSerializer(new ZNRecordSerializer()); _zkClient.waitUntilConnected(30, TimeUnit.SECONDS); _rebalancer = new UAutoRebalancer(); } public void rebalance(String clusterName, String resourceName, int replica) { rebalance(clusterName, resourceName, replica, resourceName, ""); } public void rebalance(String clusterName, String resourceName, int replica, String keyPrefix, String group) { List<String> instanceNames = new LinkedList<String>(); if (keyPrefix == null || keyPrefix.length() == 0) { keyPrefix = resourceName; } if (group != null && group.length() > 0) { instanceNames = getInstancesInClusterWithTag(clusterName, group); } if (instanceNames.size() == 0) { logger.info("No tags found for resource " + resourceName + ", use all instances"); instanceNames = getInstancesInCluster(clusterName); group = ""; } else { logger.info("Found instances with tag for " + resourceName + " " + instanceNames); } rebalance(clusterName, resourceName, replica, keyPrefix, instanceNames, group); } public void rebalance(String clusterName, String resourceName, int replica, List<String> instances) { rebalance(clusterName, resourceName, replica, resourceName, instances, ""); } void rebalance(String clusterName, String resourceName, int replica, String keyPrefix, List<String> instanceNames, String groupId) { // ensure we get the same idealState with the same set of instances Collections.sort(instanceNames); IdealState idealState = getResourceIdealState(clusterName, resourceName); if (idealState == null) { throw new HelixException("Resource: " + resourceName + " has NOT been added yet"); } logger.info("###ideal state is : "+idealState.toString()); if (groupId != null && groupId.length() > 0) { idealState.setInstanceGroupTag(groupId); } idealState.setReplicas(Integer.toString(replica)); int partitions = idealState.getNumPartitions(); String stateModelName = idealState.getStateModelDefRef(); StateModelDefinition stateModDef = getStateModelDef(clusterName, stateModelName); if (stateModDef == null) { throw new HelixException("cannot find state model: " + stateModelName); } // StateModelDefinition def = new StateModelDefinition(stateModDef); List<String> statePriorityList = stateModDef.getStatesPriorityList(); String masterStateValue = null; String slaveStateValue = null; replica--; for (String state : statePriorityList) { String count = stateModDef.getNumInstancesPerState(state); if (count.equals("1")) { if (masterStateValue != null) { throw new HelixException("Invalid or unsupported state model definition"); } masterStateValue = state; } else if (count.equalsIgnoreCase("R")) { if (slaveStateValue != null) { throw new HelixException("Invalid or unsupported state model definition"); } slaveStateValue = state; } else if (count.equalsIgnoreCase("N")) { if (!(masterStateValue == null && slaveStateValue == null)) { throw new HelixException("Invalid or unsupported state model definition"); } replica = instanceNames.size() - 1; masterStateValue = slaveStateValue = state; } } if (masterStateValue == null && slaveStateValue == null) { throw new HelixException("Invalid or unsupported state model definition"); } if (masterStateValue == null) { masterStateValue = slaveStateValue; } IdealState newIdealState = null; if (idealState.getRebalanceMode() != IdealState.RebalanceMode.FULL_AUTO && idealState.getRebalanceMode() != IdealState.RebalanceMode.USER_DEFINED) { logger.info("#### Into rebalance mode"); logger.info("get live instance :"+getLiveInstances(clusterName)); logger.info("get instance config map :"+getInstanceConfigMap(clusterName)); logger.info("get current state output "+ computeCurrentStateOutput(clusterName)); newIdealState = _rebalancer.computeNewIdealState(resourceName,idealState,stateModDef, getLiveInstances(clusterName),getInstanceConfigMap(clusterName),computeCurrentStateOutput(clusterName)); } else { for (int i = 0; i < partitions; i++) { String partitionName = keyPrefix + "_" + i; newIdealState.getRecord().setMapField(partitionName, new HashMap<String, String>()); newIdealState.getRecord().setListField(partitionName, new ArrayList<String>()); } } logger.info("new ideal state is : "+ newIdealState.toString()); setResourceIdealState(clusterName, resourceName, newIdealState); } public Map<String,LiveInstance> getLiveInstances(String clusterName){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.liveInstances()); } public Map<String,InstanceConfig> getInstanceConfigMap(String clusterName){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.instanceConfigs()); } public Map<String,IdealState> getIdealStates(String clusterName){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.idealStates()); } public IdealState getResourceIdealState(String clusterName, String resourceName) { HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getProperty(keyBuilder.idealStates(resourceName)); } public void setResourceIdealState(String clusterName, String resourceName, IdealState idealState) { HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); accessor.setProperty(keyBuilder.idealStates(resourceName), idealState); } public StateModelDefinition getStateModelDef(String clusterName, String stateModelName) { HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getProperty(keyBuilder.stateModelDef(stateModelName)); } public List<String> getInstancesInClusterWithTag(String clusterName, String tag) { String memberInstancesPath = HelixUtil.getMemberInstancesPath(clusterName); List<String> instances = _zkClient.getChildren(memberInstancesPath); List<String> result = new ArrayList<String>(); HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); for (String instanceName : instances) { InstanceConfig config = accessor.getProperty(keyBuilder.instanceConfig(instanceName)); if (config.containsTag(tag)) { result.add(instanceName); } } return result; } public List<String> getInstancesInCluster(String clusterName) { String memberInstancesPath = HelixUtil.getMemberInstancesPath(clusterName); return _zkClient.getChildren(memberInstancesPath); } public Map<String, Message> getInstanceMessage (String clusterName,String instanceName){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.messages(instanceName)); } public Map<String, CurrentState> getCurrentState (String clusterName,String instanceName,String clientSessionId){ HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); return accessor.getChildValuesMap(keyBuilder.currentStates(instanceName, clientSessionId)); } public Map<String,Resource> getResourceMap(String clusterName){ Map<String, IdealState> idealStates = getIdealStates(clusterName); Map<String, Resource> resourceMap = new LinkedHashMap<String, Resource>(); if (idealStates != null && idealStates.size() > 0) { for (IdealState idealState : idealStates.values()) { Set<String> partitionSet = idealState.getPartitionSet(); String resourceName = idealState.getResourceName(); if (!resourceMap.containsKey(resourceName)) { Resource resource = new Resource(resourceName); resourceMap.put(resourceName, resource); resource.setStateModelDefRef(idealState.getStateModelDefRef()); resource.setStateModelFactoryName(idealState.getStateModelFactoryName()); resource.setBucketSize(idealState.getBucketSize()); resource.setBatchMessageMode(idealState.getBatchMessageMode()); } for (String partition : partitionSet) { addPartition(partition, resourceName, resourceMap); } } } Map<String, LiveInstance> availableInstances = getLiveInstances(clusterName); if (availableInstances != null && availableInstances.size() > 0) { for (LiveInstance instance : availableInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getSessionId(); Map<String, CurrentState> currentStateMap = getCurrentState(clusterName, instanceName, clientSessionId); if (currentStateMap == null || currentStateMap.size() == 0) { continue; } for (CurrentState currentState : currentStateMap.values()) { String resourceName = currentState.getResourceName(); Map<String, String> resourceStateMap = currentState.getPartitionStateMap(); if (resourceStateMap.keySet().isEmpty()) { // don't include empty current state for dropped resource continue; } // don't overwrite ideal state settings if (!resourceMap.containsKey(resourceName)) { addResource(resourceName, resourceMap); Resource resource = resourceMap.get(resourceName); resource.setStateModelDefRef(currentState.getStateModelDefRef()); resource.setStateModelFactoryName(currentState.getStateModelFactoryName()); resource.setBucketSize(currentState.getBucketSize()); resource.setBatchMessageMode(currentState.getBatchMessageMode()); } if (currentState.getStateModelDefRef() == null) { logger.error("state model def is null." + "resource:" + currentState.getResourceName() + ", partitions: " + currentState.getPartitionStateMap().keySet() + ", states: " + currentState.getPartitionStateMap().values()); try { throw new StageException("State model def is null for resource:" + currentState.getResourceName()); } catch (StageException e) { e.printStackTrace(); } } for (String partition : resourceStateMap.keySet()) { addPartition(partition, resourceName, resourceMap); } } } } return resourceMap; } private void addResource(String resource, Map<String, Resource> resourceMap) { if (resource == null || resourceMap == null) { return; } if (!resourceMap.containsKey(resource)) { resourceMap.put(resource, new Resource(resource)); } } private void addPartition(String partition, String resourceName, Map<String, Resource> resourceMap) { if (resourceName == null || partition == null || resourceMap == null) { return; } if (!resourceMap.containsKey(resourceName)) { resourceMap.put(resourceName, new Resource(resourceName)); } Resource resource = resourceMap.get(resourceName); resource.addPartition(partition); } public CurrentStateOutput computeCurrentStateOutput(String clusterName){ Map<String, Resource> resourceMap = getResourceMap(clusterName); Map<String, LiveInstance> liveInstances = getLiveInstances(clusterName); CurrentStateOutput currentStateOutput = new CurrentStateOutput(); for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); Map<String, Message> instanceMessages = getInstanceMessage(clusterName,instanceName); for (Message message : instanceMessages.values()) { if (!Message.MessageType.STATE_TRANSITION.toString().equalsIgnoreCase(message.getMsgType())) { continue; } if (!instance.getSessionId().equals(message.getTgtSessionId())) { continue; } String resourceName = message.getResourceName(); Resource resource = resourceMap.get(resourceName); if (resource == null) { continue; } if (!message.getBatchMessageMode()) { String partitionName = message.getPartitionName(); Partition partition = resource.getPartition(partitionName); if (partition != null) { currentStateOutput.setPendingState(resourceName, partition, instanceName, message); } else { // log } } else { List<String> partitionNames = message.getPartitionNames(); if (!partitionNames.isEmpty()) { for (String partitionName : partitionNames) { Partition partition = resource.getPartition(partitionName); if (partition != null) { currentStateOutput.setPendingState(resourceName, partition, instanceName, message); } else { // log } } } } } } for (LiveInstance instance : liveInstances.values()) { String instanceName = instance.getInstanceName(); String clientSessionId = instance.getSessionId(); Map<String, CurrentState> currentStateMap =getCurrentState(clusterName,instanceName,clientSessionId); for (CurrentState currentState : currentStateMap.values()) { if (!instance.getSessionId().equals(currentState.getSessionId())) { continue; } String resourceName = currentState.getResourceName(); String stateModelDefName = currentState.getStateModelDefRef(); Resource resource = resourceMap.get(resourceName); if (resource == null) { continue; } if (stateModelDefName != null) { currentStateOutput.setResourceStateModelDef(resourceName, stateModelDefName); } currentStateOutput.setBucketSize(resourceName, currentState.getBucketSize()); Map<String, String> partitionStateMap = currentState.getPartitionStateMap(); for (String partitionName : partitionStateMap.keySet()) { Partition partition = resource.getPartition(partitionName); if (partition != null) { currentStateOutput.setCurrentState(resourceName, partition, instanceName, currentState.getState(partitionName)); currentStateOutput.setRequestedState(resourceName, partition, instanceName, currentState.getRequestedState(partitionName)); currentStateOutput.setInfo(resourceName, partition, instanceName, currentState.getInfo(partitionName)); } } } } return currentStateOutput; } }
note rebalancer.java
pinot-controller/src/main/java/com/linkedin/pinot/controller/helix/Rebalancer.java
note rebalancer.java
<ide><path>inot-controller/src/main/java/com/linkedin/pinot/controller/helix/Rebalancer.java <ide> import java.util.concurrent.TimeUnit; <ide> <ide> /** <del> * <add> * In this class , we rebuild many env parameters for UAutoRebalancer to calculate new idealstate <ide> */ <ide> <ide> public class Rebalancer { <ide> _zkClient.setZkSerializer(new ZNRecordSerializer()); <ide> _zkClient.waitUntilConnected(30, TimeUnit.SECONDS); <ide> _rebalancer = new UAutoRebalancer(); <add> // Here no need to init especially helixmanager <ide> } <ide> <ide> public void rebalance(String clusterName, String resourceName, int replica) { <ide> if (idealState == null) { <ide> throw new HelixException("Resource: " + resourceName + " has NOT been added yet"); <ide> } <del> logger.info("###ideal state is : "+idealState.toString()); <add>// logger.info("###ideal state is : "+idealState.toString()); <ide> if (groupId != null && groupId.length() > 0) { <ide> idealState.setInstanceGroupTag(groupId); <ide> } <ide> IdealState newIdealState = null; <ide> if (idealState.getRebalanceMode() != IdealState.RebalanceMode.FULL_AUTO <ide> && idealState.getRebalanceMode() != IdealState.RebalanceMode.USER_DEFINED) { <del> logger.info("#### Into rebalance mode"); <del> logger.info("get live instance :"+getLiveInstances(clusterName)); <del> logger.info("get instance config map :"+getInstanceConfigMap(clusterName)); <del> logger.info("get current state output "+ computeCurrentStateOutput(clusterName)); <add>// logger.info("#### Into rebalance mode"); <add>// logger.info("get live instance :"+getLiveInstances(clusterName)); <add>// logger.info("get instance config map :"+getInstanceConfigMap(clusterName)); <add>// logger.info("get current state output "+ computeCurrentStateOutput(clusterName)); <ide> newIdealState = _rebalancer.computeNewIdealState(resourceName,idealState,stateModDef, <ide> getLiveInstances(clusterName),getInstanceConfigMap(clusterName),computeCurrentStateOutput(clusterName)); <ide> <ide> newIdealState.getRecord().setListField(partitionName, new ArrayList<String>()); <ide> } <ide> } <del> logger.info("new ideal state is : "+ newIdealState.toString()); <add>// logger.info("new ideal state is : "+ newIdealState.toString()); <ide> setResourceIdealState(clusterName, resourceName, newIdealState); <ide> } <ide> <add> /** <add> * Get LiveInstances by clusterName <add> * @param clusterName <add> * @return <add> */ <ide> public Map<String,LiveInstance> getLiveInstances(String clusterName){ <ide> HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,new ZkBaseDataAccessor<ZNRecord>(_zkClient)); <ide> PropertyKey.Builder keyBuilder = accessor.keyBuilder(); <ide> return accessor.getChildValuesMap(keyBuilder.liveInstances()); <ide> } <ide> <add> /** <add> * Get Instance Configs <add> * @param clusterName <add> * @return <add> */ <ide> public Map<String,InstanceConfig> getInstanceConfigMap(String clusterName){ <ide> HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,new ZkBaseDataAccessor<ZNRecord>(_zkClient)); <ide> PropertyKey.Builder keyBuilder = accessor.keyBuilder(); <ide> return accessor.getChildValuesMap(keyBuilder.instanceConfigs()); <ide> } <ide> <add> /** <add> * Get IdealState <add> * @param clusterName <add> * @return <add> */ <ide> public Map<String,IdealState> getIdealStates(String clusterName){ <ide> HelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName,new ZkBaseDataAccessor<ZNRecord>(_zkClient)); <ide> PropertyKey.Builder keyBuilder = accessor.keyBuilder(); <ide> return accessor.getChildValuesMap(keyBuilder.idealStates()); <ide> } <ide> <add> /** <add> * Get Resource IdealState <add> * @param clusterName <add> * @param resourceName <add> * @return <add> */ <ide> public IdealState getResourceIdealState(String clusterName, String resourceName) { <ide> HelixDataAccessor accessor = <ide> new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); <ide> return accessor.getProperty(keyBuilder.idealStates(resourceName)); <ide> } <ide> <add> /** <add> * Set Resource IdealState <add> * @param clusterName <add> * @param resourceName <add> * @param idealState <add> */ <ide> public void setResourceIdealState(String clusterName, String resourceName, IdealState idealState) { <ide> HelixDataAccessor accessor = <ide> new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); <ide> accessor.setProperty(keyBuilder.idealStates(resourceName), idealState); <ide> } <ide> <add> /** <add> * Get State model Def <add> * @param clusterName <add> * @param stateModelName <add> * @return <add> */ <ide> public StateModelDefinition getStateModelDef(String clusterName, String stateModelName) { <ide> HelixDataAccessor accessor = <ide> new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); <ide> return accessor.getProperty(keyBuilder.stateModelDef(stateModelName)); <ide> } <ide> <add> /** <add> * Get Instances with Tag <add> * @param clusterName <add> * @param tag <add> * @return <add> */ <ide> public List<String> getInstancesInClusterWithTag(String clusterName, String tag) { <ide> String memberInstancesPath = HelixUtil.getMemberInstancesPath(clusterName); <ide> List<String> instances = _zkClient.getChildren(memberInstancesPath); <ide> return result; <ide> } <ide> <del> <add> /** <add> * Get all instances <add> * @param clusterName <add> * @return <add> */ <ide> public List<String> getInstancesInCluster(String clusterName) { <ide> String memberInstancesPath = HelixUtil.getMemberInstancesPath(clusterName); <ide> return _zkClient.getChildren(memberInstancesPath); <ide> } <ide> <ide> <add> /** <add> * Get Instance Message <add> * @param clusterName <add> * @param instanceName <add> * @return <add> */ <ide> public Map<String, Message> getInstanceMessage (String clusterName,String instanceName){ <ide> HelixDataAccessor accessor = <ide> new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); <ide> return accessor.getChildValuesMap(keyBuilder.messages(instanceName)); <ide> } <ide> <add> <add> /** <add> * Get Instance CurrentState <add> * @param clusterName <add> * @param instanceName <add> * @param clientSessionId <add> * @return <add> */ <ide> public Map<String, CurrentState> getCurrentState (String clusterName,String instanceName,String clientSessionId){ <ide> HelixDataAccessor accessor = <ide> new ZKHelixDataAccessor(clusterName, new ZkBaseDataAccessor<ZNRecord>(_zkClient)); <ide> return accessor.getChildValuesMap(keyBuilder.currentStates(instanceName, clientSessionId)); <ide> } <ide> <add> /** <add> * Get Resource Map <add> * @param clusterName <add> * @return <add> */ <ide> public Map<String,Resource> getResourceMap(String clusterName){ <ide> Map<String, IdealState> idealStates = getIdealStates(clusterName); <ide> <ide> <ide> } <ide> <del> <add> /** <add> * Compute CurrentStateOutput , the same as CurrentStateComputationStage.java <add> * @param clusterName <add> * @return <add> */ <ide> public CurrentStateOutput computeCurrentStateOutput(String clusterName){ <ide> <ide> Map<String, Resource> resourceMap = getResourceMap(clusterName);
JavaScript
mit
e9b57fca5fba69595fd08d8f2b6e4494254b047f
0
zen-audio-player/zen-audio-player.github.io,Ab1d/zen-audio-player.github.io,monicacheung/zen-audio-player.github.io,zen-audio-player/zen-audio-player.github.io,monicacheung/zen-audio-player.github.io,Ab1d/zen-audio-player.github.io,divayprakash/zen-audio-player.github.io,divayprakash/zen-audio-player.github.io
function getParameterByName(url, name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(url); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } function getCurrentVideoID() { var v = getParameterByName(window.location.search, "v"); if (v.length > 0) { return parseYoutubeVideoID(v); } return v; } function makeYoutubeEmbedURL(videoID) { var head = "http://www.youtube.com/embed/"; var tail = "?enablejsapi=1&origin=http://shakeelmohamed.com&autoplay=1"; if (videoID) { return head + videoID + tail; } else { // Swallow error console.log("The videoID in makeYoutubeEmbedURL was bad"); } } function makeListenURL(videoID) { var url = window.location.href; if (window.location.search.length !== 0) { url = window.location.href.replace(window.location.search, ""); } return url + "?v=" + videoID; } // The url parameter could be the video ID function parseYoutubeVideoID(url) { var videoID = null; var shortUrlDomain = "youtu.be"; var longUrlDomain = "youtube.com"; if (url) { // youtube.com format if (url.indexOf(longUrlDomain) !== -1) { videoID = getParameterByName(url, "v"); } // youtu.be format else if (url.indexOf(shortUrlDomain) !== -1) { var endPosition = url.indexOf("?") === -1 ? url.length : url.indexOf("?"); var offset = url.indexOf(shortUrlDomain) + shortUrlDomain.length + 1; // Skip over the slash also videoID = url.substring(offset, endPosition); } // Assume YouTube video ID string else { videoID = url; } return videoID; } alert("Failed to parse the video ID."); } $(function() { // Parse the querystring and populate the video when loading the page var currentVideoID = getCurrentVideoID(); if (currentVideoID) { $("#player").attr("src", makeYoutubeEmbedURL(currentVideoID)); $("#query").attr("value", currentVideoID); } // Handle form submission $("#form").submit(function(event) { event.preventDefault(); var formValue = $("#query").val(); if (formValue) { var videoID = parseYoutubeVideoID(formValue); window.location.href = makeListenURL(videoID); } else { alert("Try entering a YouTube video id or URL!"); } }); }); // Google Analytics goodness (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-36907845-2', 'shakeelmohamed.com'); ga('require', 'displayfeatures'); ga('send', 'pageview');
js/everything.js
function getParameterByName(url, name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(url); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } function getCurrentVideoID() { var v = getParameterByName(window.location.search, "v"); if (v.length > 0) { return parseYoutubeVideoID(v); } return v; } function makeYoutubeEmbedURL(videoID) { var head = "http://www.youtube.com/embed/"; var tail = "?enablejsapi=1&origin=shakeelmohamed.com&autoplay=1"; if (videoID) { return head + videoID + tail; } else { // Swallow error console.log("The videoID in makeYoutubeEmbedURL was bad"); } } function makeListenURL(videoID) { var url = window.location.href; if (window.location.search.length !== 0) { url = window.location.href.replace(window.location.search, ""); } return url + "?v=" + videoID; } // The url parameter could be the video ID function parseYoutubeVideoID(url) { var videoID = null; var shortUrlDomain = "youtu.be"; var longUrlDomain = "youtube.com"; if (url) { // youtube.com format if (url.indexOf(longUrlDomain) !== -1) { videoID = getParameterByName(url, "v"); } // youtu.be format else if (url.indexOf(shortUrlDomain) !== -1) { var endPosition = url.indexOf("?") === -1 ? url.length : url.indexOf("?"); var offset = url.indexOf(shortUrlDomain) + shortUrlDomain.length + 1; // Skip over the slash also videoID = url.substring(offset, endPosition); } // Assume YouTube video ID string else { videoID = url; } return videoID; } alert("Failed to parse the video ID."); } $(function() { // Parse the querystring and populate the video when loading the page var currentVideoID = getCurrentVideoID(); if (currentVideoID) { $("#player").attr("src", makeYoutubeEmbedURL(currentVideoID)); $("#query").attr("value", currentVideoID); } // Handle form submission $("#form").submit(function(event) { event.preventDefault(); var formValue = $("#query").val(); if (formValue) { var videoID = parseYoutubeVideoID(formValue); window.location.href = makeListenURL(videoID); } else { alert("Try entering a YouTube video id or URL!"); } }); }); // Google Analytics goodness (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-36907845-2', 'shakeelmohamed.com'); ga('require', 'displayfeatures'); ga('send', 'pageview');
try full domain
js/everything.js
try full domain
<ide><path>s/everything.js <ide> <ide> function makeYoutubeEmbedURL(videoID) { <ide> var head = "http://www.youtube.com/embed/"; <del> var tail = "?enablejsapi=1&origin=shakeelmohamed.com&autoplay=1"; <add> var tail = "?enablejsapi=1&origin=http://shakeelmohamed.com&autoplay=1"; <ide> if (videoID) { <ide> return head + videoID + tail; <ide> }
JavaScript
mit
b9f0fe2d34ac72983acde523f2dfa4074e339774
0
maritz/nohm-admin,maritz/nohm-admin
_r(function (app) { if ( ! window.app.views.hasOwnProperty('user')) { app.views.user = {}; } /** * #/user/index */ app.views.user.index = app.base.listView.extend({ collection: app.collections.User, auto_render: true }); /** * #/user/register */ app.views.user.register = app.base.formView.extend({ auto_render: true, model: app.models.User, max_age: 0, wait_for_user_loaded: false, reload_on_login: true, requires_login: false, render: function () { if (app.user_self.get('name')) { app.back(); } else { app.base.formView.prototype.render.apply(this, _.toArray(arguments)); } }, saved: function () { this.reload_on_login = false; // we only want to reload if the login is not from here. app.once('user_loaded', function () { app.go('user/profile/'); app.trigger('login'); }); app.user_self.load(); } }); /** * #/user/profile */ app.views.user.profile = app.base.pageView.extend({ auto_render: true, model: app.models.User, load: function (callback) { var self = this; var id = this.params[0] || app.user_self.id; this.model.set({'id': id}); this.model.fetch() .always(function (res) { callback(res.status >= 400, self.model); }); } }); /** * #/user/edit_profile(/:id) */ app.views.user.edit_profile = app.base.formView.extend({ auto_render: true, model: app.models.User, max_age: 0, edit_is_self: false, events: { 'click form.acl label a': 'markAclInputs', 'change .acl :checkbox': 'changeAcl', 'change .admin :checkbox': 'changeAdmin' }, init: function () { var default_acl = ['view', 'list', 'create', 'edit', 'delete']; this.addLocals({ acl: { 'User': ['self'].concat(default_acl.concat(['grant'])) } }); }, load: function (callback) { if (this.params[0] && app.user_self.may('edit', 'User')) { this.model.id = this.params[0]; } else { this.model.id = app.user_self.id; this.edit_is_self = true; } this.model.fetch(function (user, response) { callback(null, user); }); }, saved: function () { if (this.edit_is_self) { app.user_self.set(this.model.toJSON()); } app.go('user/profile/'+this.model.id); }, markAclInputs: function (e) { var $target = $(e.target); var boxes = $target.closest('.control-group').find(':checkbox'); if ($target.hasClass('setRead')) { boxes .filter('[data-action="view"], [data-action="list"]') .click(); } if ($target.hasClass('setWrite')) { boxes .filter('[data-action="create"], [data-action="edit"], [data-action="delete"]') .click(); } }, getChangeCallback: function ($target, checked) { return function (err) { var class_name = 'success_blink'; if (err) { class_name = 'error_blink'; $target.prop('checked', !checked); } var $parent = $target.parent().addClass(class_name); setTimeout(function () { $target.attr('disabled', false); $parent.removeClass(class_name); }, 500); }; }, changeAcl: function (e) { var $target = $(e.target); var checked = $target.prop('checked'); var allow_or_deny = checked ? 'allow' : 'deny'; $target.attr('disabled', true); this.model.changeAcl(allow_or_deny, $target.data('action'), $target.data('subject'), this.getChangeCallback($target, checked)); }, changeAdmin: function (e) { var self = this; var $target = $(e.target); var checked = $target.prop('checked'); var name = this.model.get('name'); var done = self.getChangeCallback($target, checked); var cancel = function () { $target.prop('checked', !checked); $target.attr('disabled', false); }; $target.attr('disabled', true); if ( ! checked) { if (this.model.id === app.user_self.id) { app.overlay({ view: 'confirm_take_self_admin', locals: { text: this._t('admin.self_warning') }, confirm: function () { self.model.changeAdmin(false, done); }, cancel: cancel }); } else { self.model.changeAdmin(false, done); } } else { app.overlay({ view: 'confirm_grant_admin', locals: { text: this._t(['admin.grant_warning', name]) }, confirm: function () { self.model.changeAdmin(true, done); }, cancel: cancel }); } } }); /** * #/user/login or manual call */ app.views.user.login = app.base.formView.extend({ model: app.models.Self, auto_render: true, max_age: 0, wait_for_user_loaded: false, requires_login: false, reload_on_login: false, /** * Login successful */ saved: function () { $.jGrowl('Login successful'); app.user_self.set(this.model.toJSON()); if (app.current.view instanceof app.views.user.login) { app.go('#'); } else { app.closeOverlay(); } app.trigger('login'); } }); /** * #/user/logout */ app.views.user.logout = app.base.pageView.extend({ init: function () { if (app.user_self) { app.user_self.logout(); } } }); /** * Userbox */ app.views.userbox = app.base.pageView.extend({ requires_login: false, model: app.user_self, module: 'user', action: 'userbox', $el: $('#userbox'), auto_render: true, init: function () { this.model.bind('change:name', this.render); }, load: function (callback) { callback(null, app.user_self); } }); });
static/js/views/userView.js
_r(function (app) { if ( ! window.app.views.hasOwnProperty('user')) { app.views.user = {}; } /** * #/user/index */ app.views.user.index = app.base.listView.extend({ collection: app.collections.User, auto_render: true }); /** * #/user/register */ app.views.user.register = app.base.formView.extend({ auto_render: true, model: app.models.User, max_age: 0, wait_for_user_loaded: false, reload_on_login: true, requires_login: false, render: function () { if (app.user_self.get('name')) { app.back(); } else { app.base.formView.prototype.render.apply(this, _.toArray(arguments)); } }, saved: function () { this.reload_on_login = false; // we only want to reload if the login is not from here. app.once('user_loaded', function () { app.go('user/profile/'); app.trigger('login'); }); app.user_self.load(); } }); /** * #/user/profile */ app.views.user.profile = app.base.pageView.extend({ auto_render: true, model: app.models.User, load: function (callback) { var self = this; var id = this.params[0] || app.user_self.id; this.model.set({'id': id}); this.model.fetch() .always(function (res) { callback(res.status >= 400, self.model); }); } }); /** * #/user/edit_profile(/:id) */ app.views.user.edit_profile = app.base.formView.extend({ auto_render: true, model: app.models.User, max_age: 0, edit_is_self: false, events: { 'click form.acl label a': 'markAclInputs', 'change .acl :checkbox': 'changeAcl', 'change .admin :checkbox': 'changeAdmin' }, init: function () { var default_acl = ['view', 'list', 'create', 'edit', 'delete']; this.addLocals({ acl: { 'User': ['self'].concat(default_acl.concat(['grant'])) } }); }, load: function (callback) { if (this.params[0] && app.user_self.may('edit', 'User')) { this.model.id = this.params[0]; } else { this.model.id = app.user_self.id; this.edit_is_self = true; } this.model.fetch(function (user, response) { callback(null, user); }); }, saved: function () { if (this.edit_is_self) { app.user_self.set(this.model.toJSON()); } app.go('user/profile/'+this.model.id); }, markAclInputs: function (e) { var $target = $(e.target); var boxes = $target.closest('.control-group').find(':checkbox'); if ($target.hasClass('setRead')) { boxes .filter('[data-action="view"], [data-action="list"]') .click(); } if ($target.hasClass('setWrite')) { boxes .filter('[data-action="create"], [data-action="edit"], [data-action="delete"]') .click(); } }, getChangeCallback: function ($target, checked) { return function (err) { var class_name = 'success_blink'; if (err) { class_name = 'error_blink'; $target.prop('checked', !checked); } var $parent = $target.parent().addClass(class_name); setTimeout(function () { $target.attr('disabled', false); $parent.removeClass(class_name); }, 500); }; }, changeAcl: function (e) { var $target = $(e.target); var checked = $target.prop('checked'); var allow_or_deny = checked ? 'allow' : 'deny'; $target.attr('disabled', true); this.model.changeAcl(allow_or_deny, $target.data('action'), $target.data('subject'), this.getChangeCallback($target, checked)); }, changeAdmin: function (e) { var self = this; var $target = $(e.target); var checked = $target.prop('checked'); var name = this.model.get('name'); var done = self.getChangeCallback($target, checked); var cancel = function () { $target.prop('checked', !checked); $target.attr('disabled', false); }; $target.attr('disabled', true); if ( ! checked) { if (this.model.id === app.user_self.id) { app.overlay({ view: 'confirm_take_self_admin', locals: { text: this._t('admin.self_warning') }, confirm: function () { self.model.changeAdmin(false, done); }, cancel: cancel }); } else { self.model.changeAdmin(false, done); } } else { app.overlay({ view: 'confirm_grant_admin', locals: { text: this._t(['admin.grant_warning', name]) }, confirm: function () { self.model.changeAdmin(true, done); }, cancel: cancel }); } } }); /** * #/user/login or manual call */ app.views.user.login = app.base.formView.extend({ model: app.models.Self, auto_render: true, max_age: 0, wait_for_user_loaded: false, requires_login: false, reload_on_login: false, /** * Login successful */ saved: function () { $.jGrowl('Login successful'); app.user_self.set(this.model.toJSON()); app.trigger('login'); if (app.current.view instanceof app.views.user.login) { app.go('#'); } } }); /** * #/user/logout */ app.views.user.logout = app.base.pageView.extend({ init: function () { if (app.user_self) { app.user_self.logout(); } } }); /** * Userbox */ app.views.userbox = app.base.pageView.extend({ requires_login: false, model: app.user_self, module: 'user', action: 'userbox', $el: $('#userbox'), auto_render: true, init: function () { this.model.bind('change:name', this.render); }, load: function (callback) { callback(null, app.user_self); } }); });
Fix login overlay not being closed on login
static/js/views/userView.js
Fix login overlay not being closed on login
<ide><path>tatic/js/views/userView.js <ide> saved: function () { <ide> $.jGrowl('Login successful'); <ide> app.user_self.set(this.model.toJSON()); <del> app.trigger('login'); <ide> <ide> if (app.current.view instanceof app.views.user.login) { <ide> app.go('#'); <del> } <add> } else { <add> app.closeOverlay(); <add> } <add> <add> app.trigger('login'); <ide> } <ide> <ide> });
JavaScript
mit
0a6aec0ee1621e316d0f8a24dca441a91aba1cd9
0
timbl/rdflib.js,timbl/rdflib.js,timbl/rdflib.js
/************************************************************ * * Project: rdflib.js, originally part of Tabulator project * * File: web.js * * Description: contains functions for requesting/fetching/retracting * This implements quite a lot of the web architecture. * A fetcher is bound to a specific knowledge base graph, into which * it loads stuff and into which it writes its metadata * @@ The metadata should be optionally a separate graph * * - implements semantics of HTTP headers, Internet Content Types * - selects parsers for rdf/xml, n3, rdfa, grddl * * Dependencies: * * needs: util.js uri.js term.js rdfparser.js rdfa.js n3parser.js * identity.js sparql.js jsonparser.js * * If jQuery is defined, it uses jQuery.ajax, else is independent of jQuery * ************************************************************/ /** * Things to test: callbacks on request, refresh, retract * loading from HTTP, HTTPS, FTP, FILE, others? * To do: * Firing up a mail client for mid: (message:) URLs */ if (typeof module !== 'undefined' && module.require) { // Node // For non-node, jasonld needs to be inlined in init.js etc $rdf.jsonld = require('jsonld'); N3 = require('n3'); asyncLib = require('async'); } $rdf.Fetcher = function(store, timeout, async) { this.store = store this.thisURI = "http://dig.csail.mit.edu/2005/ajar/ajaw/rdf/sources.js" + "#SourceFetcher" // -- Kenny this.timeout = timeout ? timeout : 30000 this.async = async != null ? async : true this.appNode = this.store.bnode(); // Denoting this session this.store.fetcher = this; //Bi-linked this.requested = {} this.lookedUp = {} this.handlers = [] this.mediatypes = {} var sf = this var kb = this.store; var ns = {} // Convenience namespaces needed in this module: // These are delibertely not exported as the user application should // make its own list and not rely on the prefixes used here, // and not be tempted to add to them, and them clash with those of another // application. ns.link = $rdf.Namespace("http://www.w3.org/2007/ont/link#"); ns.http = $rdf.Namespace("http://www.w3.org/2007/ont/http#"); ns.httph = $rdf.Namespace("http://www.w3.org/2007/ont/httph#"); ns.rdf = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); ns.rdfs = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"); ns.dc = $rdf.Namespace("http://purl.org/dc/elements/1.1/"); $rdf.Fetcher.crossSiteProxy = function(uri) { if ($rdf.Fetcher.crossSiteProxyTemplate) return $rdf.Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); else return undefined; }; $rdf.Fetcher.RDFXMLHandler = function(args) { if (args) { this.dom = args[0] } this.handlerFactory = function(xhr) { xhr.handle = function(cb) { //sf.addStatus(xhr.req, 'parsing soon as RDF/XML...'); var kb = sf.store; if (!this.dom) this.dom = $rdf.Util.parseXML(xhr.responseText); /* { var dparser; if ((typeof tabulator != 'undefined' && tabulator.isExtension)) { dparser = Components.classes["@mozilla.org/xmlextras/domparser;1"].getService(Components.interfaces.nsIDOMParser); } else { dparser = new DOMParser() } //strange things happen when responseText is empty this.dom = dparser.parseFromString(xhr.responseText, 'application/xml') } */ var root = this.dom.documentElement; if (root.nodeName == 'parsererror') { //@@ Mozilla only See issue/issue110 sf.failFetch(xhr, "Badly formed XML in " + xhr.resource.uri); //have to fail the request throw new Error("Badly formed XML in " + xhr.resource.uri); //@@ Add details } // Find the last URI we actual URI in a series of redirects // (xhr.resource.uri is the original one) var lastRequested = kb.any(xhr.req, ns.link('requestedURI')); if (!lastRequested) { lastRequested = xhr.resource; } else { lastRequested = kb.sym(lastRequested.value); } var parser = new $rdf.RDFParser(kb); // sf.addStatus(xhr.req, 'parsing as RDF/XML...'); parser.parse(this.dom, lastRequested.uri, lastRequested); kb.add(lastRequested, ns.rdf('type'), ns.link('RDFDocument'), sf.appNode); cb(); } } }; $rdf.Fetcher.RDFXMLHandler.term = this.store.sym(this.thisURI + ".RDFXMLHandler"); $rdf.Fetcher.RDFXMLHandler.toString = function() { return "RDFXMLHandler" }; $rdf.Fetcher.RDFXMLHandler.register = function(sf) { sf.mediatypes['application/rdf+xml'] = {} }; $rdf.Fetcher.RDFXMLHandler.pattern = new RegExp("application/rdf\\+xml"); // This would much better use on-board XSLT engine. @@ $rdf.Fetcher.doGRDDL = function(kb, doc, xslturi, xmluri) { sf.requestURI('http://www.w3.org/2005/08/' + 'online_xslt/xslt?' + 'xslfile=' + escape(xslturi) + '&xmlfile=' + escape(xmluri), doc) }; $rdf.Fetcher.XHTMLHandler = function(args) { if (args) { this.dom = args[0] } this.handlerFactory = function(xhr) { xhr.handle = function(cb) { if (!this.dom) { var dparser; if (typeof tabulator != 'undefined' && tabulator.isExtension) { dparser = Components.classes["@mozilla.org/xmlextras/domparser;1"].getService(Components.interfaces.nsIDOMParser); } else { dparser = new DOMParser() } this.dom = dparser.parseFromString(xhr.responseText, 'application/xml') } var kb = sf.store; // dc:title var title = this.dom.getElementsByTagName('title') if (title.length > 0) { kb.add(xhr.resource, ns.dc('title'), kb.literal(title[0].textContent), xhr.resource) // $rdf.log.info("Inferring title of " + xhr.resource) } // link rel var links = this.dom.getElementsByTagName('link'); for (var x = links.length - 1; x >= 0; x--) { sf.linkData(xhr, links[x].getAttribute('rel'), links[x].getAttribute('href')); } //GRDDL var head = this.dom.getElementsByTagName('head')[0] if (head) { var profile = head.getAttribute('profile'); if (profile && $rdf.uri.protocol(profile) == 'http') { // $rdf.log.info("GRDDL: Using generic " + "2003/11/rdf-in-xhtml-processor."); $rdf.Fetcher.doGRDDL(kb, xhr.resource, "http://www.w3.org/2003/11/rdf-in-xhtml-processor", xhr.resource.uri) /* sf.requestURI('http://www.w3.org/2005/08/' + 'online_xslt/xslt?' + 'xslfile=http://www.w3.org' + '/2003/11/' + 'rdf-in-xhtml-processor' + '&xmlfile=' + escape(xhr.resource.uri), xhr.resource) */ } else { // $rdf.log.info("GRDDL: No GRDDL profile in " + xhr.resource) } } kb.add(xhr.resource, ns.rdf('type'), ns.link('WebPage'), sf.appNode); // Do RDFa here if ($rdf.rdfa && $rdf.rdfa.parse) $rdf.rdfa.parse(this.dom, kb, xhr.resource.uri); cb(); // Fire done callbacks } } }; $rdf.Fetcher.XHTMLHandler.term = this.store.sym(this.thisURI + ".XHTMLHandler"); $rdf.Fetcher.XHTMLHandler.toString = function() { return "XHTMLHandler" }; $rdf.Fetcher.XHTMLHandler.register = function(sf) { sf.mediatypes['application/xhtml+xml'] = { 'q': 0.3 } }; $rdf.Fetcher.XHTMLHandler.pattern = new RegExp("application/xhtml"); /******************************************************/ $rdf.Fetcher.XMLHandler = function() { this.handlerFactory = function(xhr) { xhr.handle = function(cb) { var kb = sf.store var dparser; if (typeof tabulator != 'undefined' && tabulator.isExtension) { dparser = Components.classes["@mozilla.org/xmlextras/domparser;1"].getService(Components.interfaces.nsIDOMParser); } else { dparser = new DOMParser() } var dom = dparser.parseFromString(xhr.responseText, 'application/xml') // XML Semantics defined by root element namespace // figure out the root element for (var c = 0; c < dom.childNodes.length; c++) { // is this node an element? if (dom.childNodes[c].nodeType == 1) { // We've found the first element, it's the root var ns = dom.childNodes[c].namespaceURI; // Is it RDF/XML? if (ns != undefined && ns == ns['rdf']) { sf.addStatus(xhr.req, "Has XML root element in the RDF namespace, so assume RDF/XML.") sf.switchHandler('RDFXMLHandler', xhr, cb, [dom]) return } // it isn't RDF/XML or we can't tell // Are there any GRDDL transforms for this namespace? // @@ assumes ns documents have already been loaded var xforms = kb.each(kb.sym(ns), kb.sym("http://www.w3.org/2003/g/data-view#namespaceTransformation")); for (var i = 0; i < xforms.length; i++) { var xform = xforms[i]; // $rdf.log.info(xhr.resource.uri + " namespace " + ns + " has GRDDL ns transform" + xform.uri); $rdf.Fetcher.doGRDDL(kb, xhr.resource, xform.uri, xhr.resource.uri); } break } } // Or it could be XHTML? // Maybe it has an XHTML DOCTYPE? if (dom.doctype) { // $rdf.log.info("We found a DOCTYPE in " + xhr.resource) if (dom.doctype.name == 'html' && dom.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/) && dom.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)) { sf.addStatus(xhr.req,"Has XHTML DOCTYPE. Switching to XHTML Handler.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } } // Or what about an XHTML namespace? var html = dom.getElementsByTagName('html')[0] if (html) { var xmlns = html.getAttribute('xmlns') if (xmlns && xmlns.match(/^http:\/\/www.w3.org\/1999\/xhtml/)) { sf.addStatus(xhr.req, "Has a default namespace for " + "XHTML. Switching to XHTMLHandler.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } } // At this point we should check the namespace document (cache it!) and // look for a GRDDL transform // @@ Get namespace document <n>, parse it, look for <n> grddl:namespaceTransform ?y // Apply ?y to dom // We give up. What dialect is this? sf.failFetch(xhr, "Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n"+xhr.responseText.slice(0,80)); } } }; $rdf.Fetcher.XMLHandler.term = this.store.sym(this.thisURI + ".XMLHandler"); $rdf.Fetcher.XMLHandler.toString = function() { return "XMLHandler" }; $rdf.Fetcher.XMLHandler.register = function(sf) { sf.mediatypes['text/xml'] = { 'q': 0.2 } sf.mediatypes['application/xml'] = { 'q': 0.2 } }; $rdf.Fetcher.XMLHandler.pattern = new RegExp("(text|application)/(.*)xml"); $rdf.Fetcher.HTMLHandler = function() { this.handlerFactory = function(xhr) { xhr.handle = function(cb) { var rt = xhr.responseText // We only handle XHTML so we have to figure out if this is XML // $rdf.log.info("Sniffing HTML " + xhr.resource + " for XHTML."); if (rt.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)) { sf.addStatus(xhr.req, "Has an XML declaration. We'll assume " + "it's XHTML as the content-type was text/html.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } // DOCTYPE // There is probably a smarter way to do this if (rt.match(/.*<!DOCTYPE\s+html[^<]+-\/\/W3C\/\/DTD XHTML[^<]+http:\/\/www.w3.org\/TR\/xhtml[^<]+>/)) { sf.addStatus(xhr.req, "Has XHTML DOCTYPE. Switching to XHTMLHandler.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } // xmlns if (rt.match(/[^(<html)]*<html\s+[^<]*xmlns=['"]http:\/\/www.w3.org\/1999\/xhtml["'][^<]*>/)) { sf.addStatus(xhr.req, "Has default namespace for XHTML, so switching to XHTMLHandler.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } // dc:title //no need to escape '/' here var titleMatch = (new RegExp("<title>([\\s\\S]+?)</title>", 'im')).exec(rt); if (titleMatch) { var kb = sf.store; kb.add(xhr.resource, ns.dc('title'), kb.literal(titleMatch[1]), xhr.resource); //think about xml:lang later kb.add(xhr.resource, ns.rdf('type'), ns.link('WebPage'), sf.appNode); cb(); //doneFetch, not failed return; } sf.failFetch(xhr, "Sorry, can't yet parse non-XML HTML") } } }; $rdf.Fetcher.HTMLHandler.term = this.store.sym(this.thisURI + ".HTMLHandler"); $rdf.Fetcher.HTMLHandler.toString = function() { return "HTMLHandler" }; $rdf.Fetcher.HTMLHandler.register = function(sf) { sf.mediatypes['text/html'] = { 'q': 0.3 } }; $rdf.Fetcher.HTMLHandler.pattern = new RegExp("text/html"); /***********************************************/ $rdf.Fetcher.TextHandler = function() { this.handlerFactory = function(xhr) { xhr.handle = function(cb) { // We only speak dialects of XML right now. Is this XML? var rt = xhr.responseText // Look for an XML declaration if (rt.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)) { sf.addStatus(xhr.req, "Warning: "+xhr.resource + " has an XML declaration. We'll assume " + "it's XML but its content-type wasn't XML.\n") sf.switchHandler('XMLHandler', xhr, cb) return } // Look for an XML declaration if (rt.slice(0, 500).match(/xmlns:/)) { sf.addStatus(xhr.req, "May have an XML namespace. We'll assume " + "it's XML but its content-type wasn't XML.\n") sf.switchHandler('XMLHandler', xhr, cb) return } // We give up finding semantics - this is not an error, just no data sf.addStatus(xhr.req, "Plain text document, no known RDF semantics."); sf.doneFetch(xhr, [xhr.resource.uri]); // sf.failFetch(xhr, "unparseable - text/plain not visibly XML") // dump(xhr.resource + " unparseable - text/plain not visibly XML, starts:\n" + rt.slice(0, 500)+"\n") } } }; $rdf.Fetcher.TextHandler.term = this.store.sym(this.thisURI + ".TextHandler"); $rdf.Fetcher.TextHandler.toString = function() { return "TextHandler"; }; $rdf.Fetcher.TextHandler.register = function(sf) { sf.mediatypes['text/plain'] = { 'q': 0.1 } } $rdf.Fetcher.TextHandler.pattern = new RegExp("text/plain"); /***********************************************/ $rdf.Fetcher.N3Handler = function() { this.handlerFactory = function(xhr) { xhr.handle = function(cb) { // Parse the text of this non-XML file $rdf.log.debug("web.js: Parsing as N3 " + xhr.resource.uri); // @@@@ comment me out //sf.addStatus(xhr.req, "N3 not parsed yet...") var rt = xhr.responseText var p = $rdf.N3Parser(kb, kb, xhr.resource.uri, xhr.resource.uri, null, null, "", null) // p.loadBuf(xhr.responseText) try { p.loadBuf(xhr.responseText) } catch (e) { var msg = ("Error trying to parse " + xhr.resource + " as Notation3:\n" + e +':\n'+e.stack) // dump(msg+"\n") sf.failFetch(xhr, msg) return; } sf.addStatus(xhr.req, "N3 parsed: " + p.statementCount + " triples in " + p.lines + " lines.") sf.store.add(xhr.resource, ns.rdf('type'), ns.link('RDFDocument'), sf.appNode); args = [xhr.resource.uri]; // Other args needed ever? sf.doneFetch(xhr, args) } } }; $rdf.Fetcher.N3Handler.term = this.store.sym(this.thisURI + ".N3Handler"); $rdf.Fetcher.N3Handler.toString = function() { return "N3Handler"; } $rdf.Fetcher.N3Handler.register = function(sf) { sf.mediatypes['text/n3'] = { 'q': '1.0' } // as per 2008 spec sf.mediatypes['application/x-turtle'] = { 'q': 1.0 } // pre 2008 sf.mediatypes['text/turtle'] = { 'q': 1.0 } // pre 2008 } $rdf.Fetcher.N3Handler.pattern = new RegExp("(application|text)/(x-)?(rdf\\+)?(n3|turtle)") /***********************************************/ $rdf.Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail', 'refresh', 'retract', 'done']); this.addProtocol = function(proto) { sf.store.add(sf.appNode, ns.link("protocol"), sf.store.literal(proto), this.appNode) } this.addHandler = function(handler) { sf.handlers.push(handler) handler.register(sf) } this.switchHandler = function(name, xhr, cb, args) { var kb = this.store; var handler = null; for (var i=0; i<this.handlers.length; i++) { if (''+this.handlers[i] == name) { handler = this.handlers[i]; } } if (handler == undefined) { throw 'web.js: switchHandler: name='+name+' , this.handlers ='+this.handlers+'\n' + 'switchHandler: switching to '+handler+'; sf='+sf + '; typeof $rdf.Fetcher='+typeof $rdf.Fetcher + ';\n\t $rdf.Fetcher.HTMLHandler='+$rdf.Fetcher.HTMLHandler+'\n' + '\n\tsf.handlers='+sf.handlers+'\n' } (new handler(args)).handlerFactory(xhr); xhr.handle(cb) } this.addStatus = function(req, status) { //<Debug about="parsePerformance"> var now = new Date(); status = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "." + now.getMilliseconds() + "] " + status; //</Debug> var kb = this.store var s = kb.the(req, ns.link('status')); if (s && s.append) { s.append(kb.literal(status)); } else { $rdf.log.warn("web.js: No list to add to: " + s + ',' + status); // @@@ }; } // Record errors in the system on failure // Returns xhr so can just do return this.failfetch(...) this.failFetch = function(xhr, status) { this.addStatus(xhr.req, status) kb.add(xhr.resource, ns.link('error'), status) this.requested[$rdf.uri.docpart(xhr.resource.uri)] = false if (xhr.userCallback) { xhr.userCallback(false, "Fetch of <" + xhr.resource.uri + "> failed: "+status, xhr) }; this.fireCallbacks('fail', [xhr.requestedURI, status]) xhr.abort() return xhr } this.linkData = function(xhr, rel, uri) { var x = xhr.resource; if (!uri) return; // See http://www.w3.org/TR/powder-dr/#httplink for describedby 2008-12-10 if (rel == 'alternate' || rel == 'seeAlso' || rel == 'meta' || rel == 'describedby') { // var join = $rdf.uri.join2; // doesn't work, now a method of rdf.uri var obj = kb.sym($rdf.uri.join(uri, xhr.resource.uri)) if (obj.uri != xhr.resource) { kb.add(xhr.resource, ns.rdfs('seeAlso'), obj, xhr.resource); // $rdf.log.info("Loading " + obj + " from link rel in " + xhr.resource); } } }; this.doneFetch = function(xhr, args) { this.addStatus(xhr.req, 'Done.') // $rdf.log.info("Done with parse, firing 'done' callbacks for " + xhr.resource) this.requested[xhr.resource.uri] = 'done'; //Kenny if (xhr.userCallback) { xhr.userCallback(true, undefined, xhr); }; this.fireCallbacks('done', args) } this.store.add(this.appNode, ns.rdfs('label'), this.store.literal('This Session'), this.appNode); ['http', 'https', 'file', 'chrome'].map(this.addProtocol); // ftp? mailto:? [$rdf.Fetcher.RDFXMLHandler, $rdf.Fetcher.XHTMLHandler, $rdf.Fetcher.XMLHandler, $rdf.Fetcher.HTMLHandler, $rdf.Fetcher.TextHandler, $rdf.Fetcher.N3Handler ].map(this.addHandler) /** Note two nodes are now smushed ** ** If only one was flagged as looked up, then ** the new node is looked up again, which ** will make sure all the URIs are dereferenced */ this.nowKnownAs = function(was, now) { if (this.lookedUp[was.uri]) { if (!this.lookedUp[now.uri]) this.lookUpThing(now, was) // @@@@ Transfer userCallback } else if (this.lookedUp[now.uri]) { if (!this.lookedUp[was.uri]) this.lookUpThing(was, now) } } // Looks up something. // // Looks up all the URIs a things has. // Parameters: // // term: canonical term for the thing whose URI is to be dereferenced // rterm: the resource which refered to this (for tracking bad links) // force: Load the data even if loaded before // oneDone: is called as callback(ok, errorbody, xhr) for each one // allDone: is called as callback(ok, errorbody) for all of them // Returns the number of things looked up // this.lookUpThing = function(term, rterm, force, oneDone, allDone) { var uris = kb.uris(term) // Get all URIs var success = true; var errors = ''; var outstanding = {}; if (typeof uris !== 'undefined') { for (var i = 0; i < uris.length; i++) { var u = uris[i]; outstanding[u] = true; this.lookedUp[u] = true; var sf = this; var requestOne = function requestOne(u1){ sf.requestURI($rdf.uri.docpart(u1), rterm, force, function(ok, body, xhr){ if (ok) { if (oneDone) oneDone(true, u1); } else { if (oneDone) oneDone(false, body); success = false; errors += body + '\n'; }; delete outstanding[u]; for (x in outstanding) return; if (allDone) allDone(success, errors); }); }; requestOne(u); } } return uris.length } /* Ask for a doc to be loaded if necessary then call back ** ** Changed 2013-08-20: Added (ok, body) params to callback ** **/ this.nowOrWhenFetched = function(uri, referringTerm, userCallback) { var sta = this.getState(uri); if (sta == 'fetched') return userCallback(true); // If it is 'failed', then shoulkd we try again? I think so so an old error doens't get stuck //if (sta == 'unrequested') this.requestURI(uri, referringTerm, false, userCallback); } // Look up response header // // Returns: a list of header values found in a stored HTTP response // or [] if response was found but no header found // or undefined if no response is available. // this.getHeader = function(doc, header) { var kb = this.store; var requests = kb.each(undefined, tabulator.ns.link("requestedURI"), doc.uri); for (var r=0; r<requests.length; r++) { var request = requests[r]; if (request !== undefined) { var response = kb.any(request, tabulator.ns.link("response")); if (request !== undefined) { var results = kb.each(response, tabulator.ns.httph(header.toLowerCase())); if (results.length) { return results.map(function(v){return v.value}); } return []; } } } return undefined; }; this.proxyIfNecessary = function(uri) { if (typeof tabulator != 'undefined' && tabulator.isExtension) return uri; // Extenstion does not need proxy // browser does 2014 on as https browser script not trusted if ($rdf.Fetcher.crossSiteProxyTemplate && document && document.location && ('' + document.location).slice(0,6) === 'https:' && uri.slice(0,5) === 'http:') { return $rdf.Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); } return uri; }; this.saveRequestMetadata = function(xhr, kb, docuri) { var request = kb.bnode(); if (typeof tabulator != 'undefined' && tabulator.isExtension) { var ns = tabulator.ns; } else { var ns = {}; ns.link = $rdf.Namespace("http://www.w3.org/2007/ont/link#"); ns.rdfs = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"); } xhr.req = request; var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(request, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + docuri), this.appNode); kb.add(request, ns.link("requestedURI"), kb.literal(docuri), this.appNode); kb.add(request, ns.link('status'), kb.collection(), this.appNode); return request; }; this.saveResponseMetadata = function(xhr, kb) { var response = kb.bnode(); // define the set of namespaces if not using tabulator if (typeof tabulator != 'undefined' && tabulator.isExtension) { var ns = tabulator.ns; } else { var ns = {}; ns.link = $rdf.Namespace("http://www.w3.org/2007/ont/link#"); ns.http = $rdf.Namespace("http://www.w3.org/2007/ont/http#"); ns.httph = $rdf.Namespace("http://www.w3.org/2007/ont/httph#"); ns.rdfs = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"); } kb.add(xhr.req, ns.link('response'), response); kb.add(response, ns.http('status'), kb.literal(xhr.status), response); kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response); xhr.headers = {} if ($rdf.uri.protocol(xhr.resource.uri) == 'http' || $rdf.uri.protocol(xhr.resource.uri) == 'https') { xhr.headers = $rdf.Util.getHTTPHeaders(xhr) for (var h in xhr.headers) { // trim below for Safari - adds a CR! kb.add(response, ns.httph(h.toLowerCase()), xhr.headers[h].trim(), response) } } return response; }; /** Requests a document URI and arranges to load the document. ** Parameters: ** term: term for the thing whose URI is to be dereferenced ** rterm: the resource which refered to this (for tracking bad links) ** force: Load the data even if loaded before ** userCallback: Called with (true) or (false, errorbody) after load is done or failed ** Return value: ** The xhr object for the HTTP access ** null if the protocol is not a look-up protocol, ** or URI has already been loaded */ this.requestURI = function(docuri, rterm, force, userCallback) { //sources_request_new if (docuri.indexOf('#') >= 0) { // hash throw ("requestURI should not be called with fragid: " + docuri); } var pcol = $rdf.uri.protocol(docuri); if (pcol == 'tel' || pcol == 'mailto' || pcol == 'urn') return null; // No look-up operation on these, but they are not errors var force = !! force var kb = this.store var args = arguments var docterm = kb.sym(docuri) if (!force && typeof(this.requested[docuri]) != "undefined") { return null } this.fireCallbacks('request', args); //Kenny: fire 'request' callbacks here // dump( "web.js: Requesting uri: " + docuri + "\n" ); this.requested[docuri] = true if (rterm) { if (rterm.uri) { // A link betwen URIs not terms kb.add(docterm.uri, ns.link("requestedBy"), rterm.uri, this.appNode) } } if (rterm) { // $rdf.log.info('SF.request: ' + docuri + ' refd by ' + rterm.uri) } else { // $rdf.log.info('SF.request: ' + docuri + ' no referring doc') }; var useJQuery = typeof jQuery != 'undefined'; if (!useJQuery) { var xhr = $rdf.Util.XMLHTTPFactory(); var req = xhr.req = kb.bnode(); xhr.resource = docterm; xhr.requestedURI = args[0]; } else { var req = kb.bnode(); // @@ Joe, no need for xhr.req? } var requestHandlers = kb.collection(); var sf = this; var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(req, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + docuri), this.appNode) kb.add(req, ns.link("requestedURI"), kb.literal(docuri), this.appNode) kb.add(req, ns.link('status'), kb.collection(), this.appNode) // This should not be stored in the store, but in the JS data /* if (typeof kb.anyStatementMatching(this.appNode, ns.link("protocol"), $rdf.uri.protocol(docuri)) == "undefined") { // update the status before we break out this.failFetch(xhr, "Unsupported protocol: "+$rdf.uri.protocol(docuri)) return xhr } */ var onerrorFactory = function(xhr) { return function(event) { if ($rdf.Fetcher.crossSiteProxyTemplate && document && document.location && !xhr.proxyUsed) { // In mashup situation var hostpart = $rdf.uri.hostpart; var here = '' + document.location; var uri = xhr.resource.uri if (hostpart(here) && hostpart(uri) && hostpart(here) != hostpart(uri)) { newURI = $rdf.Fetcher.crossSiteProxy(uri); sf.addStatus(xhr.req, "BLOCKED -> Cross-site Proxy to <" + newURI + ">"); if (xhr.aborted) return; var kb = sf.store; var oldreq = xhr.req; kb.add(oldreq, ns.http('redirectedTo'), kb.sym(newURI), oldreq); ////////////// Change the request node to a new one: @@@@@@@@@@@@ Duplicate of what will be done by requestURI below /* var newreq = xhr.req = kb.bnode() // Make NEW reqest for everything else kb.add(oldreq, ns.http('redirectedRequest'), newreq, xhr.req); var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(newreq, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + newURI), this.appNode) kb.add(newreq, ns.link('status'), kb.collection(), this.appNode); kb.add(newreq, ns.link("requestedURI"), kb.literal(newURI), this.appNode); var response = kb.bnode(); kb.add(oldreq, ns.link('response'), response); */ // kb.add(response, ns.http('status'), kb.literal(xhr.status), response); // if (xhr.statusText) kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response) xhr.abort() xhr.aborted = true sf.addStatus(oldreq, 'done - redirected') // why //the callback throws an exception when called from xhr.onerror (so removed) //sf.fireCallbacks('done', args) // Are these args right? @@@ Noit done yet! done means success sf.requested[xhr.resource.uri] = 'redirected'; var xhr2 = sf.requestURI(newURI, xhr.resource, force, userCallback); xhr2.proxyUsed = true; //only try the proxy once if (xhr2 && xhr2.req) { kb.add(xhr.req, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), xhr2.req, sf.appNode); return; } } } else { if (xhr.withCredentials) { xhr.abort(); xhr.withCredentials = false; sf.addStatus(xhr.req, "Credentials SUPPRESSED to see if that helps"); xhr.send(); // try again } else { sf.failFetch(xhr, "XHR Error: "+event); // Alas we get no error message } } }; } // Set up callbacks var onreadystatechangeFactory = function(xhr) { return function() { var handleResponse = function() { if (xhr.handleResponseDone) return; xhr.handleResponseDone = true; var handler = null; var thisReq = xhr.req // Might have changes by redirect sf.fireCallbacks('recv', args) var kb = sf.store; sf.saveResponseMetadata(xhr, kb); sf.fireCallbacks('headers', [{uri: docuri, headers: xhr.headers}]); if (xhr.status >= 400) { // For extra dignostics, keep the reply // @@@ 401 should cause a retry with credential son // @@@ cache the credentials flag by host ???? if (xhr.responseText.length > 10) { kb.add(response, ns.http('content'), kb.literal(xhr.responseText), response); // dump("HTTP >= 400 responseText:\n"+xhr.responseText+"\n"); // @@@@ } sf.failFetch(xhr, "HTTP error for " +xhr.resource + ": "+ xhr.status + ' ' + xhr.statusText); return; } var loc = xhr.headers['content-location']; // deduce some things from the HTTP transaction var addType = function(cla) { // add type to all redirected resources too var prev = thisReq; if (loc) { var docURI = kb.any(prev, ns.link('requestedURI')); if (docURI != loc) { kb.add(kb.sym(loc), ns.rdf('type'), cla, sf.appNode); } } for (;;) { var doc = kb.any(prev, ns.link('requestedURI')); if (doc && doc.value) // convert Literal kb.add(kb.sym(doc.value), ns.rdf('type'), cla, sf.appNode); prev = kb.any(undefined, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), prev); if (!prev) break; var response = kb.any(prev, kb.sym('http://www.w3.org/2007/ont/link#response')); if (!response) break; var redirection = kb.any(response, kb.sym('http://www.w3.org/2007/ont/http#status')); if (!redirection) break; if (redirection != '301' && redirection != '302') break; } } if (xhr.status == 200) { addType(ns.link('Document')); var ct = xhr.headers['content-type']; if (ct) { if (ct.indexOf('image/') == 0 || ct.indexOf('application/pdf') == 0) addType(kb.sym('http://purl.org/dc/terms/Image')); } } if ($rdf.uri.protocol(xhr.resource.uri) == 'file' || $rdf.uri.protocol(xhr.resource.uri) == 'chrome') { switch (xhr.resource.uri.split('.').pop()) { case 'rdf': case 'owl': xhr.headers['content-type'] = 'application/rdf+xml'; break; case 'n3': case 'nt': case 'ttl': xhr.headers['content-type'] = 'text/n3'; break; default: xhr.headers['content-type'] = 'text/xml'; } } // If we have alread got the thing at this location, abort if (loc) { var udoc = $rdf.uri.join(xhr.resource.uri, loc) if (!force && udoc != xhr.resource.uri && sf.requested[udoc]) { // should we smush too? // $rdf.log.info("HTTP headers indicate we have already" + " retrieved " + xhr.resource + " as " + udoc + ". Aborting.") sf.doneFetch(xhr, args) xhr.abort() return } sf.requested[udoc] = true } for (var x = 0; x < sf.handlers.length; x++) { if (xhr.headers['content-type'] && xhr.headers['content-type'].match(sf.handlers[x].pattern)) { handler = new sf.handlers[x](); requestHandlers.append(sf.handlers[x].term) // FYI break } } var link; try { link = xhr.getResponseHeader('link'); }catch(e){} if (link) { var rel = null; var arg = link.replace(/ /g, '').split(';'); for (var i = 1; i < arg.length; i++) { lr = arg[i].split('='); if (lr[0] == 'rel') rel = lr[1]; } var v = arg[0]; // eg. Link: <.meta>, rel=meta if (v.length && v[0] == '<' && v[v.length-1] == '>' && v.slice) v = v.slice(1, -1); if (rel) // Treat just like HTML link element sf.linkData(xhr, rel, v); } if (handler) { try { handler.handlerFactory(xhr); } catch(e) { // Try to avoid silent errors sf.failFetch(xhr, "Exception handling content-type " + xhr.headers['content-type'] + ' was: '+e); }; } else { sf.doneFetch(xhr, args); // Not a problem, we just don't extract data. /* // sf.failFetch(xhr, "Unhandled content type: " + xhr.headers['content-type']+ // ", readyState = "+xhr.readyState); */ return; } }; // DONE: 4 // HEADERS_RECEIVED: 2 // LOADING: 3 // OPENED: 1 // UNSENT: 0 // $rdf.log.debug("web.js: XHR " + xhr.resource.uri + ' readyState='+xhr.readyState); // @@@@ comment me out switch (xhr.readyState) { case 0: var uri = xhr.resource.uri, newURI; if (this.crossSiteProxyTemplate && document && document.location) { // In mashup situation var hostpart = $rdf.uri.hostpart; var here = '' + document.location; if (hostpart(here) && hostpart(uri) && hostpart(here) != hostpart(uri)) { newURI = this.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); sf.addStatus(xhr.req, "BLOCKED -> Cross-site Proxy to <" + newURI + ">"); if (xhr.aborted) return; var kb = sf.store; var oldreq = xhr.req; kb.add(oldreq, ns.http('redirectedTo'), kb.sym(newURI), oldreq); ////////////// Change the request node to a new one: @@@@@@@@@@@@ Duplicate? var newreq = xhr.req = kb.bnode() // Make NEW reqest for everything else kb.add(oldreq, ns.http('redirectedRequest'), newreq, xhr.req); var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(newreq, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + newURI), this.appNode) kb.add(newreq, ns.link('status'), kb.collection(), this.appNode); kb.add(newreq, ns.link("requestedURI"), kb.literal(newURI), this.appNode); var response = kb.bnode(); kb.add(oldreq, ns.link('response'), response); // kb.add(response, ns.http('status'), kb.literal(xhr.status), response); // if (xhr.statusText) kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response) xhr.abort() xhr.aborted = true sf.addStatus(oldreq, 'done') // why if (xhr.userCallback) { xhr.userCallback(true); }; sf.fireCallbacks('done', args) // Are these args right? @@@ sf.requested[xhr.resource.uri] = 'redirected'; var xhr2 = sf.requestURI(newURI, xhr.resource); if (xhr2 && xhr2.req) kb.add(xhr.req, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), xhr2.req, sf.appNode); return; } } sf.failFetch(xhr, "HTTP Blocked. (ReadyState 0) Cross-site violation for <"+ docuri+">"); break; case 3: // Intermediate state -- 3 may OR MAY NOT be called, selon browser. // handleResponse(); // In general it you can't do it yet as the headers are in but not the data break case 4: // Final state handleResponse(); // Now handle if (xhr.handle) { if (sf.requested[xhr.resource.uri] === 'redirected') { break; } sf.fireCallbacks('load', args) xhr.handle(function() { sf.doneFetch(xhr, args) }) } else { sf.addStatus(xhr.req, "Fetch OK. No known semantics."); sf.doneFetch(xhr, args); //sf.failFetch(xhr, "HTTP failed unusually. (no handler set) (x-site violation? no net?) for <"+ // docuri+">"); } break } // switch }; } // Map the URI to a localhost proxy if we are running on localhost // This is used for working offline, e.g. on planes. // Is the script istelf is running in localhost, then access all data in a localhost mirror. // Do not remove without checking with TimBL :) var uri2 = docuri; if (typeof tabulator != 'undefined' && tabulator.preferences.get('offlineModeUsingLocalhost')) { if (uri2.slice(0,7) == 'http://' && uri2.slice(7,17) != 'localhost/') { uri2 = 'http://localhost/' + uri2.slice(7); $rdf.log.warn("Localhost kludge for offline use: actually getting <" + uri2 + ">"); } else { // $rdf.log.warn("Localhost kludge NOT USED <" + uri2 + ">"); }; } else { // $rdf.log.warn("Localhost kludge OFF offline use: actually getting <" + uri2 + ">"); } // 2014 probelm: // XMLHttpRequest cannot load http://www.w3.org/People/Berners-Lee/card. // A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. // @ Many ontology files under http: and need CORS wildcard -> can't have withCredentials var withCredentials = ( uri2.slice(0,6) === 'https:'); // @@ Kludge -- need for webid which typically is served from https var actualProxyURI = this.proxyIfNecessary(uri2); // Setup the request if (typeof jQuery !== 'undefined' && jQuery.ajax) { var xhr = jQuery.ajax({ url: actualProxyURI, accepts: {'*': 'text/turtle,text/n3,application/rdf+xml'}, processData: false, xhrFields: { withCredentials: withCredentials }, timeout: sf.timeout, error: function(xhr, s, e) { xhr.req = req; // Add these in case fails before .ajax returns xhr.userCallback = userCallback; xhr.resource = docterm; xhr.requestedURI = uri2; if (s == 'timeout') sf.failFetch(xhr, "requestTimeout"); else onerrorFactory(xhr)(e); }, success: function(d, s, xhr) { xhr.req = req; xhr.userCallback = userCallback; xhr.resource = docterm; xhr.requestedURI = uri2; onreadystatechangeFactory(xhr)(); } }); xhr.req = req; xhr.userCallback = userCallback; xhr.resource = docterm; xhr.requestedURI = uri2; xhr.actualProxyURI = actualProxyURI; } else { var xhr = $rdf.Util.XMLHTTPFactory(); xhr.onerror = onerrorFactory(xhr); xhr.onreadystatechange = onreadystatechangeFactory(xhr); xhr.timeout = sf.timeout; xhr.withCredentials = withCredentials; xhr.actualProxyURI = actualProxyURI; xhr.req = req; xhr.userCallback = userCallback; xhr.resource = docterm; xhr.requestedURI = uri2; xhr.ontimeout = function () { sf.failFetch(xhr, "requestTimeout"); } try { xhr.open('GET', actualProxyURI, this.async); } catch (er) { return this.failFetch(xhr, "XHR open for GET failed for <"+uri2+">:\n\t" + er); } } // Set redirect callback and request headers -- alas Firefox Extension Only if (typeof tabulator != 'undefined' && tabulator.isExtension && xhr.channel && ($rdf.uri.protocol(xhr.resource.uri) == 'http' || $rdf.uri.protocol(xhr.resource.uri) == 'https')) { try { xhr.channel.notificationCallbacks = { getInterface: function(iid) { if (iid.equals(Components.interfaces.nsIChannelEventSink)) { return { onChannelRedirect: function(oldC, newC, flags) { if (xhr.aborted) return; var kb = sf.store; var newURI = newC.URI.spec; var oldreq = xhr.req; sf.addStatus(xhr.req, "Redirected: " + xhr.status + " to <" + newURI + ">"); kb.add(oldreq, ns.http('redirectedTo'), kb.sym(newURI), xhr.req); ////////////// Change the request node to a new one: @@@@@@@@@@@@ Duplicate? var newreq = xhr.req = kb.bnode() // Make NEW reqest for everything else // xhr.resource = docterm // xhr.requestedURI = args[0] // var requestHandlers = kb.collection() // kb.add(kb.sym(newURI), ns.link("request"), req, this.appNode) kb.add(oldreq, ns.http('redirectedRequest'), newreq, xhr.req); var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(newreq, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + newURI), this.appNode) kb.add(newreq, ns.link('status'), kb.collection(), this.appNode) kb.add(newreq, ns.link("requestedURI"), kb.literal(newURI), this.appNode) /////////////// //// $rdf.log.info('@@ sources onChannelRedirect'+ // "Redirected: "+ // xhr.status + " to <" + newURI + ">"); //@@ var response = kb.bnode(); // kb.add(response, ns.http('location'), newURI, response); Not on this response kb.add(oldreq, ns.link('response'), response); kb.add(response, ns.http('status'), kb.literal(xhr.status), response); if (xhr.statusText) kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response) if (xhr.status - 0 != 303) kb.HTTPRedirects[xhr.resource.uri] = newURI; // same document as if (xhr.status - 0 == 301 && rterm) { // 301 Moved var badDoc = $rdf.uri.docpart(rterm.uri); var msg = 'Warning: ' + xhr.resource + ' has moved to <' + newURI + '>.'; if (rterm) { msg += ' Link in <' + badDoc + ' >should be changed'; kb.add(badDoc, kb.sym('http://www.w3.org/2007/ont/link#warning'), msg, sf.appNode); } // dump(msg+"\n"); } xhr.abort() xhr.aborted = true sf.addStatus(oldreq, 'done') // why sf.fireCallbacks('done', args) // Are these args right? @@@ sf.requested[xhr.resource.uri] = 'redirected'; var hash = newURI.indexOf('#'); if (hash >= 0) { var msg = ('Warning: ' + xhr.resource + ' HTTP redirects to' + newURI + ' which should not contain a "#" sign'); // dump(msg+"\n"); kb.add(xhr.resource, kb.sym('http://www.w3.org/2007/ont/link#warning'), msg) newURI = newURI.slice(0, hash); } var xhr2 = sf.requestURI(newURI, xhr.resource); if (xhr2 && xhr2.req) kb.add(xhr.req, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), xhr2.req, sf.appNode); // else dump("No xhr.req available for redirect from "+xhr.resource+" to "+newURI+"\n") }, // See https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIChannelEventSink asyncOnChannelRedirect: function(oldC, newC, flags, callback) { if (xhr.aborted) return; var kb = sf.store; var newURI = newC.URI.spec; var oldreq = xhr.req; sf.addStatus(xhr.req, "Redirected: " + xhr.status + " to <" + newURI + ">"); kb.add(oldreq, ns.http('redirectedTo'), kb.sym(newURI), xhr.req); ////////////// Change the request node to a new one: @@@@@@@@@@@@ Duplicate? var newreq = xhr.req = kb.bnode() // Make NEW reqest for everything else // xhr.resource = docterm // xhr.requestedURI = args[0] // var requestHandlers = kb.collection() // kb.add(kb.sym(newURI), ns.link("request"), req, this.appNode) kb.add(oldreq, ns.http('redirectedRequest'), newreq, xhr.req); var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(newreq, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + newURI), this.appNode) kb.add(newreq, ns.link('status'), kb.collection(), this.appNode) kb.add(newreq, ns.link("requestedURI"), kb.literal(newURI), this.appNode) /////////////// //// $rdf.log.info('@@ sources onChannelRedirect'+ // "Redirected: "+ // xhr.status + " to <" + newURI + ">"); //@@ var response = kb.bnode(); // kb.add(response, ns.http('location'), newURI, response); Not on this response kb.add(oldreq, ns.link('response'), response); kb.add(response, ns.http('status'), kb.literal(xhr.status), response); if (xhr.statusText) kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response) if (xhr.status - 0 != 303) kb.HTTPRedirects[xhr.resource.uri] = newURI; // same document as if (xhr.status - 0 == 301 && rterm) { // 301 Moved var badDoc = $rdf.uri.docpart(rterm.uri); var msg = 'Warning: ' + xhr.resource + ' has moved to <' + newURI + '>.'; if (rterm) { msg += ' Link in <' + badDoc + ' >should be changed'; kb.add(badDoc, kb.sym('http://www.w3.org/2007/ont/link#warning'), msg, sf.appNode); } // dump(msg+"\n"); } xhr.abort() xhr.aborted = true sf.addStatus(oldreq, 'done') // why if (xhr.userCallback) { xhr.userCallback(true); }; sf.fireCallbacks('done', args) // Are these args right? @@@ sf.requested[xhr.resource.uri] = 'redirected'; var hash = newURI.indexOf('#'); if (hash >= 0) { var msg = ('Warning: ' + xhr.resource + ' HTTP redirects to' + newURI + ' which should not contain a "#" sign'); // dump(msg+"\n"); kb.add(xhr.resource, kb.sym('http://www.w3.org/2007/ont/link#warning'), msg) newURI = newURI.slice(0, hash); } var xhr2 = sf.requestURI(newURI, xhr.resource); if (xhr2 && xhr2.req) kb.add(xhr.req, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), xhr2.req, sf.appNode); // else dump("No xhr.req available for redirect from "+xhr.resource+" to "+newURI+"\n") } // asyncOnChannelRedirect } } return Components.results.NS_NOINTERFACE } } } catch (err) { return sf.failFetch(xhr, "@@ Couldn't set callback for redirects: " + err); } } try { var acceptstring = "" for (var type in this.mediatypes) { var attrstring = "" if (acceptstring != "") { acceptstring += ", " } acceptstring += type for (var attr in this.mediatypes[type]) { acceptstring += ';' + attr + '=' + this.mediatypes[type][attr] } } xhr.setRequestHeader('Accept', acceptstring) // $rdf.log.info('Accept: ' + acceptstring) // See http://dig.csail.mit.edu/issues/tabulator/issue65 //if (requester) { xhr.setRequestHeader('Referer',requester) } } catch (err) { throw ("Can't set Accept header: " + err) } // Fire if (!useJQuery) { try { xhr.send(null) } catch (er) { return this.failFetch(xhr, "XHR send failed:" + er); } setTimeout(function() { if (xhr.readyState != 4 && sf.isPending(xhr.resource.uri)) { sf.failFetch(xhr, "requestTimeout") } }, this.timeout); this.addStatus(xhr.req, "HTTP Request sent."); } else { this.addStatus(xhr.req, "HTTP Request sent (using jQuery)"); } return xhr } // this.requested[docuri]) != "undefined" this.objectRefresh = function(term) { var uris = kb.uris(term) // Get all URIs if (typeof uris != 'undefined') { for (var i = 0; i < uris.length; i++) { this.refresh(this.store.sym($rdf.uri.docpart(uris[i]))); //what about rterm? } } } this.unload = function(term) { this.store.removeMany(undefined, undefined, undefined, term) delete this.requested[term.uri]; // So it can be loaded again } this.refresh = function(term) { // sources_refresh this.unload(term); this.fireCallbacks('refresh', arguments) this.requestURI(term.uri, undefined, true) } this.retract = function(term) { // sources_retract this.store.removeMany(undefined, undefined, undefined, term) if (term.uri) { delete this.requested[$rdf.uri.docpart(term.uri)] } this.fireCallbacks('retract', arguments) } this.getState = function(docuri) { // docState if (typeof this.requested[docuri] != "undefined") { if (this.requested[docuri]) { if (this.isPending(docuri)) { return "requested" } else { return "fetched" } } else { return "failed" } } else { return "unrequested" } } //doing anyStatementMatching is wasting time this.isPending = function(docuri) { // sources_pending //if it's not pending: false -> flailed 'done' -> done 'redirected' -> redirected return this.requested[docuri] == true; } var updatesVia = new $rdf.UpdatesVia(this); }; $rdf.fetcher = function(store, timeout, async) { return new $rdf.Fetcher(store, timeout, async) }; // Parse a string and put the result into the graph kb $rdf.parse = function parse(str, kb, base, contentType) { try { /* parseXML = function(str) { var dparser; if ((typeof tabulator != 'undefined' && tabulator.isExtension)) { dparser = Components.classes["@mozilla.org/xmlextras/domparser;1"].getService( Components.interfaces.nsIDOMParser); } else if (typeof module != 'undefined' ){ // Node.js var jsdom = require('jsdom'); return jsdom.jsdom(str, undefined, {} );// html, level, options } else { dparser = new DOMParser() } return dparser.parseFromString(str, 'application/xml'); } */ if (contentType == 'text/n3' || contentType == 'text/turtle') { var p = $rdf.N3Parser(kb, kb, base, base, null, null, "", null) p.loadBuf(str) return; } if (contentType == 'application/rdf+xml') { var parser = new $rdf.RDFParser(kb); parser.parse($rdf.Util.parseXML(str), base, kb.sym(base)); return; } if (contentType == 'application/rdfa') { // @@ not really a valid mime type if ($rdf.rdfa && $rdf.rdfa.parse) $rdf.rdfa.parse($rdf.Util.parseXML(str), kb, base); return; } if (contentType == 'application/sparql-update') { // @@ we handle a subset spaqlUpdateParser(store, str, base) if ($rdf.rdfa && $rdf.rdfa.parse) $rdf.rdfa.parse($rdf.Util.parseXML(str), kb, base); return; } } catch(e) { throw "Error trying to parse <"+base+"> as "+contentType+":\n"+e +':\n'+e.stack; } throw "Don't know how to parse "+contentType+" yet"; }; // Serialize to the appropriate format // $rdf.serialize = function(target, kb, base, contentType, callback) { var documentString; var sz = $rdf.Serializer(kb); var newSts = kb.statementsMatching(undefined, undefined, undefined, target); sz.suggestNamespaces(kb.namespaces); sz.setBase(base); sz.setFlags('r'); switch(contentType){ case 'application/rdf+xml': documentString = sz.statementsToXML(newSts); break; case 'text/n3': case 'text/turtle': case 'application/x-turtle': // Legacy case 'application/n3': // Legacy documentString = sz.statementsToN3(newSts); break; case 'application/json+ld': var n3String = sz.statementsToN3(newSts); convertToJson(n3String, callback); break; case 'application/n-quads': case 'application/nquads': // @@@ just outpout the quads? Does not work for collections var n3String = sz.statementsToN3(newSts); documentString = convertToNQuads(n3String, callback); break; default: throw "serialise: Content-type "+content_type +" not supported for data write"; } return documentString; }; ////////////////// JSON-LD code currently requires Node if (typeof module !== 'undefined' && module.require) { // Node var asyncLib = require('async'); var jsonld = require('jsonld'); var N3 = require('n3'); var convertToJson = function(n3String, jsonCallback) { var jsonString = undefined; var n3Parser = N3.Parser(); var n3Writer = N3.Writer({ format: 'N-Quads' }); asyncLib.waterfall([ function(callback) { n3Parser.parse(n3String, callback); }, function(triple, prefix, callback) { if (triple !== null) { n3Writer.addTriple(triple); } if (typeof callback === 'function') { n3Writer.end(callback); } }, function(result, callback) { try { jsonld.fromRDF(result, { format: 'application/nquads' }, callback); } catch (err) { callback(err); } }, function(json, callback) { jsonString = JSON.stringify(json); jsonCallback(null, jsonString); } ], function(err, result) { jsonCallback(err, jsonString); }); } var convertToNQuads = function(n3String, nquadCallback) { var nquadString = undefined; var n3Parser = N3.Parser(); var n3Writer = N3.Writer({ format: 'N-Quads' }); asyncLib.waterfall([ function(callback) { n3Parser.parse(n3String, callback); }, function(triple, prefix, callback) { if (triple !== null) { n3Writer.addTriple(triple); } if (typeof callback === 'function') { n3Writer.end(callback); } }, function(result, callback) { nquadString = result; nquadCallback(null, nquadString); }, ], function(err, result) { nquadCallback(err, nquadString); }); } } // ends
web.js
/************************************************************ * * Project: rdflib.js, originally part of Tabulator project * * File: web.js * * Description: contains functions for requesting/fetching/retracting * This implements quite a lot of the web architecture. * A fetcher is bound to a specific knowledge base graph, into which * it loads stuff and into which it writes its metadata * @@ The metadata should be optionally a separate graph * * - implements semantics of HTTP headers, Internet Content Types * - selects parsers for rdf/xml, n3, rdfa, grddl * * Dependencies: * * needs: util.js uri.js term.js rdfparser.js rdfa.js n3parser.js * identity.js sparql.js jsonparser.js * * If jQuery is defined, it uses jQuery.ajax, else is independent of jQuery * ************************************************************/ /** * Things to test: callbacks on request, refresh, retract * loading from HTTP, HTTPS, FTP, FILE, others? * To do: * Firing up a mail client for mid: (message:) URLs */ if (typeof module !== 'undefined' && module.require) { // Node // For non-node, jasonld needs to be inlined in init.js etc $rdf.jsonld = require('jsonld'); N3 = require('n3'); asyncLib = require('async'); } $rdf.Fetcher = function(store, timeout, async) { this.store = store this.thisURI = "http://dig.csail.mit.edu/2005/ajar/ajaw/rdf/sources.js" + "#SourceFetcher" // -- Kenny this.timeout = timeout ? timeout : 30000 this.async = async != null ? async : true this.appNode = this.store.bnode(); // Denoting this session this.store.fetcher = this; //Bi-linked this.requested = {} this.lookedUp = {} this.handlers = [] this.mediatypes = {} var sf = this var kb = this.store; var ns = {} // Convenience namespaces needed in this module: // These are delibertely not exported as the user application should // make its own list and not rely on the prefixes used here, // and not be tempted to add to them, and them clash with those of another // application. ns.link = $rdf.Namespace("http://www.w3.org/2007/ont/link#"); ns.http = $rdf.Namespace("http://www.w3.org/2007/ont/http#"); ns.httph = $rdf.Namespace("http://www.w3.org/2007/ont/httph#"); ns.rdf = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#"); ns.rdfs = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"); ns.dc = $rdf.Namespace("http://purl.org/dc/elements/1.1/"); $rdf.Fetcher.crossSiteProxy = function(uri) { if ($rdf.Fetcher.crossSiteProxyTemplate) return $rdf.Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); else return undefined; }; $rdf.Fetcher.RDFXMLHandler = function(args) { if (args) { this.dom = args[0] } this.handlerFactory = function(xhr) { xhr.handle = function(cb) { //sf.addStatus(xhr.req, 'parsing soon as RDF/XML...'); var kb = sf.store; if (!this.dom) this.dom = $rdf.Util.parseXML(xhr.responseText); /* { var dparser; if ((typeof tabulator != 'undefined' && tabulator.isExtension)) { dparser = Components.classes["@mozilla.org/xmlextras/domparser;1"].getService(Components.interfaces.nsIDOMParser); } else { dparser = new DOMParser() } //strange things happen when responseText is empty this.dom = dparser.parseFromString(xhr.responseText, 'application/xml') } */ var root = this.dom.documentElement; if (root.nodeName == 'parsererror') { //@@ Mozilla only See issue/issue110 sf.failFetch(xhr, "Badly formed XML in " + xhr.resource.uri); //have to fail the request throw new Error("Badly formed XML in " + xhr.resource.uri); //@@ Add details } // Find the last URI we actual URI in a series of redirects // (xhr.resource.uri is the original one) var lastRequested = kb.any(xhr.req, ns.link('requestedURI')); if (!lastRequested) { lastRequested = xhr.resource; } else { lastRequested = kb.sym(lastRequested.value); } var parser = new $rdf.RDFParser(kb); // sf.addStatus(xhr.req, 'parsing as RDF/XML...'); parser.parse(this.dom, lastRequested.uri, lastRequested); kb.add(lastRequested, ns.rdf('type'), ns.link('RDFDocument'), sf.appNode); cb(); } } }; $rdf.Fetcher.RDFXMLHandler.term = this.store.sym(this.thisURI + ".RDFXMLHandler"); $rdf.Fetcher.RDFXMLHandler.toString = function() { return "RDFXMLHandler" }; $rdf.Fetcher.RDFXMLHandler.register = function(sf) { sf.mediatypes['application/rdf+xml'] = {} }; $rdf.Fetcher.RDFXMLHandler.pattern = new RegExp("application/rdf\\+xml"); // This would much better use on-board XSLT engine. @@ $rdf.Fetcher.doGRDDL = function(kb, doc, xslturi, xmluri) { sf.requestURI('http://www.w3.org/2005/08/' + 'online_xslt/xslt?' + 'xslfile=' + escape(xslturi) + '&xmlfile=' + escape(xmluri), doc) }; $rdf.Fetcher.XHTMLHandler = function(args) { if (args) { this.dom = args[0] } this.handlerFactory = function(xhr) { xhr.handle = function(cb) { if (!this.dom) { var dparser; if (typeof tabulator != 'undefined' && tabulator.isExtension) { dparser = Components.classes["@mozilla.org/xmlextras/domparser;1"].getService(Components.interfaces.nsIDOMParser); } else { dparser = new DOMParser() } this.dom = dparser.parseFromString(xhr.responseText, 'application/xml') } var kb = sf.store; // dc:title var title = this.dom.getElementsByTagName('title') if (title.length > 0) { kb.add(xhr.resource, ns.dc('title'), kb.literal(title[0].textContent), xhr.resource) // $rdf.log.info("Inferring title of " + xhr.resource) } // link rel var links = this.dom.getElementsByTagName('link'); for (var x = links.length - 1; x >= 0; x--) { sf.linkData(xhr, links[x].getAttribute('rel'), links[x].getAttribute('href')); } //GRDDL var head = this.dom.getElementsByTagName('head')[0] if (head) { var profile = head.getAttribute('profile'); if (profile && $rdf.uri.protocol(profile) == 'http') { // $rdf.log.info("GRDDL: Using generic " + "2003/11/rdf-in-xhtml-processor."); $rdf.Fetcher.doGRDDL(kb, xhr.resource, "http://www.w3.org/2003/11/rdf-in-xhtml-processor", xhr.resource.uri) /* sf.requestURI('http://www.w3.org/2005/08/' + 'online_xslt/xslt?' + 'xslfile=http://www.w3.org' + '/2003/11/' + 'rdf-in-xhtml-processor' + '&xmlfile=' + escape(xhr.resource.uri), xhr.resource) */ } else { // $rdf.log.info("GRDDL: No GRDDL profile in " + xhr.resource) } } kb.add(xhr.resource, ns.rdf('type'), ns.link('WebPage'), sf.appNode); // Do RDFa here if ($rdf.rdfa && $rdf.rdfa.parse) $rdf.rdfa.parse(this.dom, kb, xhr.resource.uri); cb(); // Fire done callbacks } } }; $rdf.Fetcher.XHTMLHandler.term = this.store.sym(this.thisURI + ".XHTMLHandler"); $rdf.Fetcher.XHTMLHandler.toString = function() { return "XHTMLHandler" }; $rdf.Fetcher.XHTMLHandler.register = function(sf) { sf.mediatypes['application/xhtml+xml'] = { 'q': 0.3 } }; $rdf.Fetcher.XHTMLHandler.pattern = new RegExp("application/xhtml"); /******************************************************/ $rdf.Fetcher.XMLHandler = function() { this.handlerFactory = function(xhr) { xhr.handle = function(cb) { var kb = sf.store var dparser; if (typeof tabulator != 'undefined' && tabulator.isExtension) { dparser = Components.classes["@mozilla.org/xmlextras/domparser;1"].getService(Components.interfaces.nsIDOMParser); } else { dparser = new DOMParser() } var dom = dparser.parseFromString(xhr.responseText, 'application/xml') // XML Semantics defined by root element namespace // figure out the root element for (var c = 0; c < dom.childNodes.length; c++) { // is this node an element? if (dom.childNodes[c].nodeType == 1) { // We've found the first element, it's the root var ns = dom.childNodes[c].namespaceURI; // Is it RDF/XML? if (ns != undefined && ns == ns['rdf']) { sf.addStatus(xhr.req, "Has XML root element in the RDF namespace, so assume RDF/XML.") sf.switchHandler('RDFXMLHandler', xhr, cb, [dom]) return } // it isn't RDF/XML or we can't tell // Are there any GRDDL transforms for this namespace? // @@ assumes ns documents have already been loaded var xforms = kb.each(kb.sym(ns), kb.sym("http://www.w3.org/2003/g/data-view#namespaceTransformation")); for (var i = 0; i < xforms.length; i++) { var xform = xforms[i]; // $rdf.log.info(xhr.resource.uri + " namespace " + ns + " has GRDDL ns transform" + xform.uri); $rdf.Fetcher.doGRDDL(kb, xhr.resource, xform.uri, xhr.resource.uri); } break } } // Or it could be XHTML? // Maybe it has an XHTML DOCTYPE? if (dom.doctype) { // $rdf.log.info("We found a DOCTYPE in " + xhr.resource) if (dom.doctype.name == 'html' && dom.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/) && dom.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)) { sf.addStatus(xhr.req,"Has XHTML DOCTYPE. Switching to XHTML Handler.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } } // Or what about an XHTML namespace? var html = dom.getElementsByTagName('html')[0] if (html) { var xmlns = html.getAttribute('xmlns') if (xmlns && xmlns.match(/^http:\/\/www.w3.org\/1999\/xhtml/)) { sf.addStatus(xhr.req, "Has a default namespace for " + "XHTML. Switching to XHTMLHandler.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } } // At this point we should check the namespace document (cache it!) and // look for a GRDDL transform // @@ Get namespace document <n>, parse it, look for <n> grddl:namespaceTransform ?y // Apply ?y to dom // We give up. What dialect is this? sf.failFetch(xhr, "Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n"+xhr.responseText.slice(0,80)); } } }; $rdf.Fetcher.XMLHandler.term = this.store.sym(this.thisURI + ".XMLHandler"); $rdf.Fetcher.XMLHandler.toString = function() { return "XMLHandler" }; $rdf.Fetcher.XMLHandler.register = function(sf) { sf.mediatypes['text/xml'] = { 'q': 0.2 } sf.mediatypes['application/xml'] = { 'q': 0.2 } }; $rdf.Fetcher.XMLHandler.pattern = new RegExp("(text|application)/(.*)xml"); $rdf.Fetcher.HTMLHandler = function() { this.handlerFactory = function(xhr) { xhr.handle = function(cb) { var rt = xhr.responseText // We only handle XHTML so we have to figure out if this is XML // $rdf.log.info("Sniffing HTML " + xhr.resource + " for XHTML."); if (rt.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)) { sf.addStatus(xhr.req, "Has an XML declaration. We'll assume " + "it's XHTML as the content-type was text/html.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } // DOCTYPE // There is probably a smarter way to do this if (rt.match(/.*<!DOCTYPE\s+html[^<]+-\/\/W3C\/\/DTD XHTML[^<]+http:\/\/www.w3.org\/TR\/xhtml[^<]+>/)) { sf.addStatus(xhr.req, "Has XHTML DOCTYPE. Switching to XHTMLHandler.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } // xmlns if (rt.match(/[^(<html)]*<html\s+[^<]*xmlns=['"]http:\/\/www.w3.org\/1999\/xhtml["'][^<]*>/)) { sf.addStatus(xhr.req, "Has default namespace for XHTML, so switching to XHTMLHandler.\n") sf.switchHandler('XHTMLHandler', xhr, cb) return } // dc:title //no need to escape '/' here var titleMatch = (new RegExp("<title>([\\s\\S]+?)</title>", 'im')).exec(rt); if (titleMatch) { var kb = sf.store; kb.add(xhr.resource, ns.dc('title'), kb.literal(titleMatch[1]), xhr.resource); //think about xml:lang later kb.add(xhr.resource, ns.rdf('type'), ns.link('WebPage'), sf.appNode); cb(); //doneFetch, not failed return; } sf.failFetch(xhr, "Sorry, can't yet parse non-XML HTML") } } }; $rdf.Fetcher.HTMLHandler.term = this.store.sym(this.thisURI + ".HTMLHandler"); $rdf.Fetcher.HTMLHandler.toString = function() { return "HTMLHandler" }; $rdf.Fetcher.HTMLHandler.register = function(sf) { sf.mediatypes['text/html'] = { 'q': 0.3 } }; $rdf.Fetcher.HTMLHandler.pattern = new RegExp("text/html"); /***********************************************/ $rdf.Fetcher.TextHandler = function() { this.handlerFactory = function(xhr) { xhr.handle = function(cb) { // We only speak dialects of XML right now. Is this XML? var rt = xhr.responseText // Look for an XML declaration if (rt.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/)) { sf.addStatus(xhr.req, "Warning: "+xhr.resource + " has an XML declaration. We'll assume " + "it's XML but its content-type wasn't XML.\n") sf.switchHandler('XMLHandler', xhr, cb) return } // Look for an XML declaration if (rt.slice(0, 500).match(/xmlns:/)) { sf.addStatus(xhr.req, "May have an XML namespace. We'll assume " + "it's XML but its content-type wasn't XML.\n") sf.switchHandler('XMLHandler', xhr, cb) return } // We give up finding semantics - this is not an error, just no data sf.addStatus(xhr.req, "Plain text document, no known RDF semantics."); sf.doneFetch(xhr, [xhr.resource.uri]); // sf.failFetch(xhr, "unparseable - text/plain not visibly XML") // dump(xhr.resource + " unparseable - text/plain not visibly XML, starts:\n" + rt.slice(0, 500)+"\n") } } }; $rdf.Fetcher.TextHandler.term = this.store.sym(this.thisURI + ".TextHandler"); $rdf.Fetcher.TextHandler.toString = function() { return "TextHandler"; }; $rdf.Fetcher.TextHandler.register = function(sf) { sf.mediatypes['text/plain'] = { 'q': 0.1 } } $rdf.Fetcher.TextHandler.pattern = new RegExp("text/plain"); /***********************************************/ $rdf.Fetcher.N3Handler = function() { this.handlerFactory = function(xhr) { xhr.handle = function(cb) { // Parse the text of this non-XML file $rdf.log.debug("web.js: Parsing as N3 " + xhr.resource.uri); // @@@@ comment me out //sf.addStatus(xhr.req, "N3 not parsed yet...") var rt = xhr.responseText var p = $rdf.N3Parser(kb, kb, xhr.resource.uri, xhr.resource.uri, null, null, "", null) // p.loadBuf(xhr.responseText) try { p.loadBuf(xhr.responseText) } catch (e) { var msg = ("Error trying to parse " + xhr.resource + " as Notation3:\n" + e +':\n'+e.stack) // dump(msg+"\n") sf.failFetch(xhr, msg) return; } sf.addStatus(xhr.req, "N3 parsed: " + p.statementCount + " triples in " + p.lines + " lines.") sf.store.add(xhr.resource, ns.rdf('type'), ns.link('RDFDocument'), sf.appNode); args = [xhr.resource.uri]; // Other args needed ever? sf.doneFetch(xhr, args) } } }; $rdf.Fetcher.N3Handler.term = this.store.sym(this.thisURI + ".N3Handler"); $rdf.Fetcher.N3Handler.toString = function() { return "N3Handler"; } $rdf.Fetcher.N3Handler.register = function(sf) { sf.mediatypes['text/n3'] = { 'q': '1.0' } // as per 2008 spec sf.mediatypes['application/x-turtle'] = { 'q': 1.0 } // pre 2008 sf.mediatypes['text/turtle'] = { 'q': 1.0 } // pre 2008 } $rdf.Fetcher.N3Handler.pattern = new RegExp("(application|text)/(x-)?(rdf\\+)?(n3|turtle)") /***********************************************/ $rdf.Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail', 'refresh', 'retract', 'done']); this.addProtocol = function(proto) { sf.store.add(sf.appNode, ns.link("protocol"), sf.store.literal(proto), this.appNode) } this.addHandler = function(handler) { sf.handlers.push(handler) handler.register(sf) } this.switchHandler = function(name, xhr, cb, args) { var kb = this.store; var handler = null; for (var i=0; i<this.handlers.length; i++) { if (''+this.handlers[i] == name) { handler = this.handlers[i]; } } if (handler == undefined) { throw 'web.js: switchHandler: name='+name+' , this.handlers ='+this.handlers+'\n' + 'switchHandler: switching to '+handler+'; sf='+sf + '; typeof $rdf.Fetcher='+typeof $rdf.Fetcher + ';\n\t $rdf.Fetcher.HTMLHandler='+$rdf.Fetcher.HTMLHandler+'\n' + '\n\tsf.handlers='+sf.handlers+'\n' } (new handler(args)).handlerFactory(xhr); xhr.handle(cb) } this.addStatus = function(req, status) { //<Debug about="parsePerformance"> var now = new Date(); status = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "." + now.getMilliseconds() + "] " + status; //</Debug> var kb = this.store var s = kb.the(req, ns.link('status')); if (s && s.append) { s.append(kb.literal(status)); } else { $rdf.log.warn("web.js: No list to add to: " + s + ',' + status); // @@@ }; } // Record errors in the system on failure // Returns xhr so can just do return this.failfetch(...) this.failFetch = function(xhr, status) { this.addStatus(xhr.req, status) kb.add(xhr.resource, ns.link('error'), status) this.requested[$rdf.uri.docpart(xhr.resource.uri)] = false if (xhr.userCallback) { xhr.userCallback(false, "Fetch of <" + xhr.resource.uri + "> failed: "+status, xhr) }; this.fireCallbacks('fail', [xhr.requestedURI, status]) xhr.abort() return xhr } this.linkData = function(xhr, rel, uri) { var x = xhr.resource; if (!uri) return; // See http://www.w3.org/TR/powder-dr/#httplink for describedby 2008-12-10 if (rel == 'alternate' || rel == 'seeAlso' || rel == 'meta' || rel == 'describedby') { // var join = $rdf.uri.join2; // doesn't work, now a method of rdf.uri var obj = kb.sym($rdf.uri.join(uri, xhr.resource.uri)) if (obj.uri != xhr.resource) { kb.add(xhr.resource, ns.rdfs('seeAlso'), obj, xhr.resource); // $rdf.log.info("Loading " + obj + " from link rel in " + xhr.resource); } } }; this.doneFetch = function(xhr, args) { this.addStatus(xhr.req, 'Done.') // $rdf.log.info("Done with parse, firing 'done' callbacks for " + xhr.resource) this.requested[xhr.resource.uri] = 'done'; //Kenny if (xhr.userCallback) { xhr.userCallback(true, undefined, xhr); }; this.fireCallbacks('done', args) } this.store.add(this.appNode, ns.rdfs('label'), this.store.literal('This Session'), this.appNode); ['http', 'https', 'file', 'chrome'].map(this.addProtocol); // ftp? mailto:? [$rdf.Fetcher.RDFXMLHandler, $rdf.Fetcher.XHTMLHandler, $rdf.Fetcher.XMLHandler, $rdf.Fetcher.HTMLHandler, $rdf.Fetcher.TextHandler, $rdf.Fetcher.N3Handler ].map(this.addHandler) /** Note two nodes are now smushed ** ** If only one was flagged as looked up, then ** the new node is looked up again, which ** will make sure all the URIs are dereferenced */ this.nowKnownAs = function(was, now) { if (this.lookedUp[was.uri]) { if (!this.lookedUp[now.uri]) this.lookUpThing(now, was) // @@@@ Transfer userCallback } else if (this.lookedUp[now.uri]) { if (!this.lookedUp[was.uri]) this.lookUpThing(was, now) } } // Looks up something. // // Looks up all the URIs a things has. // Parameters: // // term: canonical term for the thing whose URI is to be dereferenced // rterm: the resource which refered to this (for tracking bad links) // force: Load the data even if loaded before // oneDone: is called as callback(ok, errorbody, xhr) for each one // allDone: is called as callback(ok, errorbody) for all of them // Returns the number of things looked up // this.lookUpThing = function(term, rterm, force, oneDone, allDone) { var uris = kb.uris(term) // Get all URIs var success = true; var errors = ''; var outstanding = {}; if (typeof uris !== 'undefined') { for (var i = 0; i < uris.length; i++) { var u = uris[i]; outstanding[u] = true; this.lookedUp[u] = true; var sf = this; var requestOne = function requestOne(u1){ sf.requestURI($rdf.uri.docpart(u1), rterm, force, function(ok, body, xhr){ if (ok) { if (oneDone) oneDone(true, u1); } else { if (oneDone) oneDone(false, body); success = false; errors += body + '\n'; }; delete outstanding[u]; for (x in outstanding) return; if (allDone) allDone(success, errors); }); }; requestOne(u); } } return uris.length } /* Ask for a doc to be loaded if necessary then call back ** ** Changed 2013-08-20: Added (ok, body) params to callback ** **/ this.nowOrWhenFetched = function(uri, referringTerm, userCallback) { var sta = this.getState(uri); if (sta == 'fetched') return userCallback(true); // If it is 'failed', then shoulkd we try again? I think so so an old error doens't get stuck //if (sta == 'unrequested') this.requestURI(uri, referringTerm, false, userCallback); } // Look up response header // // Returns: a list of header values found in a stored HTTP response // or [] if response was found but no header found // or undefined if no response is available. // this.getHeader = function(doc, header) { var kb = this.store; var requests = kb.each(undefined, tabulator.ns.link("requestedURI"), doc.uri); for (var r=0; r<requests.length; r++) { var request = requests[r]; if (request !== undefined) { var response = kb.any(request, tabulator.ns.link("response")); if (request !== undefined) { var results = kb.each(response, tabulator.ns.httph(header.toLowerCase())); if (results.length) { return results.map(function(v){return v.value}); } return []; } } } return undefined; }; this.proxyIfNecessary = function(uri) { if (typeof tabulator != 'undefined' && tabulator.isExtension) return uri; // Extenstion does not need proxy // browser does 2014 on as https browser script not trusted if ($rdf.Fetcher.crossSiteProxyTemplate && document && document.location && ('' + document.location).slice(0,6) === 'https:' && uri.slice(0,5) === 'http:') { return $rdf.Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); } return uri; }; this.saveRequestMetadata = function(xhr, kb, docuri) { var request = kb.bnode(); if (typeof tabulator != 'undefined' && tabulator.isExtension) { var ns = tabulator.ns; } else { var ns = {}; ns.link = $rdf.Namespace("http://www.w3.org/2007/ont/link#"); ns.rdfs = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"); } xhr.req = request; var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(request, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + docuri), this.appNode); kb.add(request, ns.link("requestedURI"), kb.literal(docuri), this.appNode); kb.add(request, ns.link('status'), kb.collection(), this.appNode); return request; }; this.saveResponseMetadata = function(xhr, kb) { var response = kb.bnode(); // define the set of namespaces if not using tabulator if (typeof tabulator != 'undefined' && tabulator.isExtension) { var ns = tabulator.ns; } else { var ns = {}; ns.link = $rdf.Namespace("http://www.w3.org/2007/ont/link#"); ns.http = $rdf.Namespace("http://www.w3.org/2007/ont/http#"); ns.httph = $rdf.Namespace("http://www.w3.org/2007/ont/httph#"); ns.rdfs = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#"); } kb.add(xhr.req, ns.link('response'), response); kb.add(response, ns.http('status'), kb.literal(xhr.status), response); kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response); xhr.headers = {} if ($rdf.uri.protocol(xhr.resource.uri) == 'http' || $rdf.uri.protocol(xhr.resource.uri) == 'https') { xhr.headers = $rdf.Util.getHTTPHeaders(xhr) for (var h in xhr.headers) { // trim below for Safari - adds a CR! kb.add(response, ns.httph(h.toLowerCase()), xhr.headers[h].trim(), response) } } return response; }; /** Requests a document URI and arranges to load the document. ** Parameters: ** term: term for the thing whose URI is to be dereferenced ** rterm: the resource which refered to this (for tracking bad links) ** force: Load the data even if loaded before ** userCallback: Called with (true) or (false, errorbody) after load is done or failed ** Return value: ** The xhr object for the HTTP access ** null if the protocol is not a look-up protocol, ** or URI has already been loaded */ this.requestURI = function(docuri, rterm, force, userCallback) { //sources_request_new if (docuri.indexOf('#') >= 0) { // hash throw ("requestURI should not be called with fragid: " + docuri); } var pcol = $rdf.uri.protocol(docuri); if (pcol == 'tel' || pcol == 'mailto' || pcol == 'urn') return null; // No look-up operation on these, but they are not errors var force = !! force var kb = this.store var args = arguments var docterm = kb.sym(docuri) if (!force && typeof(this.requested[docuri]) != "undefined") { return null } this.fireCallbacks('request', args); //Kenny: fire 'request' callbacks here // dump( "web.js: Requesting uri: " + docuri + "\n" ); this.requested[docuri] = true if (rterm) { if (rterm.uri) { // A link betwen URIs not terms kb.add(docterm.uri, ns.link("requestedBy"), rterm.uri, this.appNode) } } if (rterm) { // $rdf.log.info('SF.request: ' + docuri + ' refd by ' + rterm.uri) } else { // $rdf.log.info('SF.request: ' + docuri + ' no referring doc') }; var useJQuery = typeof jQuery != 'undefined'; if (!useJQuery) { var xhr = $rdf.Util.XMLHTTPFactory(); var req = xhr.req = kb.bnode(); xhr.resource = docterm; xhr.requestedURI = args[0]; } else { var req = kb.bnode(); // @@ Joe, no need for xhr.req? } var requestHandlers = kb.collection(); var sf = this; var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(req, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + docuri), this.appNode) kb.add(req, ns.link("requestedURI"), kb.literal(docuri), this.appNode) kb.add(req, ns.link('status'), kb.collection(), this.appNode) // This should not be stored in the store, but in the JS data /* if (typeof kb.anyStatementMatching(this.appNode, ns.link("protocol"), $rdf.uri.protocol(docuri)) == "undefined") { // update the status before we break out this.failFetch(xhr, "Unsupported protocol: "+$rdf.uri.protocol(docuri)) return xhr } */ var onerrorFactory = function(xhr) { return function(event) { if ($rdf.Fetcher.crossSiteProxyTemplate && document && document.location && !xhr.proxyUsed) { // In mashup situation var hostpart = $rdf.uri.hostpart; var here = '' + document.location; var uri = xhr.resource.uri if (hostpart(here) && hostpart(uri) && hostpart(here) != hostpart(uri)) { newURI = $rdf.Fetcher.crossSiteProxy(uri); sf.addStatus(xhr.req, "BLOCKED -> Cross-site Proxy to <" + newURI + ">"); if (xhr.aborted) return; var kb = sf.store; var oldreq = xhr.req; kb.add(oldreq, ns.http('redirectedTo'), kb.sym(newURI), oldreq); ////////////// Change the request node to a new one: @@@@@@@@@@@@ Duplicate of what will be done by requestURI below /* var newreq = xhr.req = kb.bnode() // Make NEW reqest for everything else kb.add(oldreq, ns.http('redirectedRequest'), newreq, xhr.req); var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(newreq, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + newURI), this.appNode) kb.add(newreq, ns.link('status'), kb.collection(), this.appNode); kb.add(newreq, ns.link("requestedURI"), kb.literal(newURI), this.appNode); var response = kb.bnode(); kb.add(oldreq, ns.link('response'), response); */ // kb.add(response, ns.http('status'), kb.literal(xhr.status), response); // if (xhr.statusText) kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response) xhr.abort() xhr.aborted = true sf.addStatus(oldreq, 'done - redirected') // why //the callback throws an exception when called from xhr.onerror (so removed) //sf.fireCallbacks('done', args) // Are these args right? @@@ Noit done yet! done means success sf.requested[xhr.resource.uri] = 'redirected'; var xhr2 = sf.requestURI(newURI, xhr.resource, force, userCallback); xhr2.proxyUsed = true; //only try the proxy once if (xhr2 && xhr2.req) { kb.add(xhr.req, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), xhr2.req, sf.appNode); return; } } } else { if (xhr.withCredentials) { xhr.abort(); xhr.withCredentials = false; sf.addStatus(xhr.req, "Credentials SUPPRESSED to see if that helps"); xhr.send(); // try again } else { sf.failFetch(xhr, "XHR Error: "+event); // Alas we get no error message } } }; } // Set up callbacks var onreadystatechangeFactory = function(xhr) { return function() { var handleResponse = function() { if (xhr.handleResponseDone) return; xhr.handleResponseDone = true; var handler = null; var thisReq = xhr.req // Might have changes by redirect sf.fireCallbacks('recv', args) var kb = sf.store; sf.saveResponseMetadata(xhr, kb); sf.fireCallbacks('headers', [{uri: docuri, headers: xhr.headers}]); if (xhr.status >= 400) { // For extra dignostics, keep the reply // @@@ 401 should cause a retry with credential son // @@@ cache the credentials flag by host ???? if (xhr.responseText.length > 10) { kb.add(response, ns.http('content'), kb.literal(xhr.responseText), response); // dump("HTTP >= 400 responseText:\n"+xhr.responseText+"\n"); // @@@@ } sf.failFetch(xhr, "HTTP error for " +xhr.resource + ": "+ xhr.status + ' ' + xhr.statusText); return; } var loc = xhr.headers['content-location']; // deduce some things from the HTTP transaction var addType = function(cla) { // add type to all redirected resources too var prev = thisReq; if (loc) { var docURI = kb.any(prev, ns.link('requestedURI')); if (docURI != loc) { kb.add(kb.sym(loc), ns.rdf('type'), cla, sf.appNode); } } for (;;) { var doc = kb.any(prev, ns.link('requestedURI')); if (doc && doc.value) // convert Literal kb.add(kb.sym(doc.value), ns.rdf('type'), cla, sf.appNode); prev = kb.any(undefined, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), prev); if (!prev) break; var response = kb.any(prev, kb.sym('http://www.w3.org/2007/ont/link#response')); if (!response) break; var redirection = kb.any(response, kb.sym('http://www.w3.org/2007/ont/http#status')); if (!redirection) break; if (redirection != '301' && redirection != '302') break; } } if (xhr.status == 200) { addType(ns.link('Document')); var ct = xhr.headers['content-type']; if (ct) { if (ct.indexOf('image/') == 0 || ct.indexOf('application/pdf') == 0) addType(kb.sym('http://purl.org/dc/terms/Image')); } } if ($rdf.uri.protocol(xhr.resource.uri) == 'file' || $rdf.uri.protocol(xhr.resource.uri) == 'chrome') { switch (xhr.resource.uri.split('.').pop()) { case 'rdf': case 'owl': xhr.headers['content-type'] = 'application/rdf+xml'; break; case 'n3': case 'nt': case 'ttl': xhr.headers['content-type'] = 'text/n3'; break; default: xhr.headers['content-type'] = 'text/xml'; } } // If we have alread got the thing at this location, abort if (loc) { var udoc = $rdf.uri.join(xhr.resource.uri, loc) if (!force && udoc != xhr.resource.uri && sf.requested[udoc]) { // should we smush too? // $rdf.log.info("HTTP headers indicate we have already" + " retrieved " + xhr.resource + " as " + udoc + ". Aborting.") sf.doneFetch(xhr, args) xhr.abort() return } sf.requested[udoc] = true } for (var x = 0; x < sf.handlers.length; x++) { if (xhr.headers['content-type'] && xhr.headers['content-type'].match(sf.handlers[x].pattern)) { handler = new sf.handlers[x](); requestHandlers.append(sf.handlers[x].term) // FYI break } } var link; try { link = xhr.getResponseHeader('link'); }catch(e){} if (link) { var rel = null; var arg = link.replace(/ /g, '').split(';'); for (var i = 1; i < arg.length; i++) { lr = arg[i].split('='); if (lr[0] == 'rel') rel = lr[1]; } var v = arg[0]; // eg. Link: <.meta>, rel=meta if (v.length && v[0] == '<' && v[v.length-1] == '>' && v.slice) v = v.slice(1, -1); if (rel) // Treat just like HTML link element sf.linkData(xhr, rel, v); } if (handler) { try { handler.handlerFactory(xhr); } catch(e) { // Try to avoid silent errors sf.failFetch(xhr, "Exception handling content-type " + xhr.headers['content-type'] + ' was: '+e); }; } else { sf.doneFetch(xhr, args); // Not a problem, we just don't extract data. /* // sf.failFetch(xhr, "Unhandled content type: " + xhr.headers['content-type']+ // ", readyState = "+xhr.readyState); */ return; } }; // DONE: 4 // HEADERS_RECEIVED: 2 // LOADING: 3 // OPENED: 1 // UNSENT: 0 // $rdf.log.debug("web.js: XHR " + xhr.resource.uri + ' readyState='+xhr.readyState); // @@@@ comment me out switch (xhr.readyState) { case 0: var uri = xhr.resource.uri, newURI; if (this.crossSiteProxyTemplate && document && document.location) { // In mashup situation var hostpart = $rdf.uri.hostpart; var here = '' + document.location; if (hostpart(here) && hostpart(uri) && hostpart(here) != hostpart(uri)) { newURI = this.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); sf.addStatus(xhr.req, "BLOCKED -> Cross-site Proxy to <" + newURI + ">"); if (xhr.aborted) return; var kb = sf.store; var oldreq = xhr.req; kb.add(oldreq, ns.http('redirectedTo'), kb.sym(newURI), oldreq); ////////////// Change the request node to a new one: @@@@@@@@@@@@ Duplicate? var newreq = xhr.req = kb.bnode() // Make NEW reqest for everything else kb.add(oldreq, ns.http('redirectedRequest'), newreq, xhr.req); var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(newreq, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + newURI), this.appNode) kb.add(newreq, ns.link('status'), kb.collection(), this.appNode); kb.add(newreq, ns.link("requestedURI"), kb.literal(newURI), this.appNode); var response = kb.bnode(); kb.add(oldreq, ns.link('response'), response); // kb.add(response, ns.http('status'), kb.literal(xhr.status), response); // if (xhr.statusText) kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response) xhr.abort() xhr.aborted = true sf.addStatus(oldreq, 'done') // why if (xhr.userCallback) { xhr.userCallback(true); }; sf.fireCallbacks('done', args) // Are these args right? @@@ sf.requested[xhr.resource.uri] = 'redirected'; var xhr2 = sf.requestURI(newURI, xhr.resource); if (xhr2 && xhr2.req) kb.add(xhr.req, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), xhr2.req, sf.appNode); return; } } sf.failFetch(xhr, "HTTP Blocked. (ReadyState 0) Cross-site violation for <"+ docuri+">"); break; case 3: // Intermediate state -- 3 may OR MAY NOT be called, selon browser. // handleResponse(); // In general it you can't do it yet as the headers are in but not the data break case 4: // Final state handleResponse(); // Now handle if (xhr.handle) { if (sf.requested[xhr.resource.uri] === 'redirected') { break; } sf.fireCallbacks('load', args) xhr.handle(function() { sf.doneFetch(xhr, args) }) } else { sf.addStatus(xhr.req, "Fetch OK. No known semantics."); sf.doneFetch(xhr, args); //sf.failFetch(xhr, "HTTP failed unusually. (no handler set) (x-site violation? no net?) for <"+ // docuri+">"); } break } // switch }; } // Map the URI to a localhost proxy if we are running on localhost // This is used for working offline, e.g. on planes. // Is the script istelf is running in localhost, then access all data in a localhost mirror. // Do not remove without checking with TimBL :) var uri2 = docuri; if (typeof tabulator != 'undefined' && tabulator.preferences.get('offlineModeUsingLocalhost')) { if (uri2.slice(0,7) == 'http://' && uri2.slice(7,17) != 'localhost/') { uri2 = 'http://localhost/' + uri2.slice(7); $rdf.log.warn("Localhost kludge for offline use: actually getting <" + uri2 + ">"); } else { // $rdf.log.warn("Localhost kludge NOT USED <" + uri2 + ">"); }; } else { // $rdf.log.warn("Localhost kludge OFF offline use: actually getting <" + uri2 + ">"); } // 2014 probelm: // XMLHttpRequest cannot load http://www.w3.org/People/Berners-Lee/card. // A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. // @ Many ontology files under http: and need CORS wildcard -> can't have withCredentials var withCredentials = ( uri2.slice(0,6) === 'https:'); // @@ Kludge -- need for webid which typically is served from https var actualProxyURI = this.proxyIfNecessary(uri2); // Setup the request if (typeof jQuery !== 'undefined' && jQuery.ajax) { var xhr = jQuery.ajax({ url: actualProxyURI, accepts: {'*': 'text/turtle,text/n3,application/rdf+xml'}, processData: false, xhrFields: { withCredentials: withCredentials }, timeout: sf.timeout, error: function(xhr, s, e) { xhr.req = req; // Add these in case fails before .ajax returns xhr.userCallback = userCallback; xhr.resource = docterm; xhr.requestedURI = uri2; if (s == 'timeout') sf.failFetch(xhr, "requestTimeout"); else onerrorFactory(xhr)(e); }, success: function(d, s, xhr) { xhr.req = req; xhr.userCallback = userCallback; xhr.resource = docterm; xhr.requestedURI = uri2; onreadystatechangeFactory(xhr)(); } }); xhr.req = req; xhr.userCallback = userCallback; xhr.resource = docterm; xhr.requestedURI = uri2; xhr.actualProxyURI = actualProxyURI; } else { var xhr = $rdf.Util.XMLHTTPFactory(); xhr.onerror = onerrorFactory(xhr); xhr.onreadystatechange = onreadystatechangeFactory(xhr); xhr.timeout = sf.timeout; xhr.withCredentials = withCredentials; xhr.actualProxyURI = actualProxyURI; xhr.req = req; xhr.userCallback = userCallback; xhr.resource = docterm; xhr.requestedURI = uri2; xhr.ontimeout = function () { sf.failFetch(xhr, "requestTimeout"); } try { xhr.open('GET', actualProxyURI, this.async); } catch (er) { return this.failFetch(xhr, "XHR open for GET failed for <"+uri2+">:\n\t" + er); } } // Set redirect callback and request headers -- alas Firefox Extension Only if (typeof tabulator != 'undefined' && tabulator.isExtension && xhr.channel && ($rdf.uri.protocol(xhr.resource.uri) == 'http' || $rdf.uri.protocol(xhr.resource.uri) == 'https')) { try { xhr.channel.notificationCallbacks = { getInterface: function(iid) { if (iid.equals(Components.interfaces.nsIChannelEventSink)) { return { onChannelRedirect: function(oldC, newC, flags) { if (xhr.aborted) return; var kb = sf.store; var newURI = newC.URI.spec; var oldreq = xhr.req; sf.addStatus(xhr.req, "Redirected: " + xhr.status + " to <" + newURI + ">"); kb.add(oldreq, ns.http('redirectedTo'), kb.sym(newURI), xhr.req); ////////////// Change the request node to a new one: @@@@@@@@@@@@ Duplicate? var newreq = xhr.req = kb.bnode() // Make NEW reqest for everything else // xhr.resource = docterm // xhr.requestedURI = args[0] // var requestHandlers = kb.collection() // kb.add(kb.sym(newURI), ns.link("request"), req, this.appNode) kb.add(oldreq, ns.http('redirectedRequest'), newreq, xhr.req); var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(newreq, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + newURI), this.appNode) kb.add(newreq, ns.link('status'), kb.collection(), this.appNode) kb.add(newreq, ns.link("requestedURI"), kb.literal(newURI), this.appNode) /////////////// //// $rdf.log.info('@@ sources onChannelRedirect'+ // "Redirected: "+ // xhr.status + " to <" + newURI + ">"); //@@ var response = kb.bnode(); // kb.add(response, ns.http('location'), newURI, response); Not on this response kb.add(oldreq, ns.link('response'), response); kb.add(response, ns.http('status'), kb.literal(xhr.status), response); if (xhr.statusText) kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response) if (xhr.status - 0 != 303) kb.HTTPRedirects[xhr.resource.uri] = newURI; // same document as if (xhr.status - 0 == 301 && rterm) { // 301 Moved var badDoc = $rdf.uri.docpart(rterm.uri); var msg = 'Warning: ' + xhr.resource + ' has moved to <' + newURI + '>.'; if (rterm) { msg += ' Link in <' + badDoc + ' >should be changed'; kb.add(badDoc, kb.sym('http://www.w3.org/2007/ont/link#warning'), msg, sf.appNode); } // dump(msg+"\n"); } xhr.abort() xhr.aborted = true sf.addStatus(oldreq, 'done') // why sf.fireCallbacks('done', args) // Are these args right? @@@ sf.requested[xhr.resource.uri] = 'redirected'; var hash = newURI.indexOf('#'); if (hash >= 0) { var msg = ('Warning: ' + xhr.resource + ' HTTP redirects to' + newURI + ' which should not contain a "#" sign'); // dump(msg+"\n"); kb.add(xhr.resource, kb.sym('http://www.w3.org/2007/ont/link#warning'), msg) newURI = newURI.slice(0, hash); } var xhr2 = sf.requestURI(newURI, xhr.resource); if (xhr2 && xhr2.req) kb.add(xhr.req, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), xhr2.req, sf.appNode); // else dump("No xhr.req available for redirect from "+xhr.resource+" to "+newURI+"\n") }, // See https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIChannelEventSink asyncOnChannelRedirect: function(oldC, newC, flags, callback) { if (xhr.aborted) return; var kb = sf.store; var newURI = newC.URI.spec; var oldreq = xhr.req; sf.addStatus(xhr.req, "Redirected: " + xhr.status + " to <" + newURI + ">"); kb.add(oldreq, ns.http('redirectedTo'), kb.sym(newURI), xhr.req); ////////////// Change the request node to a new one: @@@@@@@@@@@@ Duplicate? var newreq = xhr.req = kb.bnode() // Make NEW reqest for everything else // xhr.resource = docterm // xhr.requestedURI = args[0] // var requestHandlers = kb.collection() // kb.add(kb.sym(newURI), ns.link("request"), req, this.appNode) kb.add(oldreq, ns.http('redirectedRequest'), newreq, xhr.req); var now = new Date(); var timeNow = "[" + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "] "; kb.add(newreq, ns.rdfs("label"), kb.literal(timeNow + ' Request for ' + newURI), this.appNode) kb.add(newreq, ns.link('status'), kb.collection(), this.appNode) kb.add(newreq, ns.link("requestedURI"), kb.literal(newURI), this.appNode) /////////////// //// $rdf.log.info('@@ sources onChannelRedirect'+ // "Redirected: "+ // xhr.status + " to <" + newURI + ">"); //@@ var response = kb.bnode(); // kb.add(response, ns.http('location'), newURI, response); Not on this response kb.add(oldreq, ns.link('response'), response); kb.add(response, ns.http('status'), kb.literal(xhr.status), response); if (xhr.statusText) kb.add(response, ns.http('statusText'), kb.literal(xhr.statusText), response) if (xhr.status - 0 != 303) kb.HTTPRedirects[xhr.resource.uri] = newURI; // same document as if (xhr.status - 0 == 301 && rterm) { // 301 Moved var badDoc = $rdf.uri.docpart(rterm.uri); var msg = 'Warning: ' + xhr.resource + ' has moved to <' + newURI + '>.'; if (rterm) { msg += ' Link in <' + badDoc + ' >should be changed'; kb.add(badDoc, kb.sym('http://www.w3.org/2007/ont/link#warning'), msg, sf.appNode); } // dump(msg+"\n"); } xhr.abort() xhr.aborted = true sf.addStatus(oldreq, 'done') // why if (xhr.userCallback) { xhr.userCallback(true); }; sf.fireCallbacks('done', args) // Are these args right? @@@ sf.requested[xhr.resource.uri] = 'redirected'; var hash = newURI.indexOf('#'); if (hash >= 0) { var msg = ('Warning: ' + xhr.resource + ' HTTP redirects to' + newURI + ' which should not contain a "#" sign'); // dump(msg+"\n"); kb.add(xhr.resource, kb.sym('http://www.w3.org/2007/ont/link#warning'), msg) newURI = newURI.slice(0, hash); } var xhr2 = sf.requestURI(newURI, xhr.resource); if (xhr2 && xhr2.req) kb.add(xhr.req, kb.sym('http://www.w3.org/2007/ont/link#redirectedRequest'), xhr2.req, sf.appNode); // else dump("No xhr.req available for redirect from "+xhr.resource+" to "+newURI+"\n") } // asyncOnChannelRedirect } } return Components.results.NS_NOINTERFACE } } } catch (err) { return sf.failFetch(xhr, "@@ Couldn't set callback for redirects: " + err); } } try { var acceptstring = "" for (var type in this.mediatypes) { var attrstring = "" if (acceptstring != "") { acceptstring += ", " } acceptstring += type for (var attr in this.mediatypes[type]) { acceptstring += ';' + attr + '=' + this.mediatypes[type][attr] } } xhr.setRequestHeader('Accept', acceptstring) // $rdf.log.info('Accept: ' + acceptstring) // See http://dig.csail.mit.edu/issues/tabulator/issue65 //if (requester) { xhr.setRequestHeader('Referer',requester) } } catch (err) { throw ("Can't set Accept header: " + err) } // Fire if (!useJQuery) { try { xhr.send(null) } catch (er) { return this.failFetch(xhr, "XHR send failed:" + er); } setTimeout(function() { if (xhr.readyState != 4 && sf.isPending(xhr.resource.uri)) { sf.failFetch(xhr, "requestTimeout") } }, this.timeout); this.addStatus(xhr.req, "HTTP Request sent."); } else { this.addStatus(xhr.req, "HTTP Request sent (using jQuery)"); } return xhr } // this.requested[docuri]) != "undefined" this.objectRefresh = function(term) { var uris = kb.uris(term) // Get all URIs if (typeof uris != 'undefined') { for (var i = 0; i < uris.length; i++) { this.refresh(this.store.sym($rdf.uri.docpart(uris[i]))); //what about rterm? } } } this.unload = function(term) { this.store.removeMany(undefined, undefined, undefined, term) delete this.requested[term.uri]; // So it can be loaded again } this.refresh = function(term) { // sources_refresh this.unload(term); this.fireCallbacks('refresh', arguments) this.requestURI(term.uri, undefined, true) } this.retract = function(term) { // sources_retract this.store.removeMany(undefined, undefined, undefined, term) if (term.uri) { delete this.requested[$rdf.uri.docpart(term.uri)] } this.fireCallbacks('retract', arguments) } this.getState = function(docuri) { // docState if (typeof this.requested[docuri] != "undefined") { if (this.requested[docuri]) { if (this.isPending(docuri)) { return "requested" } else { return "fetched" } } else { return "failed" } } else { return "unrequested" } } //doing anyStatementMatching is wasting time this.isPending = function(docuri) { // sources_pending //if it's not pending: false -> flailed 'done' -> done 'redirected' -> redirected return this.requested[docuri] == true; } var updatesVia = new $rdf.UpdatesVia(this); }; $rdf.fetcher = function(store, timeout, async) { return new $rdf.Fetcher(store, timeout, async) }; // Parse a string and put the result into the graph kb $rdf.parse = function parse(str, kb, base, contentType) { try { /* parseXML = function(str) { var dparser; if ((typeof tabulator != 'undefined' && tabulator.isExtension)) { dparser = Components.classes["@mozilla.org/xmlextras/domparser;1"].getService( Components.interfaces.nsIDOMParser); } else if (typeof module != 'undefined' ){ // Node.js var jsdom = require('jsdom'); return jsdom.jsdom(str, undefined, {} );// html, level, options } else { dparser = new DOMParser() } return dparser.parseFromString(str, 'application/xml'); } */ if (contentType == 'text/n3' || contentType == 'text/turtle') { var p = $rdf.N3Parser(kb, kb, base, base, null, null, "", null) p.loadBuf(str) return; } if (contentType == 'application/rdf+xml') { var parser = new $rdf.RDFParser(kb); parser.parse($rdf.Util.parseXML(str), base, kb.sym(base)); return; } if (contentType == 'application/rdfa') { // @@ not really a valid mime type if ($rdf.rdfa && $rdf.rdfa.parse) $rdf.rdfa.parse($rdf.Util.parseXML(str), kb, base); return; } if (contentType == 'application/sparql-update') { // @@ we handle a subset spaqlUpdateParser(store, str, base) if ($rdf.rdfa && $rdf.rdfa.parse) $rdf.rdfa.parse($rdf.Util.parseXML(str), kb, base); return; } } catch(e) { throw "Error trying to parse <"+base+"> as "+contentType+":\n"+e +':\n'+e.stack; } throw "Don't know how to parse "+contentType+" yet"; }; // Serialize to the appropriate format // $rdf.serialize = function(target, kb, base, contentType, callback) { var documentString; var sz = $rdf.Serializer(kb); var newSts = kb.statementsMatching(undefined, undefined, undefined, target); sz.suggestNamespaces(kb.namespaces); sz.setBase(base); switch(contentType){ case 'application/rdf+xml': documentString = sz.statementsToXML(newSts); break; case 'text/n3': case 'text/turtle': case 'application/x-turtle': // Legacy case 'application/n3': // Legacy documentString = sz.statementsToN3(newSts); break; case 'application/json+ld': var n3String = sz.statementsToN3(newSts); convertToJson(n3String, callback); break; case 'application/n-quads': case 'application/nquads': // @@@ just outpout the quads? Does not work for collections var n3String = sz.statementsToN3(newSts); documentString = convertToNQuads(n3String, callback); break; default: throw "serialise: Content-type "+content_type +" not supported for data write"; } return documentString; }; ////////////////// JSON-LD code currently requires Node if (typeof module !== 'undefined' && module.require) { // Node var asyncLib = require('async'); var jsonld = require('jsonld'); var N3 = require('n3'); var convertToJson = function(n3String, jsonCallback) { var jsonString = undefined; var n3Parser = N3.Parser(); var n3Writer = N3.Writer({ format: 'N-Quads' }); asyncLib.waterfall([ function(callback) { n3Parser.parse(n3String, callback); }, function(triple, prefix, callback) { if (triple !== null) { n3Writer.addTriple(triple); } if (typeof callback === 'function') { n3Writer.end(callback); } }, function(result, callback) { try { jsonld.fromRDF(result, { format: 'application/nquads' }, callback); } catch (err) { callback(err); } }, function(json, callback) { jsonString = JSON.stringify(json); jsonCallback(null, jsonString); } ], function(err, result) { jsonCallback(err, jsonString); }); } var convertToNQuads = function(n3String, nquadCallback) { var nquadString = undefined; var n3Parser = N3.Parser(); var n3Writer = N3.Writer({ format: 'N-Quads' }); asyncLib.waterfall([ function(callback) { n3Parser.parse(n3String, callback); }, function(triple, prefix, callback) { if (triple !== null) { n3Writer.addTriple(triple); } if (typeof callback === 'function') { n3Writer.end(callback); } }, function(result, callback) { nquadString = result; nquadCallback(null, nquadString); }, ], function(err, result) { nquadCallback(err, nquadString); }); } } // ends
Added r flag to serializer
web.js
Added r flag to serializer
<ide><path>eb.js <ide> var newSts = kb.statementsMatching(undefined, undefined, undefined, target); <ide> sz.suggestNamespaces(kb.namespaces); <ide> sz.setBase(base); <add> sz.setFlags('r'); <ide> switch(contentType){ <ide> case 'application/rdf+xml': <ide> documentString = sz.statementsToXML(newSts);
Java
apache-2.0
f9e7e7e30ece588776ba03ad52a696f4e4941e1d
0
SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java
/* * Copyright 2018, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.integration; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.Message; import io.spine.base.Error; import io.spine.core.Rejection; import io.spine.core.RejectionClass; import static com.google.common.base.Preconditions.checkArgument; /** * An abstract verifier of Bounded Context acknowledgements. Its intended to be executed by the * {@link BlackBoxBoundedContext Black Box Bounded Context}. Its implementations throw assertion * errors if the acknowledgements observed in the Bounded Context do not meet the verifier criteria. * * <p>Contains static factory methods for creating acknowledgement verifiers, checking that * commands were acknowledged, responded with rejections, and errors. * * <p>Allows combining verifiers using {@link #and(AcknowledgementsVerifier) and()} or factory method * shortcuts: {@code ackedWithoutErrors().and(ackedWithRejection(rej))} can be simplified * to {@code ackedWithoutErrors().withRejection(rej)}. * * @author Mykhailo Drachuk */ @SuppressWarnings("ClassWithTooManyMethods") @VisibleForTesting public abstract class AcknowledgementsVerifier { /** * Executes the acknowledgement verifier throwing an assertion error if the * data does not match the rule.. * * @param acks acknowledgements of handling commands by the Bounded Context */ public abstract void verify(Acknowledgements acks); /** * Verifies that Bounded Context responded with a specified number of acknowledgements. * * @param expectedCount an expected amount of acknowledgements observed in Bounded Context * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier acked(int expectedCount) { checkArgument(expectedCount >= 0, "0 or more acknowledgements must be expected."); return new AcksCountVerifier(expectedCount); } /* * Factory methods for verifying acks with errors. ******************************************************************************/ /** * Verifies that the command handling did not respond with {@link Error error}. * * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithoutErrors() { return new AcksErrorAbsenceVerifier(); } /** * Verifies that a command or an event was handled responding with some {@link Error error}. * * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithErrors() { return new AcksErrorPresenceVerifier(); } /** * Verifies that a command or an event was handled responding with specified number of * {@link Error errors}. * * @param expectedCount an amount of errors that are expected to match the qualifier * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithErrors(int expectedCount) { checkArgument(expectedCount >= 0, "0 or more errors must be expected."); return new AcksErrorCountVerifier(expectedCount); } /** * Verifies that a command or an event was handled responding with an error matching a provided * {@link ErrorQualifier error qualifier}. * * @param qualifier an error qualifier specifying which kind of error should be a part * of acknowledgement * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithErrors(ErrorQualifier qualifier) { return new AcksSpecificErrorPresenceVerifier(qualifier); } /** * Verifies that a command or an event was handled responding with an error matching a provided * {@link ErrorQualifier error qualifier}. * * @param expectedCount an amount of errors that are expected to match the qualifier * @param qualifier an error qualifier specifying which kind of error should be a part * of acknowledgement * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithErrors(int expectedCount, ErrorQualifier qualifier) { checkArgument(expectedCount >= 0, "0 or more errors matching qualifier must be expected."); return new AcksSpecificErrorCountVerifier(expectedCount, qualifier); } /* * Factory methods for verifying acks with rejections. ******************************************************************************/ /** * Verifies that a command handling did not respond with any {@link Rejection rejections}. * * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithoutRejections() { return new AcksRejectionAbsenceVerifier(); } /** * Verifies that a command or an event was handled responding with some * {@link Rejection rejection}. * * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections() { return new AcksRejectionPresenceVerifier(); } /** * Verifies that a command or an event was handled responding with a {@link Rejection rejection} * of the provided type. * * @param type rejection type in a form of message class * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(Class<? extends Message> type) { RejectionClass rejectionClass = RejectionClass.of(type); return ackedWithRejections(rejectionClass); } /** * Verifies that a command or an event was handled responding with a {@link Rejection rejection} * of the provided type. * * @param type rejection type in a form of {@link RejectionClass RejectionClass} * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(RejectionClass type) { return new AcksRejectionOfTypePresenceVerifier(type); } /** * Verifies that a command or an event was handled responding with rejection matching the * provided predicate. * * @param type a type of a domain rejection specified by a message class * @param predicate a predicate filtering the domain rejections * @param <T> a domain rejection type * @return a new {@link AcknowledgementsVerifier} instance */ public static <T extends Message> AcknowledgementsVerifier ackedWithRejections(Class<T> type, RejectionPredicate<T> predicate) { return new AcksSpecificRejectionPresenceVerifier<>(type, predicate); } /** * Verifies that a command or an event was handled responding with a rejection specified * amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(int expectedCount) { checkArgument(expectedCount >= 0, "0 or more rejections must be expected."); return new AcksRejectionCountVerifier(expectedCount); } /** * Verifies that a command or an event was handled responding with a {@link Rejection rejection} * of a provided type specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type rejection type in a form of message class * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(int expectedCount, Class<? extends Message> type) { checkArgument(expectedCount >= 0, "0 or more rejections of rejections of message class type must be expected."); RejectionClass rejectionClass = RejectionClass.of(type); return ackedWithRejections(expectedCount, rejectionClass); } /** * Verifies that a command or an event was handled responding with a {@link Rejection rejection} * of a provided type specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type rejection type in a form of {@link RejectionClass RejectionClass} * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(int expectedCount, RejectionClass type) { checkArgument(expectedCount >= 0, "0 or more rejections of rejecetions of class must be expected."); return new AcksRejectionOfTypeCountVerifier(type, expectedCount); } /** * Verifies that a command or an event was handled responding with a provided domain rejection * specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type a type of a domain rejection specified by a message class * @param predicate a predicate filtering domain rejections * @param <T> a domain rejection type * @return a new {@link AcknowledgementsVerifier} instance */ public static <T extends Message> AcknowledgementsVerifier ackedWithRejections(int expectedCount, Class<T> type, RejectionPredicate<T> predicate) { checkArgument(expectedCount >= 0, "0 or more specified rejections must be expected."); return new AcksSpecificRejectionCountVerifier<>(expectedCount, type, predicate); } /* * Verifier combination shortcuts. ******************************************************************************/ /** * Combines current verifier with a provided verifier, making them execute sequentially. * * @param otherVerifier a verifier executed after the current verifier * @return a verifier that executes both current and provided assertions */ public AcknowledgementsVerifier and(AcknowledgementsVerifier otherVerifier) { return AcksVerifierCombination.of(this, otherVerifier); } /** * Creates a new verifier adding a check to not contain any {@link Error errors}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withoutErrors() { AcknowledgementsVerifier noErrors = ackedWithoutErrors(); return this.and(noErrors); } /** * Creates a new verifier adding a check to contain at least one {@link Error error}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withErrors() { AcknowledgementsVerifier withError = ackedWithErrors(); return this.and(withError); } /** * Creates a new verifier adding a check to contain specified amount of {@link Error errors}. * * @param expectedCount an amount of errors that are expected to be observed in Bounded Context * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withErrors(int expectedCount) { AcknowledgementsVerifier withError = ackedWithErrors(expectedCount); return this.and(withError); } /** * Creates a new verifier adding a check to contain an {@link Error error} that * matches the qualifier. * * @param qualifier an error qualifier specifying which kind of error should be a part * of acknowledgement * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withErrors(ErrorQualifier qualifier) { AcknowledgementsVerifier withError = ackedWithErrors(qualifier); return this.and(withError); } /** * Creates a new verifier adding a check to contain an {@link Error error} that * matches the qualifier. * * @param expectedCount an amount of errors that are expected to match the qualifier * @param qualifier an error qualifier specifying which kind of error should be a part * of acknowledgement * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withErrors(int expectedCount, ErrorQualifier qualifier) { AcknowledgementsVerifier withError = ackedWithErrors(expectedCount, qualifier); return this.and(withError); } /** * Creates a new verifier adding a check to not contain any {@link Error errors} or * {@link Rejection rejections}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withoutErrorsOrRejections() { AcknowledgementsVerifier noRejections = ackedWithoutRejections(); AcknowledgementsVerifier noErrors = ackedWithoutErrors(); return this.and(noErrors.and(noRejections)); } /** * Creates a new verifier adding a check to not contain any {@link Rejection rejections}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withoutRejections() { AcknowledgementsVerifier noRejections = ackedWithoutRejections(); return this.and(noRejections); } /** * Creates a new verifier adding a check to contain some {@link Rejection rejection}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections() { AcknowledgementsVerifier someRejection = ackedWithRejections(); return this.and(someRejection); } /** * Creates a new verifier adding a check to contain a {@link Rejection rejection} of a * type specified by {@code class}. * * @param type a type of a domain rejection specified by message class * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections(Class<? extends Message> type) { AcknowledgementsVerifier rejectedType = ackedWithRejections(type); return this.and(rejectedType); } /** * Creates a new verifier adding a check to contain a {@link Rejection rejection} of a * type specified by a {@link RejectionClass rejection class}. * * @param type a type of a domain rejection specified by a {@link RejectionClass} * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections(RejectionClass type) { AcknowledgementsVerifier rejectedType = ackedWithRejections(type); return this.and(rejectedType); } /** * Creates a new verifier adding a check to contain a {@link Rejection rejection} of a * type specified by a {@link RejectionClass rejection class} specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type rejection type in a form of message class * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections(int expectedCount, Class<? extends Message> type) { AcknowledgementsVerifier rejectedType = ackedWithRejections(expectedCount, type); return this.and(rejectedType); } /** * Creates a new verifier adding a check to contain a {@link Rejection rejection} of a * type specified by a {@link RejectionClass rejection class} specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type rejection type in a form of {@link RejectionClass RejectionClass} * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections(int expectedCount, RejectionClass type) { AcknowledgementsVerifier rejectedType = ackedWithRejections(expectedCount, type); return this.and(rejectedType); } /** * Creates a new verifier adding a check to contain a provided domain rejection. * * @param type a type of a domain rejection specified by a {@link RejectionClass} * @param predicate a predicate filtering domain rejections * @param <T> a domain rejection type * @return a new {@link AcknowledgementsVerifier} instance */ public <T extends Message> AcknowledgementsVerifier withRejections(Class<T> type, RejectionPredicate<T> predicate) { AcknowledgementsVerifier oneRejection = ackedWithRejections(type, predicate); return this.and(oneRejection); } /** * Creates a new verifier adding a check to contain a provided domain rejection. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type a type of a domain rejection specified by a {@link RejectionClass} * @param predicate a predicate filtering domain rejections * @param <T> a domain rejection type * @return a new {@link AcknowledgementsVerifier} instance */ public <T extends Message> AcknowledgementsVerifier withRejections(int expectedCount, Class<T> type, RejectionPredicate<T> predicate) { AcknowledgementsVerifier oneRejection = ackedWithRejections(expectedCount, type, predicate); return this.and(oneRejection); } }
testutil-server/src/main/java/io/spine/server/integration/AcknowledgementsVerifier.java
/* * Copyright 2018, TeamDev Ltd. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.integration; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.Message; import io.spine.base.Error; import io.spine.core.Rejection; import io.spine.core.RejectionClass; import static com.google.common.base.Preconditions.checkArgument; /** * An abstract verifier of acknowledgements. * * <p>Contains static factory methods for creating acknowledgement verifiers, checking that * commands were acknowledged, responded with rejections, and errors. * * <p>Allows combining verifiers using {@link #and(AcknowledgementsVerifier) and()} or factory method * shortcuts: {@code ackedWithoutErrors().and(ackedWithRejection(rej))} can be simplified * to {@code ackedWithoutErrors().withRejection(rej)}. * * @author Mykhailo Drachuk */ @SuppressWarnings("ClassWithTooManyMethods") @VisibleForTesting public abstract class AcknowledgementsVerifier { /** * Executes the acknowledgement verifier throwing an assertion error if the * data does not match the rule.. * * @param acks acknowledgements of handling commands by the Bounded Context */ public abstract void verify(Acknowledgements acks); /** * Verifies that Bounded Context responded with a specified number of acknowledgements. * * @param expectedCount an expected amount of acknowledgements observed in Bounded Context * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier acked(int expectedCount) { checkArgument(expectedCount >= 0, "0 or more acknowledgements must be expected."); return new AcksCountVerifier(expectedCount); } /* * Factory methods for verifying acks with errors. ******************************************************************************/ /** * Verifies that the command handling did not respond with {@link Error error}. * * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithoutErrors() { return new AcksErrorAbsenceVerifier(); } /** * Verifies that a command or an event was handled responding with some {@link Error error}. * * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithErrors() { return new AcksErrorPresenceVerifier(); } /** * Verifies that a command or an event was handled responding with specified number of * {@link Error errors}. * * @param expectedCount an amount of errors that are expected to match the qualifier * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithErrors(int expectedCount) { checkArgument(expectedCount >= 0, "0 or more errors must be expected."); return new AcksErrorCountVerifier(expectedCount); } /** * Verifies that a command or an event was handled responding with an error matching a provided * {@link ErrorQualifier error qualifier}. * * @param qualifier an error qualifier specifying which kind of error should be a part * of acknowledgement * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithErrors(ErrorQualifier qualifier) { return new AcksSpecificErrorPresenceVerifier(qualifier); } /** * Verifies that a command or an event was handled responding with an error matching a provided * {@link ErrorQualifier error qualifier}. * * @param expectedCount an amount of errors that are expected to match the qualifier * @param qualifier an error qualifier specifying which kind of error should be a part * of acknowledgement * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithErrors(int expectedCount, ErrorQualifier qualifier) { checkArgument(expectedCount >= 0, "0 or more errors matching qualifier must be expected."); return new AcksSpecificErrorCountVerifier(expectedCount, qualifier); } /* * Factory methods for verifying acks with rejections. ******************************************************************************/ /** * Verifies that a command handling did not respond with any {@link Rejection rejections}. * * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithoutRejections() { return new AcksRejectionAbsenceVerifier(); } /** * Verifies that a command or an event was handled responding with some * {@link Rejection rejection}. * * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections() { return new AcksRejectionPresenceVerifier(); } /** * Verifies that a command or an event was handled responding with a {@link Rejection rejection} * of the provided type. * * @param type rejection type in a form of message class * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(Class<? extends Message> type) { RejectionClass rejectionClass = RejectionClass.of(type); return ackedWithRejections(rejectionClass); } /** * Verifies that a command or an event was handled responding with a {@link Rejection rejection} * of the provided type. * * @param type rejection type in a form of {@link RejectionClass RejectionClass} * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(RejectionClass type) { return new AcksRejectionOfTypePresenceVerifier(type); } /** * Verifies that a command or an event was handled responding with rejection matching the * provided predicate. * * @param type a type of a domain rejection specified by a message class * @param predicate a predicate filtering the domain rejections * @param <T> a domain rejection type * @return a new {@link AcknowledgementsVerifier} instance */ public static <T extends Message> AcknowledgementsVerifier ackedWithRejections(Class<T> type, RejectionPredicate<T> predicate) { return new AcksSpecificRejectionPresenceVerifier<>(type, predicate); } /** * Verifies that a command or an event was handled responding with a rejection specified * amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(int expectedCount) { checkArgument(expectedCount >= 0, "0 or more rejections must be expected."); return new AcksRejectionCountVerifier(expectedCount); } /** * Verifies that a command or an event was handled responding with a {@link Rejection rejection} * of a provided type specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type rejection type in a form of message class * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(int expectedCount, Class<? extends Message> type) { checkArgument(expectedCount >= 0, "0 or more rejections of rejections of message class type must be expected."); RejectionClass rejectionClass = RejectionClass.of(type); return ackedWithRejections(expectedCount, rejectionClass); } /** * Verifies that a command or an event was handled responding with a {@link Rejection rejection} * of a provided type specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type rejection type in a form of {@link RejectionClass RejectionClass} * @return a new {@link AcknowledgementsVerifier} instance */ public static AcknowledgementsVerifier ackedWithRejections(int expectedCount, RejectionClass type) { checkArgument(expectedCount >= 0, "0 or more rejections of rejecetions of class must be expected."); return new AcksRejectionOfTypeCountVerifier(type, expectedCount); } /** * Verifies that a command or an event was handled responding with a provided domain rejection * specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type a type of a domain rejection specified by a message class * @param predicate a predicate filtering domain rejections * @param <T> a domain rejection type * @return a new {@link AcknowledgementsVerifier} instance */ public static <T extends Message> AcknowledgementsVerifier ackedWithRejections(int expectedCount, Class<T> type, RejectionPredicate<T> predicate) { checkArgument(expectedCount >= 0, "0 or more specified rejections must be expected."); return new AcksSpecificRejectionCountVerifier<>(expectedCount, type, predicate); } /* * Verifier combination shortcuts. ******************************************************************************/ /** * Combines current verifier with a provided verifier, making them execute sequentially. * * @param otherVerifier a verifier executed after the current verifier * @return a verifier that executes both current and provided assertions */ public AcknowledgementsVerifier and(AcknowledgementsVerifier otherVerifier) { return AcksVerifierCombination.of(this, otherVerifier); } /** * Creates a new verifier adding a check to not contain any {@link Error errors}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withoutErrors() { AcknowledgementsVerifier noErrors = ackedWithoutErrors(); return this.and(noErrors); } /** * Creates a new verifier adding a check to contain at least one {@link Error error}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withErrors() { AcknowledgementsVerifier withError = ackedWithErrors(); return this.and(withError); } /** * Creates a new verifier adding a check to contain specified amount of {@link Error errors}. * * @param expectedCount an amount of errors that are expected to be observed in Bounded Context * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withErrors(int expectedCount) { AcknowledgementsVerifier withError = ackedWithErrors(expectedCount); return this.and(withError); } /** * Creates a new verifier adding a check to contain an {@link Error error} that * matches the qualifier. * * @param qualifier an error qualifier specifying which kind of error should be a part * of acknowledgement * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withErrors(ErrorQualifier qualifier) { AcknowledgementsVerifier withError = ackedWithErrors(qualifier); return this.and(withError); } /** * Creates a new verifier adding a check to contain an {@link Error error} that * matches the qualifier. * * @param expectedCount an amount of errors that are expected to match the qualifier * @param qualifier an error qualifier specifying which kind of error should be a part * of acknowledgement * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withErrors(int expectedCount, ErrorQualifier qualifier) { AcknowledgementsVerifier withError = ackedWithErrors(expectedCount, qualifier); return this.and(withError); } /** * Creates a new verifier adding a check to not contain any {@link Error errors} or * {@link Rejection rejections}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withoutErrorsOrRejections() { AcknowledgementsVerifier noRejections = ackedWithoutRejections(); AcknowledgementsVerifier noErrors = ackedWithoutErrors(); return this.and(noErrors.and(noRejections)); } /** * Creates a new verifier adding a check to not contain any {@link Rejection rejections}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withoutRejections() { AcknowledgementsVerifier noRejections = ackedWithoutRejections(); return this.and(noRejections); } /** * Creates a new verifier adding a check to contain some {@link Rejection rejection}. * * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections() { AcknowledgementsVerifier someRejection = ackedWithRejections(); return this.and(someRejection); } /** * Creates a new verifier adding a check to contain a {@link Rejection rejection} of a * type specified by {@code class}. * * @param type a type of a domain rejection specified by message class * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections(Class<? extends Message> type) { AcknowledgementsVerifier rejectedType = ackedWithRejections(type); return this.and(rejectedType); } /** * Creates a new verifier adding a check to contain a {@link Rejection rejection} of a * type specified by a {@link RejectionClass rejection class}. * * @param type a type of a domain rejection specified by a {@link RejectionClass} * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections(RejectionClass type) { AcknowledgementsVerifier rejectedType = ackedWithRejections(type); return this.and(rejectedType); } /** * Creates a new verifier adding a check to contain a {@link Rejection rejection} of a * type specified by a {@link RejectionClass rejection class} specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type rejection type in a form of message class * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections(int expectedCount, Class<? extends Message> type) { AcknowledgementsVerifier rejectedType = ackedWithRejections(expectedCount, type); return this.and(rejectedType); } /** * Creates a new verifier adding a check to contain a {@link Rejection rejection} of a * type specified by a {@link RejectionClass rejection class} specified amount of times. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type rejection type in a form of {@link RejectionClass RejectionClass} * @return a new {@link AcknowledgementsVerifier} instance */ public AcknowledgementsVerifier withRejections(int expectedCount, RejectionClass type) { AcknowledgementsVerifier rejectedType = ackedWithRejections(expectedCount, type); return this.and(rejectedType); } /** * Creates a new verifier adding a check to contain a provided domain rejection. * * @param type a type of a domain rejection specified by a {@link RejectionClass} * @param predicate a predicate filtering domain rejections * @param <T> a domain rejection type * @return a new {@link AcknowledgementsVerifier} instance */ public <T extends Message> AcknowledgementsVerifier withRejections(Class<T> type, RejectionPredicate<T> predicate) { AcknowledgementsVerifier oneRejection = ackedWithRejections(type, predicate); return this.and(oneRejection); } /** * Creates a new verifier adding a check to contain a provided domain rejection. * * @param expectedCount an amount of rejection that are expected in Bounded Context * @param type a type of a domain rejection specified by a {@link RejectionClass} * @param predicate a predicate filtering domain rejections * @param <T> a domain rejection type * @return a new {@link AcknowledgementsVerifier} instance */ public <T extends Message> AcknowledgementsVerifier withRejections(int expectedCount, Class<T> type, RejectionPredicate<T> predicate) { AcknowledgementsVerifier oneRejection = ackedWithRejections(expectedCount, type, predicate); return this.and(oneRejection); } }
Add details to AcknowledgementVerifier docs.
testutil-server/src/main/java/io/spine/server/integration/AcknowledgementsVerifier.java
Add details to AcknowledgementVerifier docs.
<ide><path>estutil-server/src/main/java/io/spine/server/integration/AcknowledgementsVerifier.java <ide> import static com.google.common.base.Preconditions.checkArgument; <ide> <ide> /** <del> * An abstract verifier of acknowledgements. <add> * An abstract verifier of Bounded Context acknowledgements. Its intended to be executed by the <add> * {@link BlackBoxBoundedContext Black Box Bounded Context}. Its implementations throw assertion <add> * errors if the acknowledgements observed in the Bounded Context do not meet the verifier criteria. <ide> * <ide> * <p>Contains static factory methods for creating acknowledgement verifiers, checking that <ide> * commands were acknowledged, responded with rejections, and errors.
Java
apache-2.0
8c29da631f720c42b1676721178e417499962ef9
0
pfirmstone/JGDMS,cdegroot/river,pfirmstone/JGDMS,pfirmstone/JGDMS,pfirmstone/river-internet,pfirmstone/river-internet,pfirmstone/JGDMS,pfirmstone/river-internet,cdegroot/river
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.jini.jeri.internal.runtime; import com.sun.jini.jeri.internal.runtime.ImplRefManager.ImplRef; import com.sun.jini.jeri.internal.runtime.ObjectTable.NoSuchObject; import java.io.IOException; import java.io.OutputStream; import java.rmi.Remote; import java.rmi.server.ExportException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import net.jini.export.ServerContext; import net.jini.id.Uuid; import net.jini.jeri.InboundRequest; import net.jini.jeri.InvocationDispatcher; import net.jini.security.SecurityContext; /** * A Target represents a remote object, exported by BasicJeriExporter. * * Based on original ObjectTable.Target, modified to support forced interrupted * unexport. * * @since 2.2.0 * @author Peter Firmstone */ final class Target { private static final Logger logger = Logger.getLogger("net.jini.jeri.BasicJeriExporter"); private volatile ImplRef implRef; private final Uuid id; private final DgcRequestDispatcher[] requestDispatchers; private final boolean allowDGC; private final boolean keepAlive; private final SecurityContext securityContext; private final ClassLoader ccl; private final Lock lock = new ReentrantLock(); private volatile InvocationDispatcher invocationDispatcher; private volatile boolean exported = false; private volatile boolean unexported = false; private volatile boolean success = false; private volatile boolean interrupted = false; private final Set<Uuid> referencedSet; private final Map<Uuid, SequenceEntry> sequenceTable; private final JvmLifeSupport keepAliveCount; private volatile boolean decrementedKeepAlive = false; private final ObjectTable objTable; private final Collection<Thread> calls = new ArrayList<Thread>(); /** * Construction must be directly followed by three calls. * * procRequestDispatchers() * setImplRef(ImplRef implRef) * export() * * @param id * @param requestDispatchers * @param allowDGC * @param keepAlive * @param table * @param sc * @param contextCl * @param counter * @throws java.rmi.server.ExportException */ Target(Uuid id, DgcRequestDispatcher[] requestDispatchers, boolean allowDGC, boolean keepAlive, ObjectTable table, SecurityContext sc, ClassLoader contextCl, JvmLifeSupport counter) throws ExportException { super(); this.objTable = table; this.id = id; this.requestDispatchers = requestDispatchers; this.allowDGC = allowDGC; this.keepAlive = keepAlive; this.keepAliveCount = counter; securityContext = sc; ccl = contextCl; if (allowDGC) { referencedSet = new HashSet<Uuid>(3); sequenceTable = new HashMap<Uuid, SequenceEntry>(3); } else { referencedSet = null; sequenceTable = null; } } /** * Must be synchronized externally by the object table. * Synchronization cannot be performed by a class lock, there may * be more than one object table. * * Unsynchronized method. */ void procRequestDispatchers() throws ExportException{ if (exported) throw new ExportException("Target already exported"); int i = 0; try { for (i = 0; i < requestDispatchers.length; i++) { requestDispatchers[i].put(this); } success = true; } finally { if (!success) { for (int j = 0; j < i; j++) { requestDispatchers[i].remove(this, false); } } } } /** * Set the ImplRef. * * Unsynchronized method, with volatile internal visibility, set * after construction, prior to setExport. * * @param implRef */ void setImplRef(ImplRef implRef) throws ExportException{ if (exported) throw new ExportException("Target already exported"); this.implRef = implRef; } void setInvocationDispatcher(InvocationDispatcher id) { assert id != null; lock.lock(); try { assert invocationDispatcher == null; invocationDispatcher = id; } finally { lock.unlock(); } } /** * This method is called after construction, processing RequestDispatchers, * creating and setting an ImplRef. * * It should not be called if the object has been unexported. * * Unsynchronized method. */ void setExported() throws ExportException{ if (exported) throw new ExportException("Target already exported"); if (unexported == true) throw new ExportException("Target cannot be re-exported"); if (implRef == null) throw new ExportException("ImplRef cannot be null"); if (success == false) throw new ExportException("RequestDispatchers unsuccessful"); exported = true; if (keepAlive){ keepAliveCount.incrementKeepAliveCount(); } } private void decrementKeepAliveCount(){ if (keepAlive){ if (decrementedKeepAlive) return; // Ensure only once per target. decrementedKeepAlive = true; keepAliveCount.decrementKeepAliveCount(); } } /** * To quote the Exporter interface: * * If the remote object is unexported as a result of this method, * then the implementation may (and should, if possible) prevent * remote calls in progress from being able to communicate their * results successfully. * * To comply with the above, dispatch call interruption has been added. * * @param force - if true forcibly unexported * @return true - if unexport successful */ boolean unexport(boolean force) { if (!exported) return true; lock.lock(); try { if (!force && !calls.isEmpty()) { return false; } unexported = true; exported = false; if ( force && !calls.isEmpty()){ interrupted = true; Iterator<Thread> i = calls.iterator(); while (i.hasNext()){ i.next().interrupt(); i.remove(); } } if (calls.isEmpty()) { decrementKeepAliveCount(); } if (allowDGC) { if (!referencedSet.isEmpty()) { for (Iterator i = referencedSet.iterator(); i.hasNext();) { Uuid clientID = (Uuid) i.next(); objTable.unregisterTarget(this, clientID); } referencedSet.clear(); } sequenceTable.clear(); } } finally { lock.unlock(); } implRef.release(this); for (int i = 0; i < requestDispatchers.length; i++) { requestDispatchers[i].remove(this, false); } return true; } void collect() { if (!exported) return; lock.lock(); try { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "garbage collection of object with id {0}", id); } unexported = true; exported = false; if (calls.isEmpty()) { decrementKeepAliveCount(); } if (allowDGC) { assert referencedSet.isEmpty(); sequenceTable.clear(); } } finally { lock.unlock(); } for (int i = 0; i < requestDispatchers.length; i++) { requestDispatchers[i].remove(this, true); } } Uuid getObjectIdentifier() { return id; } // used by ImplRef for invoking Unreferenced.unreferenced boolean getEnableDGC() { return allowDGC; } SecurityContext getSecurityContext() { return securityContext; } ClassLoader getContextClassLoader() { return ccl; } void referenced(Uuid clientID, long sequenceNum) { if (!allowDGC) return; if (!exported) return; lock.lock(); try { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, clientID={1}, sequenceNum={2}", new Object[]{this, clientID, new Long(sequenceNum)}); } SequenceEntry entry = (SequenceEntry) sequenceTable.get(clientID); if (entry == null) { entry = new SequenceEntry(sequenceNum); sequenceTable.put(clientID, entry); } else if (!entry.update(sequenceNum, false)) { /* entry will be updated if sequenceNum is greater * return if entry was not updated. */ return; } if (!referencedSet.contains(clientID)) { if (referencedSet.isEmpty()) { Remote impl = implRef.getImpl(); if (impl == null) { return; } implRef.pin(this); } referencedSet.add(clientID); objTable.registerTarget(this, clientID); } } finally { lock.unlock(); } } void unreferenced(Uuid clientID, long sequenceNum, boolean strong) { if (!allowDGC) return; if (!exported) return; lock.lock(); try { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, clientID={1}, sequenceNum={2}, strong={3}", new Object[]{this, clientID, new Long(sequenceNum), Boolean.valueOf(strong)}); } SequenceEntry entry = sequenceTable.get(clientID); if (entry == null) { if (strong) { entry = new SequenceEntry(sequenceNum, strong); sequenceTable.put(clientID, entry); } } else if (!entry.update(sequenceNum, strong)) { return; } else if (!entry.keep()) { sequenceTable.remove(clientID); } objTable.unregisterTarget(this, clientID); if (referencedSet.remove(clientID) && referencedSet.isEmpty()) { implRef.unpin(this); } } finally { lock.unlock(); } } void leaseExpired(Uuid clientID) { assert allowDGC; if (!exported) return; lock.lock(); try { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, clientID={1}", new Object[]{this, clientID}); } SequenceEntry entry = sequenceTable.get(clientID); if (entry != null && !entry.keep()) { /* * REMIND: We could be removing the sequence number * for a more recent lease, thus allowing a "late * clean call" to be inappropriately processed? * (See 4848840 Comments.) See River-142 * * FIXED see ObjectTable */ sequenceTable.remove(clientID); } if (referencedSet.remove(clientID) && referencedSet.isEmpty()) { implRef.unpin(this); } } finally { lock.unlock(); } } private void interrupted(Thread currentThread) throws InterruptedException { if (currentThread.interrupted()) { // clears the interrupt status. throw new InterruptedException("Target interrupted during dispatch, unexported: " + unexported); } } void dispatch(InboundRequest request) throws IOException, NoSuchObject { if (!exported){ // optimisation to avoid locking. if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, not exported", this); } throw new NoSuchObject(); } Thread current = Thread.currentThread(); boolean exitNormally = true; boolean callerAdded = false; try { InvocationDispatcher id = null; lock.lockInterruptibly(); try { callerAdded = calls.add(current); if (!exported || invocationDispatcher == null) { // check again now we've got the lock. if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, not exported", this); } throw new NoSuchObject(); } id = invocationDispatcher; } finally { lock.unlock(); } Remote impl = implRef.getImpl(); if (impl == null) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, garbage collected", this); } throw new NoSuchObject(); } interrupted(current); dispatch(request, id, impl, current); interrupted(current); } catch (InterruptedException ex) { exitNormally = false; request.abort(); if (!interrupted){ // Not interrupted by unexport, reset interrupted status. current.interrupt(); }// else interrupt is swallowed. if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, interrupted" , this); } }finally { // Either exit normally with clean up, or clean up if caller was added and unexport didn't interrupt. if ( exitNormally || (callerAdded && !interrupted)) { lock.lock(); try { calls.remove(current); if (!exported && calls.isEmpty()) { // In case Target was collected while call in progress. decrementKeepAliveCount(); } }finally { lock.unlock(); } } // else exit without cleanup. } } private void dispatch(final InboundRequest request, final InvocationDispatcher id, final Remote impl, Thread t) throws IOException, NoSuchObject { ClassLoader savedCcl = t.getContextClassLoader(); try { if (ccl != savedCcl) { t.setContextClassLoader(ccl); } AccessController.doPrivileged(securityContext.wrap(new PrivilegedExceptionAction() { public Object run() throws IOException, InterruptedException { dispatch(request, id, impl); return null; } }), securityContext.getAccessControlContext()); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if ( ex instanceof IOException ) throw (IOException) ex; if ( ex instanceof InterruptedException ) { Thread.currentThread().interrupt(); } } finally { if (ccl != savedCcl || savedCcl != t.getContextClassLoader()) { t.setContextClassLoader(savedCcl); } } } private void dispatch(final InboundRequest request, final InvocationDispatcher id, final Remote impl) throws IOException, InterruptedException { request.checkPermissions(); interrupted(Thread.currentThread()); OutputStream out = request.getResponseOutputStream(); out.write(Jeri.OBJECT_HERE); final Collection context = new ArrayList(5); request.populateContext(context); ServerContext.doWithServerContext(new Runnable() { public void run() { id.dispatch(impl, request, context); } }, Collections.unmodifiableCollection(context)); } public String toString() { // for logging return "Target@" + Integer.toHexString(hashCode()) + "[" + id + "]"; } }
src/com/sun/jini/jeri/internal/runtime/Target.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.jini.jeri.internal.runtime; import com.sun.jini.jeri.internal.runtime.ImplRefManager.ImplRef; import com.sun.jini.jeri.internal.runtime.ObjectTable.NoSuchObject; import java.io.IOException; import java.io.OutputStream; import java.rmi.Remote; import java.rmi.server.ExportException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import net.jini.export.ServerContext; import net.jini.id.Uuid; import net.jini.jeri.InboundRequest; import net.jini.jeri.InvocationDispatcher; import net.jini.security.SecurityContext; /** * A Target represents a remote object, exported by BasicJeriExporter. * * Based on original ObjectTable.Target, modified to support forced interrupted * unexport. * * @since 2.2.0 * @author Peter Firmstone */ final class Target { private static final Logger logger = Logger.getLogger("net.jini.jeri.BasicJeriExporter"); private volatile ImplRef implRef; private final Uuid id; private final DgcRequestDispatcher[] requestDispatchers; private final boolean allowDGC; private final boolean keepAlive; private final SecurityContext securityContext; private final ClassLoader ccl; private final Lock lock = new ReentrantLock(); private volatile InvocationDispatcher invocationDispatcher; private volatile boolean exported = false; private volatile boolean unexported = false; private volatile boolean success = false; private volatile boolean interrupted = false; private final Set<Uuid> referencedSet; private final Map<Uuid, SequenceEntry> sequenceTable; private final JvmLifeSupport keepAliveCount; private volatile boolean decrementedKeepAlive = false; private final ObjectTable objTable; private final Collection<Thread> calls = new ArrayList<Thread>(); /** * Construction must be directly followed by three calls. * * procRequestDispatchers() * setImplRef(ImplRef implRef) * export() * * @param id * @param requestDispatchers * @param allowDGC * @param keepAlive * @param table * @param sc * @param contextCl * @param counter * @throws java.rmi.server.ExportException */ Target(Uuid id, DgcRequestDispatcher[] requestDispatchers, boolean allowDGC, boolean keepAlive, ObjectTable table, SecurityContext sc, ClassLoader contextCl, JvmLifeSupport counter) throws ExportException { super(); this.objTable = table; this.id = id; this.requestDispatchers = requestDispatchers; this.allowDGC = allowDGC; this.keepAlive = keepAlive; this.keepAliveCount = counter; securityContext = sc; ccl = contextCl; if (allowDGC) { referencedSet = new HashSet<Uuid>(3); sequenceTable = new HashMap<Uuid, SequenceEntry>(3); } else { referencedSet = null; sequenceTable = null; } } /** * Must be synchronized externally by the object table. * Synchronization cannot be performed by a class lock, there may * be more than one object table. * * Unsynchronized method. */ void procRequestDispatchers() throws ExportException{ if (exported) throw new ExportException("Target already exported"); int i = 0; try { for (i = 0; i < requestDispatchers.length; i++) { requestDispatchers[i].put(this); } success = true; } finally { if (!success) { for (int j = 0; j < i; j++) { requestDispatchers[i].remove(this, false); } } } } /** * Set the ImplRef. * * Unsynchronized method, with volatile internal visibility, set * after construction, prior to setExport. * * @param implRef */ void setImplRef(ImplRef implRef) throws ExportException{ if (exported) throw new ExportException("Target already exported"); this.implRef = implRef; } void setInvocationDispatcher(InvocationDispatcher id) { assert id != null; lock.lock(); try { assert invocationDispatcher == null; invocationDispatcher = id; } finally { lock.unlock(); } } /** * This method is called after construction, processing RequestDispatchers, * creating and setting an ImplRef. * * It should not be called if the object has been unexported. * * Unsynchronized method. */ void setExported() throws ExportException{ if (exported) throw new ExportException("Target already exported"); if (unexported == true) throw new ExportException("Target cannot be re-exported"); if (implRef == null) throw new ExportException("ImplRef cannot be null"); if (success == false) throw new ExportException("RequestDispatchers unsuccessful"); exported = true; if (keepAlive){ keepAliveCount.incrementKeepAliveCount(); } } private void decrementKeepAliveCount(){ if (keepAlive){ if (decrementedKeepAlive) return; // Ensure only once per target. decrementedKeepAlive = true; keepAliveCount.decrementKeepAliveCount(); } } /** * To quote the Exporter interface: * * If the remote object is unexported as a result of this method, * then the implementation may (and should, if possible) prevent * remote calls in progress from being able to communicate their * results successfully. * * To comply with the above, dispatch call interruption has been added. * * @param force - if true forcibly unexported * @return true - if unexport successful */ boolean unexport(boolean force) { if (!exported) return true; lock.lock(); try { if (!force && !calls.isEmpty()) { return false; } unexported = true; exported = false; if ( force && !calls.isEmpty()){ interrupted = true; Iterator<Thread> i = calls.iterator(); while (i.hasNext()){ i.next().interrupt(); i.remove(); } } if (calls.isEmpty()) { decrementKeepAliveCount(); } if (allowDGC) { if (!referencedSet.isEmpty()) { for (Iterator i = referencedSet.iterator(); i.hasNext();) { Uuid clientID = (Uuid) i.next(); objTable.unregisterTarget(this, clientID); } referencedSet.clear(); } sequenceTable.clear(); } } finally { lock.unlock(); } implRef.release(this); for (int i = 0; i < requestDispatchers.length; i++) { requestDispatchers[i].remove(this, false); } return true; } void collect() { if (!exported) return; lock.lock(); try { if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "garbage collection of object with id {0}", id); } unexported = true; exported = false; if (calls.isEmpty()) { decrementKeepAliveCount(); } if (allowDGC) { assert referencedSet.isEmpty(); sequenceTable.clear(); } } finally { lock.unlock(); } for (int i = 0; i < requestDispatchers.length; i++) { requestDispatchers[i].remove(this, true); } } Uuid getObjectIdentifier() { return id; } // used by ImplRef for invoking Unreferenced.unreferenced boolean getEnableDGC() { return allowDGC; } SecurityContext getSecurityContext() { return securityContext; } ClassLoader getContextClassLoader() { return ccl; } void referenced(Uuid clientID, long sequenceNum) { if (!allowDGC) return; if (!exported) return; lock.lock(); try { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, clientID={1}, sequenceNum={2}", new Object[]{this, clientID, new Long(sequenceNum)}); } SequenceEntry entry = (SequenceEntry) sequenceTable.get(clientID); if (entry == null) { entry = new SequenceEntry(sequenceNum); sequenceTable.put(clientID, entry); } else if (!entry.update(sequenceNum, false)) { /* entry will be updated if sequenceNum is greater * return if entry was not updated. */ return; } if (!referencedSet.contains(clientID)) { if (referencedSet.isEmpty()) { Remote impl = implRef.getImpl(); if (impl == null) { return; } implRef.pin(this); } referencedSet.add(clientID); objTable.registerTarget(this, clientID); } } finally { lock.unlock(); } } void unreferenced(Uuid clientID, long sequenceNum, boolean strong) { if (!allowDGC) return; if (!exported) return; lock.lock(); try { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, clientID={1}, sequenceNum={2}, strong={3}", new Object[]{this, clientID, new Long(sequenceNum), Boolean.valueOf(strong)}); } SequenceEntry entry = sequenceTable.get(clientID); if (entry == null) { if (strong) { entry = new SequenceEntry(sequenceNum, strong); sequenceTable.put(clientID, entry); } } else if (!entry.update(sequenceNum, strong)) { return; } else if (!entry.keep()) { sequenceTable.remove(clientID); } objTable.unregisterTarget(this, clientID); if (referencedSet.remove(clientID) && referencedSet.isEmpty()) { implRef.unpin(this); } } finally { lock.unlock(); } } void leaseExpired(Uuid clientID) { assert allowDGC; if (!exported) return; lock.lock(); try { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, clientID={1}", new Object[]{this, clientID}); } SequenceEntry entry = sequenceTable.get(clientID); if (entry != null && !entry.keep()) { /* * REMIND: We could be removing the sequence number * for a more recent lease, thus allowing a "late * clean call" to be inappropriately processed? * (See 4848840 Comments.) See River-142 * * FIXED see ObjectTable */ sequenceTable.remove(clientID); } if (referencedSet.remove(clientID) && referencedSet.isEmpty()) { implRef.unpin(this); } } finally { lock.unlock(); } } private void interrupted(Thread currentThread) throws InterruptedException { if (currentThread.interrupted()) { // clears the interrupt status. throw new InterruptedException("Target interrupted during dispatch, unexported: " + unexported); } } void dispatch(InboundRequest request) throws IOException, NoSuchObject { if (!exported){ // optimisation to avoid locking. if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, not exported", this); } throw new NoSuchObject(); } Thread current = Thread.currentThread(); boolean exitNormally = true; boolean callerAdded = false; try { InvocationDispatcher id = null; lock.lockInterruptibly(); try { callerAdded = calls.add(current); if (!exported || invocationDispatcher == null) { // check again now we've got the lock. if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, not exported", this); } throw new NoSuchObject(); } id = invocationDispatcher; } finally { lock.unlock(); } Remote impl = implRef.getImpl(); if (impl == null) { if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, garbage collected", this); } throw new NoSuchObject(); } interrupted(current); dispatch(request, id, impl, current); interrupted(current); } catch (InterruptedException ex) { exitNormally = false; request.abort(); if (!interrupted){ // Not interrupted by unexport, reset interrupted status. current.interrupt(); }// else interrupt is swallowed. if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "this={0}, interrupted" , this); } }finally { // Either exit normally with clean up, or clean up if caller was added and unexport didn't interrupt. if ( exitNormally || (callerAdded && !interrupted)) { lock.lock(); try { calls.remove(current); if (!exported && calls.isEmpty()) { // In case Target was collected while call in progress. decrementKeepAliveCount(); } }finally { lock.unlock(); } } // else exit without cleanup. } } private void dispatch(final InboundRequest request, final InvocationDispatcher id, final Remote impl, Thread t) throws IOException, NoSuchObject { ClassLoader savedCcl = t.getContextClassLoader(); try { if (ccl != savedCcl) { t.setContextClassLoader(ccl); } AccessController.doPrivileged(securityContext.wrap(new PrivilegedExceptionAction() { public Object run() throws IOException, InterruptedException { dispatch(request, id, impl); return null; } }), securityContext.getAccessControlContext()); } catch (PrivilegedActionException e) { throw (IOException) e.getException(); } finally { if (ccl != savedCcl || savedCcl != t.getContextClassLoader()) { t.setContextClassLoader(savedCcl); } } } private void dispatch(final InboundRequest request, final InvocationDispatcher id, final Remote impl) throws IOException, InterruptedException { request.checkPermissions(); interrupted(Thread.currentThread()); OutputStream out = request.getResponseOutputStream(); out.write(Jeri.OBJECT_HERE); final Collection context = new ArrayList(5); request.populateContext(context); ServerContext.doWithServerContext(new Runnable() { public void run() { id.dispatch(impl, request, context); } }, Collections.unmodifiableCollection(context)); } public String toString() { // for logging return "Target@" + Integer.toHexString(hashCode()) + "[" + id + "]"; } }
Fix exception cast and reset interrupt status git-svn-id: c7bbe51404944d9b279db17c7a6e06b416cefbc7@1222914 13f79535-47bb-0310-9956-ffa450edef68
src/com/sun/jini/jeri/internal/runtime/Target.java
Fix exception cast and reset interrupt status
<ide><path>rc/com/sun/jini/jeri/internal/runtime/Target.java <ide> } <ide> }), securityContext.getAccessControlContext()); <ide> } catch (PrivilegedActionException e) { <del> throw (IOException) e.getException(); <add> Exception ex = e.getException(); <add> if ( ex instanceof IOException ) throw (IOException) ex; <add> if ( ex instanceof InterruptedException ) { <add> Thread.currentThread().interrupt(); <add> } <ide> } finally { <ide> if (ccl != savedCcl || savedCcl != t.getContextClassLoader()) { <ide> t.setContextClassLoader(savedCcl);
Java
agpl-3.0
c70197576cf4d3b2e25e3a628dde8732cbcc7434
0
ktunaxa/rms,ktunaxa/rms,ktunaxa/rms,ktunaxa/rms
/* * This is part of the Ktunaxa referral system. * * Copyright 2011 Ktunaxa Nation Council, http://www.ktunaxa.org/, Canada. */ package org.ktunaxa.referral.client.gui; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.VisibilityMode; import com.smartgwt.client.widgets.layout.SectionStack; import com.smartgwt.client.widgets.layout.SectionStackSection; import com.smartgwt.client.widgets.layout.VLayout; import org.geomajas.gwt.client.command.AbstractCommandCallback; import org.geomajas.gwt.client.command.GwtCommand; import org.geomajas.gwt.client.command.GwtCommandDispatcher; import org.geomajas.gwt.client.map.feature.Feature; import org.geomajas.gwt.client.map.layer.VectorLayer; import org.ktunaxa.bpm.KtunaxaBpmConstant; import org.ktunaxa.referral.client.security.UserContext; import org.ktunaxa.referral.client.widget.AbstractCollapsibleListBlock; import org.ktunaxa.referral.server.command.dto.GetTasksRequest; import org.ktunaxa.referral.server.command.dto.GetTasksResponse; import org.ktunaxa.referral.server.dto.TaskDto; import java.util.ArrayList; import java.util.List; /** * Panel to display unassigned tasks. * * @author Joachim Van der Auwera */ public class UnassignedTasksPanel extends VLayout { // Candidate group titles, positions need to match {@link #CANDIDATE_CHECKS} private static final String[] CANDIDATE_TITLES = { "Aquatic evaluator", "Archaeology evaluator", "Community manager", "Cultural evaluator", "Ecology evaluator", "Referral manager", "Treaty evaluator" }; // Candidate group string to test, positions need to match {@link #CANDIDATE_TITLES} private static final String[][] CANDIDATE_CHECKS = { {KtunaxaBpmConstant.ROLE_AQUATIC}, {KtunaxaBpmConstant.ROLE_ARCHAEOLOGY}, {KtunaxaBpmConstant.ROLE_COMMUNITY_AKISQNUK, KtunaxaBpmConstant.ROLE_COMMUNITY_LOWER_KOOTENAY, KtunaxaBpmConstant.ROLE_COMMUNITY_ST_MARYS, KtunaxaBpmConstant.ROLE_COMMUNITY_TOBACCO_PLAINS}, {KtunaxaBpmConstant.ROLE_CULTURAL}, {KtunaxaBpmConstant.ROLE_ECOLOGY}, {KtunaxaBpmConstant.ROLE_REFERRAL_MANAGER}, {KtunaxaBpmConstant.ROLE_TREATY} }; // index of the referralManager role in the candidate lists private static final int MANAGER = 6; private SectionStackSection[] sections = new SectionStackSection[CANDIDATE_CHECKS.length]; private TaskListView[] views = new TaskListView[CANDIDATE_CHECKS.length]; private List<AbstractCollapsibleListBlock<TaskDto>>[] lists = new List[CANDIDATE_CHECKS.length]; private SectionStack groups; public UnassignedTasksPanel() { super(); setWidth100(); } public void init(VectorLayer referralLayer, Feature referral) { // nothing to do for now } @Override public void show() { super.show(); if (null != groups) { removeMember(groups); } groups = new SectionStack(); groups.setSize("100%", "100%"); groups.setOverflow(Overflow.AUTO); groups.setVisibilityMode(VisibilityMode.MULTIPLE); groups.setPadding(LayoutConstant.MARGIN_SMALL); addMember(groups); UserContext user = UserContext.getInstance(); for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { if (user.hasBpmRole(CANDIDATE_CHECKS[i])) { sections[i] = new SectionStackSection(CANDIDATE_TITLES[i]); sections[i].setTitle(CANDIDATE_TITLES[i]); sections[i].setExpanded(false); views[i] = new TaskListView(); lists[i] = new ArrayList<AbstractCollapsibleListBlock<TaskDto>>(); } } GetTasksRequest request = new GetTasksRequest(); request.setIncludeUnassignedTasks(true); GwtCommand command = new GwtCommand(GetTasksRequest.COMMAND); command.setCommandRequest(request); GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<GetTasksResponse>() { public void execute(GetTasksResponse response) { UserContext user = UserContext.getInstance(); for (TaskDto task : response.getTasks()) { TaskBlock block = new TaskBlock(task); String candidates = task.getCandidates().toString(); boolean added = false; for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { for (String role : CANDIDATE_CHECKS[i]) { if (candidates.contains(role)) { if (user.hasBpmRole(role)) { lists[i].add(block); } added = true; } } } if (!added) { if (user.isReferralManager()) { lists[MANAGER].add(block); } } } int sectionToExpand = 0; int sectionsToExpandCount = 0; for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { if (user.hasBpmRole(CANDIDATE_CHECKS[i])) { int count = lists[i].size(); if (count > 0) { sections[i].setTitle(CANDIDATE_TITLES[i] + " (<span style=\"font-weight:bold;\">" + count + "</span>)"); sectionToExpand = i; sectionsToExpandCount++; } views[i].populate(lists[i]); sections[i].addItem(views[i]); groups.addSection(sections[i]); } } if (1 == sectionsToExpandCount) { sections[sectionToExpand].setExpanded(true); } } }); } }
map/src/main/java/org/ktunaxa/referral/client/gui/UnassignedTasksPanel.java
/* * This is part of the Ktunaxa referral system. * * Copyright 2011 Ktunaxa Nation Council, http://www.ktunaxa.org/, Canada. */ package org.ktunaxa.referral.client.gui; import com.smartgwt.client.types.Overflow; import com.smartgwt.client.types.VisibilityMode; import com.smartgwt.client.widgets.layout.SectionStack; import com.smartgwt.client.widgets.layout.SectionStackSection; import com.smartgwt.client.widgets.layout.VLayout; import org.geomajas.gwt.client.command.AbstractCommandCallback; import org.geomajas.gwt.client.command.GwtCommand; import org.geomajas.gwt.client.command.GwtCommandDispatcher; import org.geomajas.gwt.client.map.feature.Feature; import org.geomajas.gwt.client.map.layer.VectorLayer; import org.ktunaxa.bpm.KtunaxaBpmConstant; import org.ktunaxa.referral.client.security.UserContext; import org.ktunaxa.referral.client.widget.AbstractCollapsibleListBlock; import org.ktunaxa.referral.server.command.dto.GetTasksRequest; import org.ktunaxa.referral.server.command.dto.GetTasksResponse; import org.ktunaxa.referral.server.dto.TaskDto; import java.util.ArrayList; import java.util.List; /** * Panel to display unassigned tasks. * * @author Joachim Van der Auwera */ public class UnassignedTasksPanel extends VLayout { // Candidate group titles, positions need to match {@link #CANDIDATE_CHECKS} private static final String[] CANDIDATE_TITLES = { "Aquatic evaluator", "Archaeology evaluator", "Community manager", "Cultural evaluator", "Ecology evaluator", "Referral manager", "Treaty evaluator" }; // Candidate group string to test, positions need to match {@link #CANDIDATE_TITLES} private static final String[][] CANDIDATE_CHECKS = { {KtunaxaBpmConstant.ROLE_AQUATIC}, {KtunaxaBpmConstant.ROLE_ARCHAEOLOGY}, {KtunaxaBpmConstant.ROLE_COMMUNITY_AKISQNUK, KtunaxaBpmConstant.ROLE_COMMUNITY_LOWER_KOOTENAY, KtunaxaBpmConstant.ROLE_COMMUNITY_ST_MARYS, KtunaxaBpmConstant.ROLE_COMMUNITY_TOBACCO_PLAINS}, {KtunaxaBpmConstant.ROLE_CULTURAL}, {KtunaxaBpmConstant.ROLE_ECOLOGY}, {KtunaxaBpmConstant.ROLE_REFERRAL_MANAGER}, {KtunaxaBpmConstant.ROLE_TREATY} }; // index of the referralManager role in the candidate lists private static final int MANAGER = 6; private SectionStackSection[] sections = new SectionStackSection[CANDIDATE_CHECKS.length]; private TaskListView[] views = new TaskListView[CANDIDATE_CHECKS.length]; private List<AbstractCollapsibleListBlock<TaskDto>>[] lists = new List[CANDIDATE_CHECKS.length]; private SectionStack groups; public UnassignedTasksPanel() { super(); setWidth100(); } public void init(VectorLayer referralLayer, Feature referral) { // nothing to do for now } // @Override // public void hide() { // super.hide(); // groups.destroy(); // for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { // views[i].destroy(); // sections[i] = null; // lists[i] = null; // } // } @Override public void show() { super.show(); if (null != groups) { removeMember(groups); } groups = new SectionStack(); groups.setSize("100%", "100%"); groups.setOverflow(Overflow.AUTO); groups.setVisibilityMode(VisibilityMode.MULTIPLE); groups.setPadding(LayoutConstant.MARGIN_SMALL); addMember(groups); // for (SectionStackSection section : groups.getSections()) { // groups.removeSection(section.getID()); // } UserContext user = UserContext.getInstance(); for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { if (user.hasBpmRole(CANDIDATE_CHECKS[i])) { sections[i] = new SectionStackSection(CANDIDATE_TITLES[i]); sections[i].setTitle(CANDIDATE_TITLES[i]); sections[i].setExpanded(false); views[i] = new TaskListView(); lists[i] = new ArrayList<AbstractCollapsibleListBlock<TaskDto>>(); } } GetTasksRequest request = new GetTasksRequest(); request.setIncludeUnassignedTasks(true); GwtCommand command = new GwtCommand(GetTasksRequest.COMMAND); command.setCommandRequest(request); GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<GetTasksResponse>() { public void execute(GetTasksResponse response) { UserContext user = UserContext.getInstance(); // for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { // lists[i].clear(); // clear again to avoid double AJAX calls causing duplicates // } for (TaskDto task : response.getTasks()) { TaskBlock block = new TaskBlock(task); String candidates = task.getCandidates().toString(); boolean added = false; for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { for (String role : CANDIDATE_CHECKS[i]) { if (candidates.contains(role)) { if (user.hasBpmRole(role)) { lists[i].add(block); } added = true; } } } if (!added) { if (user.isReferralManager()) { lists[MANAGER].add(block); } } } int sectionToExpand = 0; int sectionsToExpandCount = 0; for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { if (user.hasBpmRole(CANDIDATE_CHECKS[i])) { int count = lists[i].size(); if (count > 0) { sections[i].setTitle(CANDIDATE_TITLES[i] + " (<span style=\"font-weight:bold;\">" + count + "</span>)"); sectionToExpand = i; sectionsToExpandCount++; } views[i].populate(lists[i]); sections[i].addItem(views[i]); groups.addSection(sections[i]); } } //Section is expanded AFTER it was added to the group. Does this even work? if (1 == sectionsToExpandCount) { sections[sectionToExpand].setExpanded(true); } } }); } }
remove commented code git-svn-id: 1cc9c407a3edc78ef4a46932c73684f07c8b3c91@1567 cebd4ea5-dd72-4036-80b6-269358829854
map/src/main/java/org/ktunaxa/referral/client/gui/UnassignedTasksPanel.java
remove commented code
<ide><path>ap/src/main/java/org/ktunaxa/referral/client/gui/UnassignedTasksPanel.java <ide> // nothing to do for now <ide> } <ide> <del>// @Override <del>// public void hide() { <del>// super.hide(); <del>// groups.destroy(); <del>// for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { <del>// views[i].destroy(); <del>// sections[i] = null; <del>// lists[i] = null; <del>// } <del>// } <del> <ide> @Override <ide> public void show() { <ide> super.show(); <ide> groups.setPadding(LayoutConstant.MARGIN_SMALL); <ide> addMember(groups); <ide> <del>// for (SectionStackSection section : groups.getSections()) { <del>// groups.removeSection(section.getID()); <del>// } <del> <ide> UserContext user = UserContext.getInstance(); <ide> for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { <ide> if (user.hasBpmRole(CANDIDATE_CHECKS[i])) { <ide> GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<GetTasksResponse>() { <ide> public void execute(GetTasksResponse response) { <ide> UserContext user = UserContext.getInstance(); <del>// for (int i = 0 ; i < CANDIDATE_CHECKS.length ; i++) { <del>// lists[i].clear(); // clear again to avoid double AJAX calls causing duplicates <del>// } <ide> for (TaskDto task : response.getTasks()) { <ide> TaskBlock block = new TaskBlock(task); <ide> String candidates = task.getCandidates().toString(); <ide> groups.addSection(sections[i]); <ide> } <ide> } <del> //Section is expanded AFTER it was added to the group. Does this even work? <ide> if (1 == sectionsToExpandCount) { <ide> sections[sectionToExpand].setExpanded(true); <ide> }
JavaScript
agpl-3.0
4f3dd316d5ae1fd5150ebb779945b1ea6f4e351d
0
Openki/Openki,schuel/hmmm,Openki/Openki,schuel/hmmm,Openki/Openki,schuel/hmmm
Template.courseMembers.onCreated(function() { this.increaseBy = 10; this.membersLimit = new ReactiveVar(this.increaseBy); }); Template.courseMembers.helpers({ howManyEnrolled: function() { return this.members.length; }, sortedMembers: function() { var sortedMembers = this.members.sort(function(a, b) { var aRoles = _.without(a.roles, 'participant'); var bRoles = _.without(b.roles, 'participant'); return aRoles.length < bRoles.length; }); var membersLimit = Template.instance().membersLimit.get(); if (membersLimit) { sortedMembers = sortedMembers.slice(0, membersLimit); } return sortedMembers; }, limited: function() { var membersLimit = Template.instance().membersLimit.get(); return membersLimit && this.members.length >= membersLimit; }, increaseBy: function() { return Template.instance().increaseBy; } }); Template.courseMembers.events({ 'click .js-show-all-members': function(e, instance) { var membersLimit = instance.membersLimit; membersLimit.set(membersLimit.get() + instance.increaseBy); } }); Template.courseMember.onCreated(function() { var instance = this; var courseId = this.data.course._id; instance.editableMessage = Editable( true, function(newMessage) { Meteor.call("change_comment", courseId, newMessage, function(err, courseId) { if (err) { showServerError('Unable to change your message', err); } else { addMessage("\u2713 " + mf('_message.saved'), 'success'); } }); }, mf('roles.message.placeholder', 'My interests...') ); instance.autorun(function() { var data = Template.currentData(); instance.editableMessage.setText(data.member.comment); }); }); Template.courseMember.helpers({ showMemberRoles: function() { var memberRoles = this.member.roles; return memberRoles.length != 1 || memberRoles[0] != "participant"; }, roleShort: function() { return 'roles.'+this+'.short'; }, maySubscribe: function() { return maySubscribe(Meteor.userId(), this.course, this.member.user, 'team'); }, rolelistIcon: function(roletype) { if (roletype != "participant") { return _.findWhere(Roles, { type: roletype }).icon; } }, editableMessage: function() { var mayChangeComment = this.member.user === Meteor.userId(); return mayChangeComment && Template.instance().editableMessage; }, mayUnsubscribeFromTeam: function(label) { return label == 'team' && mayUnsubscribe(Meteor.userId(), this.course, this.member.user, 'team'); } }); Template.removeFromTeamDropdown.helpers({ isNotPriviledgedSelf: function() { var notPriviledgedUser = !privileged(Meteor.userId(), 'admin'); return (this.member.user === Meteor.userId() && notPriviledgedUser); } }); Template.courseMember.events({ 'click .js-add-to-team-btn': function(e, template) { Meteor.call("add_role", this.course._id, this.member.user, 'team', false); return false; }, 'click .js-remove-team': function(e, template) { Meteor.call("remove_role", this.course._id, this.member.user, 'team'); return false; } });
client/views/courses/members/course.members.js
Template.courseMembers.onCreated(function() { this.increaseBy = 10; this.membersLimit = new ReactiveVar(this.increaseBy); }); Template.courseMembers.helpers({ howManyEnrolled: function() { return this.members.length; }, sortedMembers: function() { var members = this.members.map(function(member) { member.roles = _.without(member.roles, 'participant'); return member; }); var sortedMembers = members.sort(function(a, b) { return b.roles.length - a.roles.length; }); var membersLimit = Template.instance().membersLimit.get(); if (membersLimit) { sortedMembers = sortedMembers.slice(0, membersLimit); } return sortedMembers; }, limited: function() { var membersLimit = Template.instance().membersLimit.get(); return membersLimit && this.members.length >= membersLimit; }, increaseBy: function() { return Template.instance().increaseBy; } }); Template.courseMembers.events({ 'click .js-show-all-members': function(e, instance) { var membersLimit = instance.membersLimit; membersLimit.set(membersLimit.get() + instance.increaseBy); } }); Template.courseMember.onCreated(function() { var instance = this; var courseId = this.data.course._id; instance.editableMessage = Editable( true, function(newMessage) { Meteor.call("change_comment", courseId, newMessage, function(err, courseId) { if (err) { showServerError('Unable to change your message', err); } else { addMessage("\u2713 " + mf('_message.saved'), 'success'); } }); }, mf('roles.message.placeholder', 'My interests...') ); instance.autorun(function() { var data = Template.currentData(); instance.editableMessage.setText(data.member.comment); }); }); Template.courseMember.helpers({ showMemberRoles: function() { var memberRoles = this.member.roles; return memberRoles.length != 1 || memberRoles[0] != "participant"; }, roleShort: function() { return 'roles.'+this+'.short'; }, maySubscribe: function() { return maySubscribe(Meteor.userId(), this.course, this.member.user, 'team'); }, rolelistIcon: function(roletype) { if (roletype != "participant") { return _.findWhere(Roles, { type: roletype }).icon; } }, editableMessage: function() { var mayChangeComment = this.member.user === Meteor.userId(); return mayChangeComment && Template.instance().editableMessage; }, mayUnsubscribeFromTeam: function(label) { return label == 'team' && mayUnsubscribe(Meteor.userId(), this.course, this.member.user, 'team'); } }); Template.removeFromTeamDropdown.helpers({ isNotPriviledgedSelf: function() { var notPriviledgedUser = !privileged(Meteor.userId(), 'admin'); return (this.member.user === Meteor.userId() && notPriviledgedUser); } }); Template.courseMember.events({ 'click .js-add-to-team-btn': function(e, template) { Meteor.call("add_role", this.course._id, this.member.user, 'team', false); return false; }, 'click .js-remove-team': function(e, template) { Meteor.call("remove_role", this.course._id, this.member.user, 'team'); return false; } });
don't remove the poarticipant role from members fixes #894
client/views/courses/members/course.members.js
don't remove the poarticipant role from members
<ide><path>lient/views/courses/members/course.members.js <ide> }, <ide> <ide> sortedMembers: function() { <del> var members = this.members.map(function(member) { <del> member.roles = _.without(member.roles, 'participant'); <del> return member; <del> }); <add> var sortedMembers = this.members.sort(function(a, b) { <add> var aRoles = _.without(a.roles, 'participant'); <add> var bRoles = _.without(b.roles, 'participant'); <ide> <del> var sortedMembers = members.sort(function(a, b) { <del> return b.roles.length - a.roles.length; <del> }); <add> return aRoles.length < bRoles.length; <add> }); <ide> <ide> var membersLimit = Template.instance().membersLimit.get(); <ide> if (membersLimit) {
Java
unlicense
c141b978a2a05c5536fd939b8f748aec880e2026
0
playasophy/wonderdome,playasophy/wonderdome,playasophy/wonderdome,playasophy/wonderdome
package org.playasophy.wonderdome; import ddf.minim.*; import ddf.minim.analysis.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import processing.core.*; import org.playasophy.wonderdome.input.ButtonEvent; import org.playasophy.wonderdome.input.InputEvent; import org.playasophy.wonderdome.input.InputEventListener; import org.playasophy.wonderdome.input.KonamiCodeListener; import org.playasophy.wonderdome.mode.*; import org.playasophy.wonderdome.sdk.AudioContext; public class Wonderdome { ///// TYPES ///// private enum State { PAUSED, RUNNING } ///// CONSTANTS ///// public static final int NUM_STRIPS = 6; public static final int PIXELS_PER_STRIP = 240; ///// PROPERTIES ///// // Parent applet for graphics interaction. private final PApplet parent; // Display buffer. private final int[][] pixels; // Audio processing components. private final AudioContext audio; // Mode management variables. private List<Mode> modes; private Mode easterEggMode; private boolean easterEggRunning; private int currentModeIndex; private State state; private boolean autoCycle; private long lastUpdate; private long lastEvent; // Event management variables. private List<InputEventListener> listeners; ///// INITIALIZATION ///// public Wonderdome( final PApplet parent, final AudioInput input) { this.parent = parent; parent.registerMethod("pre", this); pixels = new int[NUM_STRIPS][PIXELS_PER_STRIP]; if ( input != null ) { System.out.println("Acquired audio input, initializing FFT and beat detection"); audio = new AudioContext(input); } else { System.out.println("No audio input detected"); audio = null; } modes = Arrays.asList( new ColorCycle(parent), new FlickerMode(parent), //new PulseMode(parent), //new MovementTest(parent), new LanternMode(parent), new SeizureMode(parent), new LeftRightMode(parent), new OpticalAssaultMode(parent) //new ShootingStarMode(parent) ); // Initial Mode [Change for ease of use when testing new modes]. switchToMode(0); easterEggMode = new StrobeMode(parent); easterEggRunning = false; // Initialize event listeners. listeners = new ArrayList<InputEventListener>(); listeners.add(new KonamiCodeListener(this)); setLastEvent(); state = State.RUNNING; autoCycle = true; lastUpdate = System.currentTimeMillis(); } ///// PUBLIC METHODS ///// public void pre() { // If auto-cycling is enabled and no events have occurred in the last // 5 minutes, cycle modes. if ( autoCycle && System.currentTimeMillis() - lastEvent > 5 * 60 * 1000) { cycleModes(); lastEvent = System.currentTimeMillis(); } if ( state == State.RUNNING ) { // Perform audio processing. if ( audio != null ) audio.update(); long dt = System.currentTimeMillis() - lastUpdate; try { getCurrentMode().update(pixels, dt); } catch ( Exception e ) { evictCurrentMode(e); } // If auto-cycling is disabled, indicate it with a single red pixel. if ( !autoCycle ) { parent.colorMode(parent.RGB); pixels[0][PIXELS_PER_STRIP - 1] = parent.color(255, 0, 0); } } lastUpdate = System.currentTimeMillis(); } public int[][] getPixels() { return pixels; } public void handleEvent(InputEvent event) { System.out.println("Handling event '" + event + "'"); setLastEvent(); boolean consumed = false; // First, run through all of the registered event listeners. for ( InputEventListener listener : listeners ) { consumed = listener.handleEvent(event); if ( consumed ) { return; } } // If no registered listener consumed the event, process it here. // FIXME: Move this code into one or more additional event listeners. if ( event instanceof ButtonEvent ) { ButtonEvent be = (ButtonEvent) event; if ( be.getId() == ButtonEvent.Id.SELECT ) { handleSelectButton(be.getType()); consumed = true; } else if ( be.getId() == ButtonEvent.Id.START ) { if ( be.getType() == ButtonEvent.Type.PRESSED ) { toggleAutoCycle(); } consumed = true; } } // If nothing else consumed the event, send it to the current mode. if ( !consumed ) { try { getCurrentMode().handleEvent(event); } catch ( Exception e ) { evictCurrentMode(e); } } } public void toggleAutoCycle() { autoCycle = !autoCycle; } public void togglePause() { System.out.println("togglePause"); if ( state == State.RUNNING ) { pause(); } else { resume(); } } public void pause() { System.out.println("pause"); state = State.PAUSED; } public void resume() { System.out.println("resume"); state = State.RUNNING; } public void runEasterEgg() { System.out.println("Running easter egg!"); easterEggRunning = true; getCurrentMode().onShow(); new Thread() { public void run() { try { Thread.sleep(20 * 1000); } catch ( InterruptedException e ) { // Do nothing. } easterEggRunning = false; System.out.println("Easter egg stopped"); setLastEvent(); } }.start(); } public void setModeList(List<Mode> modes) { // TODO: Implement this. } ///// PRIVATE METHODS ///// private Mode getCurrentMode() { if ( easterEggRunning ) { return easterEggMode; } else { return modes.get(currentModeIndex); } } private void evictCurrentMode(final Throwable cause) { System.err.println( "Mode '" + getCurrentMode().getClass() + "' threw exception '" + cause.getMessage() + "' and is being evicted from the mode cycle." ); cause.printStackTrace(); modes.remove(currentModeIndex); cycleModes(); setLastEvent(); } private void handleSelectButton(final ButtonEvent.Type type) { if ( type == ButtonEvent.Type.PRESSED ) { cycleModes(); } } private void switchToMode(int modeIndex) { if (modeIndex >= 0 && modeIndex < modes.size()) { currentModeIndex = modeIndex; getCurrentMode().onShow(); System.out.println("Now in mode " + currentModeIndex + ": " + modes.get(currentModeIndex).getClass()); } } private void cycleModes() { int newMode = currentModeIndex + 1; if (newMode >= modes.size()) { newMode = 0; } switchToMode(newMode); } private void setLastEvent() { lastEvent = System.currentTimeMillis(); } }
src/org/playasophy/wonderdome/Wonderdome.java
package org.playasophy.wonderdome; import ddf.minim.*; import ddf.minim.analysis.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import processing.core.*; import org.playasophy.wonderdome.input.ButtonEvent; import org.playasophy.wonderdome.input.InputEvent; import org.playasophy.wonderdome.input.InputEventListener; import org.playasophy.wonderdome.input.KonamiCodeListener; import org.playasophy.wonderdome.mode.*; import org.playasophy.wonderdome.sdk.AudioContext; public class Wonderdome { ///// TYPES ///// private enum State { PAUSED, RUNNING } ///// CONSTANTS ///// public static final int NUM_STRIPS = 6; public static final int PIXELS_PER_STRIP = 240; ///// PROPERTIES ///// // Parent applet for graphics interaction. private final PApplet parent; // Display buffer. private final int[][] pixels; // Audio processing components. private final AudioContext audio; // Mode management variables. private List<Mode> modes; private Mode easterEggMode; private boolean easterEggRunning; private int currentModeIndex; private State state; private long lastUpdate; private long lastEvent; // Event management variables. private List<InputEventListener> listeners; ///// INITIALIZATION ///// public Wonderdome( final PApplet parent, final AudioInput input) { this.parent = parent; parent.registerMethod("pre", this); pixels = new int[NUM_STRIPS][PIXELS_PER_STRIP]; if ( input != null ) { System.out.println("Acquired audio input, initializing FFT and beat detection"); audio = new AudioContext(input); } else { System.out.println("No audio input detected"); audio = null; } modes = Arrays.asList( new ColorCycle(parent), new FlickerMode(parent), //new PulseMode(parent), //new MovementTest(parent), new LanternMode(parent), new SeizureMode(parent), new LeftRightMode(parent), new OpticalAssaultMode(parent) //new ShootingStarMode(parent) ); // Initial Mode [Change for ease of use when testing new modes]. switchToMode(0); easterEggMode = new StrobeMode(parent); easterEggRunning = false; // Initialize event listeners. listeners = new ArrayList<InputEventListener>(); listeners.add(new KonamiCodeListener(this)); setLastEvent(); state = State.RUNNING; lastUpdate = System.currentTimeMillis(); } ///// PUBLIC METHODS ///// public void pre() { // If no events have occurred in the last 5 minutes, cycle modes. if ( System.currentTimeMillis() - lastEvent > 5 * 60 * 1000) { cycleModes(); lastEvent = System.currentTimeMillis(); } if ( state == State.RUNNING ) { // Perform audio processing. if ( audio != null ) audio.update(); long dt = System.currentTimeMillis() - lastUpdate; try { getCurrentMode().update(pixels, dt); } catch ( Exception e ) { evictCurrentMode(e); } } lastUpdate = System.currentTimeMillis(); } public int[][] getPixels() { return pixels; } public void handleEvent(InputEvent event) { System.out.println("Handling event '" + event + "'"); setLastEvent(); boolean consumed = false; // First, run through all of the registered event listeners. for ( InputEventListener listener : listeners ) { consumed = listener.handleEvent(event); if ( consumed ) { return; } } // If no registered listener consumed the event, process it here. // FIXME: Move this code into one or more additional event listeners. if ( event instanceof ButtonEvent ) { ButtonEvent be = (ButtonEvent) event; if ( be.getId() == ButtonEvent.Id.SELECT ) { handleSelectButton(be.getType()); consumed = true; } else if ( be.getId() == ButtonEvent.Id.START ) { if ( be.getType() == ButtonEvent.Type.PRESSED ) { togglePause(); } consumed = true; } } // If nothing else consumed the event, send it to the current mode. if ( !consumed ) { try { getCurrentMode().handleEvent(event); } catch ( Exception e ) { evictCurrentMode(e); } } } public void togglePause() { System.out.println("togglePause"); if ( state == State.RUNNING ) { pause(); } else { resume(); } } public void pause() { System.out.println("pause"); state = State.PAUSED; } public void resume() { System.out.println("resume"); state = State.RUNNING; } public void runEasterEgg() { System.out.println("Running easter egg!"); easterEggRunning = true; getCurrentMode().onShow(); new Thread() { public void run() { try { Thread.sleep(20 * 1000); } catch ( InterruptedException e ) { // Do nothing. } easterEggRunning = false; System.out.println("Easter egg stopped"); setLastEvent(); } }.start(); } public void setModeList(List<Mode> modes) { // TODO: Implement this. } ///// PRIVATE METHODS ///// private Mode getCurrentMode() { if ( easterEggRunning ) { return easterEggMode; } else { return modes.get(currentModeIndex); } } private void evictCurrentMode(final Throwable cause) { System.err.println( "Mode '" + getCurrentMode().getClass() + "' threw exception '" + cause.getMessage() + "' and is being evicted from the mode cycle." ); cause.printStackTrace(); modes.remove(currentModeIndex); cycleModes(); setLastEvent(); } private void handleSelectButton(final ButtonEvent.Type type) { if ( type == ButtonEvent.Type.PRESSED ) { cycleModes(); } } private void switchToMode(int modeIndex) { if (modeIndex >= 0 && modeIndex < modes.size()) { currentModeIndex = modeIndex; getCurrentMode().onShow(); System.out.println("Now in mode " + currentModeIndex + ": " + modes.get(currentModeIndex).getClass()); } } private void cycleModes() { int newMode = currentModeIndex + 1; if (newMode >= modes.size()) { newMode = 0; } switchToMode(newMode); } private void setLastEvent() { lastEvent = System.currentTimeMillis(); } }
Start button toggles auto cycling of modes
src/org/playasophy/wonderdome/Wonderdome.java
Start button toggles auto cycling of modes
<ide><path>rc/org/playasophy/wonderdome/Wonderdome.java <ide> private boolean easterEggRunning; <ide> private int currentModeIndex; <ide> private State state; <add> private boolean autoCycle; <ide> private long lastUpdate; <ide> private long lastEvent; <ide> <ide> setLastEvent(); <ide> <ide> state = State.RUNNING; <add> autoCycle = true; <ide> lastUpdate = System.currentTimeMillis(); <ide> <ide> } <ide> <ide> public void pre() { <ide> <del> // If no events have occurred in the last 5 minutes, cycle modes. <del> if ( System.currentTimeMillis() - lastEvent > 5 * 60 * 1000) { <add> // If auto-cycling is enabled and no events have occurred in the last <add> // 5 minutes, cycle modes. <add> if ( autoCycle && System.currentTimeMillis() - lastEvent > 5 * 60 * 1000) { <ide> cycleModes(); <ide> lastEvent = System.currentTimeMillis(); <ide> } <ide> } catch ( Exception e ) { <ide> evictCurrentMode(e); <ide> } <add> <add> // If auto-cycling is disabled, indicate it with a single red pixel. <add> if ( !autoCycle ) { <add> parent.colorMode(parent.RGB); <add> pixels[0][PIXELS_PER_STRIP - 1] = parent.color(255, 0, 0); <add> } <add> <ide> } <ide> <ide> lastUpdate = System.currentTimeMillis(); <ide> consumed = true; <ide> } else if ( be.getId() == ButtonEvent.Id.START ) { <ide> if ( be.getType() == ButtonEvent.Type.PRESSED ) { <del> togglePause(); <add> toggleAutoCycle(); <ide> } <ide> consumed = true; <ide> } <ide> } <ide> } <ide> <add> } <add> <add> <add> public void toggleAutoCycle() { <add> autoCycle = !autoCycle; <ide> } <ide> <ide>
Java
agpl-3.0
ea5c1b6aa7300c3a25a0cefe4338e6ca07bbe3dc
0
MaridProject/marid,MaridProject/marid
/* * MARID, the visual component programming environment. * Copyright (C) 2020 Dzmitry Auchynnikau * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.marid.ide; import org.marid.ide.logging.IdeLogManager; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.regex.Pattern; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; public class AppLauncher { public static void main(String... args) throws Exception { // initialize logging System.setProperty("java.util.logging.manager", IdeLogManager.class.getName()); // create temporary directory var tempDir = Files.createTempDirectory("marid-ide"); addShutdownAction(() -> Files.walkFileTree(tempDir, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.deleteIfExists(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.deleteIfExists(dir); return FileVisitResult.CONTINUE; } })); // detect os final String os; { var osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("mac")) { os = "mac"; } else if (osName.contains("win")) { os = "win"; } else { os = "linux"; } } // copy jars var pattern = Pattern.compile("javafx-\\w++-[\\d.]++-(\\w++).jar"); var parentClassLoader = Thread.currentThread().getContextClassLoader(); var depsListUrl = requireNonNull(parentClassLoader.getResource("deps.list")); var futures = new ArrayList<Future<URL>>(); try (var scanner = new Scanner(depsListUrl.openStream(), UTF_8)) { while (scanner.hasNextLine()) { var jar = scanner.nextLine(); var task = new FutureTask<>(() -> { var matcher = pattern.matcher(jar); if (matcher.matches()) { if (!matcher.group(1).equals(os)) { return null; } } var jarUrl = requireNonNull(parentClassLoader.getResource("deps/" + jar)); var targetFile = tempDir.resolve(jar); try (var is = jarUrl.openStream()) { Files.copy(is, targetFile); } return targetFile.toUri().toURL(); }); var thread = new Thread(task); thread.setDaemon(true); thread.start(); futures.add(task); } } // make custom classpath var urls = new ArrayList<URL>(futures.size()); for (var f : futures) { var url = f.get(); if (url != null) { urls.add(url); } } var javaClassPath = System.getProperty("java.class.path"); var javaClassPathParts = javaClassPath.split(File.pathSeparator); for (var part : javaClassPathParts) { var path = Path.of(part); urls.add(path.toUri().toURL()); } var classLoader = new URLClassLoader(urls.toArray(URL[]::new), ClassLoader.getPlatformClassLoader()); addShutdownAction(() -> { classLoader.close(); return null; }); // launch application var applicationClass = classLoader.loadClass("javafx.application.Application"); var appClass = classLoader.loadClass("org.marid.ide.App"); var launchMethod = applicationClass.getMethod("launch", Class.class, String[].class); launchMethod.invoke(null, appClass, args); } private static void addShutdownAction(Callable<?> code) { Runtime.getRuntime().addShutdownHook(new Thread(new FutureTask<>(code))); } }
marid-ide/src/main/java/org/marid/ide/AppLauncher.java
/* * MARID, the visual component programming environment. * Copyright (C) 2020 Dzmitry Auchynnikau * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.marid.ide; import org.marid.ide.logging.IdeLogManager; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.regex.Pattern; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; public class AppLauncher { public static void main(String... args) throws Exception { // initialize logging System.setProperty("java.util.logging.manager", IdeLogManager.class.getName()); // create temporary directory var tempDir = Files.createTempDirectory("marid-ide"); addShutdownAction(() -> Files.walkFileTree(tempDir, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.deleteIfExists(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.deleteIfExists(dir); return FileVisitResult.CONTINUE; } })); // detect os final String os; { var osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("mac")) { os = "mac"; } else if (osName.contains("win")) { os = "win"; } else { os = "linux"; } } // copy jars var pattern = Pattern.compile("javafx-\\w++-[\\d.]++-(\\w++).jar"); var parentClassLoader = Thread.currentThread().getContextClassLoader(); var depsListUrl = requireNonNull(parentClassLoader.getResource("deps.list")); var futures = new ArrayList<Future<URL>>(); try (var scanner = new Scanner(depsListUrl.openStream(), UTF_8)) { while (scanner.hasNextLine()) { var jar = scanner.nextLine(); var task = new FutureTask<>(() -> { var matcher = pattern.matcher(jar); if (matcher.matches()) { if (!matcher.group(1).equals(os)) { return null; } } var jarUrl = requireNonNull(parentClassLoader.getResource("deps/" + jar)); var targetFile = tempDir.resolve(jar); try (var is = jarUrl.openStream()) { Files.copy(is, targetFile); } return targetFile.toUri().toURL(); }); var thread = new Thread(task); thread.setDaemon(true); thread.start(); futures.add(task); } } // make custom classpath var urls = new ArrayList<URL>(); for (var f : futures) { var url = f.get(); if (url != null) { urls.add(url); } } var javaClassPath = System.getProperty("java.class.path"); var javaClassPathParts = javaClassPath.split(File.pathSeparator); for (var part : javaClassPathParts) { var path = Path.of(part); urls.add(path.toUri().toURL()); } var classLoader = new URLClassLoader(urls.toArray(URL[]::new), ClassLoader.getPlatformClassLoader()); addShutdownAction(() -> { classLoader.close(); return null; }); // launch application var applicationClass = classLoader.loadClass("javafx.application.Application"); var appClass = classLoader.loadClass("org.marid.ide.App"); var launchMethod = applicationClass.getMethod("launch", Class.class, String[].class); launchMethod.invoke(null, appClass, args); } private static void addShutdownAction(Callable<?> code) { Runtime.getRuntime().addShutdownHook(new Thread(new FutureTask<>(code))); } }
Single jar
marid-ide/src/main/java/org/marid/ide/AppLauncher.java
Single jar
<ide><path>arid-ide/src/main/java/org/marid/ide/AppLauncher.java <ide> } <ide> } <ide> // make custom classpath <del> var urls = new ArrayList<URL>(); <add> var urls = new ArrayList<URL>(futures.size()); <ide> for (var f : futures) { <ide> var url = f.get(); <ide> if (url != null) {
JavaScript
mit
c8a68052743aed5cbc905d9e63c34d0c9a3328cc
0
TrustTheVote-Project/horatio-client,TrustTheVote-Project/horatio-client,TrustTheVote-Project/horatio-client
// Browser detection for when you get desparate. A measure of last resort. // http://rog.ie/post/9089341529/html5boilerplatejs // var b = document.documentElement; // b.setAttribute('data-useragent', navigator.userAgent); // b.setAttribute('data-platform', navigator.platform); // sample CSS: html[data-useragent*='Chrome/13.0'] { ... } // remap jQuery to $ (function($){ $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; /* trigger when page is ready */ $(document).ready(function (){ $(function() { $('form').submit(function() { // for testing, output the JSON at the bottom of the page $('#result').text(JSON.stringify($('form').serializeObject())); // use this when there's a server URL to point to // $.post( "[server URL]", JSON.stringify($('form').serializeObject() ); return false; }); }); }); /* optional triggers $(window).load(function() { }); $(window).resize(function() { }); */ })(window.jQuery);
assets/js/functions.js
// Browser detection for when you get desparate. A measure of last resort. // http://rog.ie/post/9089341529/html5boilerplatejs // var b = document.documentElement; // b.setAttribute('data-useragent', navigator.userAgent); // b.setAttribute('data-platform', navigator.platform); // sample CSS: html[data-useragent*='Chrome/13.0'] { ... } // remap jQuery to $ (function($){ $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; /* trigger when page is ready */ $(document).ready(function (){ $(function() { $('form').submit(function() { $('#result').text(JSON.stringify($('form').serializeObject())); return false; }); }); }); /* optional triggers $(window).load(function() { }); $(window).resize(function() { }); */ })(window.jQuery);
send form results via POST, commented out for now
assets/js/functions.js
send form results via POST, commented out for now
<ide><path>ssets/js/functions.js <ide> <ide> $(function() { <ide> $('form').submit(function() { <add> <add> // for testing, output the JSON at the bottom of the page <ide> $('#result').text(JSON.stringify($('form').serializeObject())); <add> <add> // use this when there's a server URL to point to <add> // $.post( "[server URL]", JSON.stringify($('form').serializeObject() ); <add> <ide> return false; <ide> }); <ide> });
Java
mit
6bd45f6dd71d8bcbda6a78ef19e3de82681966ae
0
McJty/RFTools
package mcjty.rftools.blocks.ores; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; public class DimensionalShardItemBlock extends ItemBlock { public DimensionalShardItemBlock(Block block) { super(block); setHasSubtypes(true); } @Override public int getMetadata(int damage) { return damage; } }
src/main/java/mcjty/rftools/blocks/ores/DimensionalShardItemBlock.java
package mcjty.rftools.blocks.ores; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; public class DimensionalShardItemBlock extends ItemBlock { public DimensionalShardItemBlock(Block block) { super(block); } @Override public int getMetadata(int damage) { return damage; } }
Call setHasSubtypes(true) on dimensional shard ore This fixes the nether and end variants of dimensional shard ore dropping as the overworld variant when silk touched.
src/main/java/mcjty/rftools/blocks/ores/DimensionalShardItemBlock.java
Call setHasSubtypes(true) on dimensional shard ore
<ide><path>rc/main/java/mcjty/rftools/blocks/ores/DimensionalShardItemBlock.java <ide> public class DimensionalShardItemBlock extends ItemBlock { <ide> public DimensionalShardItemBlock(Block block) { <ide> super(block); <add> setHasSubtypes(true); <ide> } <ide> <ide> @Override
Java
apache-2.0
32c4e661abb39a9c9745014c6f57758a469b73e6
0
msoute/vertx-deploy-tools,msoute/vertx-deploy-tools,msoute/vertx-deploy-tools
package nl.jpoint.maven.vertx.utils; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.maven.plugin.logging.Log; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; public class AwsOpsWorksUtil { private final static String AWS_OPSWORKS_SERVICE = "opsworks"; private final String targetHost = AWS_OPSWORKS_SERVICE + "." + "us-east-1" + ".amazonaws.com"; private final AwsUtil awsUtil; protected final SimpleDateFormat compressedIso8601DateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"); public AwsOpsWorksUtil(String accessKey, String secretAccessKey) { this.awsUtil = new AwsUtil(accessKey, secretAccessKey); this.compressedIso8601DateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } private String getElasticIp(String stackId, String instanceId) throws AwsException { String date = compressedIso8601DateFormat.format(new Date()); StringBuilder payloadBuilder = new StringBuilder("{\"InstanceId\":\""+instanceId+"\"}"); //StringBuilder payloadBuilder = new StringBuilder("{\"InstanceId\":\""+instanceId+"\",\"StackId\":\""+stackId+"\"}"); Map<String, String> signedHeaders = this.createDefaultSignedHeaders(date, targetHost); HttpPost awsPost = awsUtil.createSignedPost(targetHost, signedHeaders, date, payloadBuilder.toString(), AWS_OPSWORKS_SERVICE, "us-east-1", "DescribeElasticIps"); byte[] result = this.executeRequest(awsPost); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = null; try { parser = factory.createParser(result); JsonNode describeResult = mapper.readValue(parser, JsonNode.class); if (describeResult != null) { JsonNode eips = describeResult.get("ElasticIps"); if (eips != null) { Iterator<JsonNode> it = eips.elements(); while (it.hasNext()) { JsonNode eip = it.next(); if (instanceId.equals(eip.get("InstanceId").textValue())) { return eip.get("Ip").textValue(); } } } } } catch (IOException e) { throw new AwsException(e); } return null; } public List<String> ListStackInstances(final String stackId, final String layerId, boolean usePrivateIp, Log log) throws AwsException { List<String> hosts = new ArrayList<>(); String date = compressedIso8601DateFormat.format(new Date()); Map<String, String> signedHeaders = this.createDefaultSignedHeaders(date, targetHost); HttpPost awsPost = awsUtil.createSignedPost(targetHost, signedHeaders, date, "{\"StackId\":\"" + stackId + "\"}", AWS_OPSWORKS_SERVICE, "us-east-1", "DescribeInstances"); byte[] result = this.executeRequest(awsPost); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); try { JsonParser parser = factory.createParser(result); JsonNode describeResult = mapper.readValue(parser, JsonNode.class); if (describeResult != null) { JsonNode instances = describeResult.get("Instances"); if (instances != null) { Iterator<JsonNode> it = instances.elements(); while (it.hasNext()) { String host = null; JsonNode instance = it.next(); JsonNode layers = instance.get("LayerIds"); if ( layerId != null && layerId.length() > 0 && !containesLayer(layerId, layers)) { continue; } String status = instance.get("Status").textValue(); if (usePrivateIp) { host = instance.get("PrivateIp").textValue(); } else { if (instance.get("InstanceId") != null) { host = getElasticIp(stackId, instance.get("InstanceId").textValue()); } if (host == null && instance.get("PublicDns") != null) { host = instance.get("PublicDns").textValue(); } } if (host != null && status.equals("online")) { hosts.add(host); } else { log.warn("skipping host " + host + " with status " + status); } } } } } catch (IOException e) { throw new AwsException(e); } return hosts; } private boolean containesLayer(String layerId, JsonNode layers) { Iterator<JsonNode> it = layers.elements(); while (it.hasNext()) { JsonNode next = it.next(); if (next.asText().equals(layerId)) { return true; } } return false; } private byte[] executeRequest(final HttpPost awsPost) throws AwsException { try (CloseableHttpClient client = HttpClients.createDefault()) { try (CloseableHttpResponse response = client.execute(awsPost)) { return EntityUtils.toByteArray(response.getEntity()); } } catch (IOException e) { throw new AwsException(e); } } private Map<String, String> createDefaultSignedHeaders(String date, String targetHost) { Map<String, String> signedHeaders = new HashMap<>(); signedHeaders.put("X-Amz-Date", date); signedHeaders.put("Host", targetHost); return signedHeaders; } }
vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/AwsOpsWorksUtil.java
package nl.jpoint.maven.vertx.utils; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.maven.plugin.logging.Log; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; public class AwsOpsWorksUtil { private final static String AWS_OPSWORKS_SERVICE = "opsworks"; private final String targetHost = AWS_OPSWORKS_SERVICE + "." + "us-east-1" + ".amazonaws.com"; private final AwsUtil awsUtil; protected final SimpleDateFormat compressedIso8601DateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"); public AwsOpsWorksUtil(String accessKey, String secretAccessKey) { this.awsUtil = new AwsUtil(accessKey, secretAccessKey); this.compressedIso8601DateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } private String getElasticIp(String stackId, String instanceId) throws AwsException { String date = compressedIso8601DateFormat.format(new Date()); StringBuilder payloadBuilder = new StringBuilder("{\"InstanceId\":\""+instanceId+"\"}"); //StringBuilder payloadBuilder = new StringBuilder("{\"InstanceId\":\""+instanceId+"\",\"StackId\":\""+stackId+"\"}"); Map<String, String> signedHeaders = this.createDefaultSignedHeaders(date, targetHost); HttpPost awsPost = awsUtil.createSignedPost(targetHost, signedHeaders, date, payloadBuilder.toString(), AWS_OPSWORKS_SERVICE, "us-east-1", "DescribeElasticIps"); byte[] result = this.executeRequest(awsPost); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonParser parser = null; try { parser = factory.createParser(result); JsonNode describeResult = mapper.readValue(parser, JsonNode.class); if (describeResult != null) { JsonNode eips = describeResult.get("ElasticIps"); if (eips != null) { Iterator<JsonNode> it = eips.elements(); while (it.hasNext()) { JsonNode eip = it.next(); if (instanceId.equals(eip.get("InstanceId").textValue())) { return eip.get("Ip").textValue(); } } } } } catch (IOException e) { throw new AwsException(e); } return null; } public List<String> ListStackInstances(final String stackId, final String layerId, boolean usePrivateIp, Log log) throws AwsException { List<String> hosts = new ArrayList<>(); String date = compressedIso8601DateFormat.format(new Date()); StringBuilder payloadBuilder = new StringBuilder("{"); payloadBuilder.append("\"StackId\":\""+stackId+"\""); payloadBuilder.append("}"); Map<String, String> signedHeaders = this.createDefaultSignedHeaders(date, targetHost); HttpPost awsPost = awsUtil.createSignedPost(targetHost, signedHeaders, date, payloadBuilder.toString(), AWS_OPSWORKS_SERVICE, "us-east-1", "DescribeInstances"); byte[] result = this.executeRequest(awsPost); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); try { JsonParser parser = factory.createParser(result); JsonNode describeResult = mapper.readValue(parser, JsonNode.class); if (describeResult != null) { //JsonNode layers = describeResult.get("LayerIds"); JsonNode instances = describeResult.get("Instances"); if (instances != null) { Iterator<JsonNode> it = instances.elements(); while (it.hasNext()) { String host = null; JsonNode instance = it.next(); JsonNode layers = instance.get("LayerIds"); if ( layerId != null && layerId.length() > 0 && !containesLayer(layerId, layers)) { continue; } String status = instance.get("Status").textValue(); if (usePrivateIp) { host = instance.get("PrivateIp").textValue(); } else { if (instance.get("InstanceId") != null) { host = getElasticIp(stackId, instance.get("InstanceId").textValue()); } if (host == null && instance.get("PublicDns") != null) { host = instance.get("PublicDns").textValue(); } } if (host != null && status.equals("online")) { hosts.add(host); } else { log.warn("skipping host " + host + " with status " + status); } } } } } catch (IOException e) { throw new AwsException(e); } return hosts; } private boolean containesLayer(String layerId, JsonNode layers) { Iterator<JsonNode> it = layers.elements(); while (it.hasNext()) { JsonNode next = it.next(); if (next.asText().equals(layerId)) { return true; } } return false; } private byte[] executeRequest(final HttpPost awsPost) throws AwsException { try (CloseableHttpClient client = HttpClients.createDefault()) { try (CloseableHttpResponse response = client.execute(awsPost)) { return EntityUtils.toByteArray(response.getEntity()); } } catch (IOException e) { throw new AwsException(e); } } private Map<String, String> createDefaultSignedHeaders(String date, String targetHost) { Map<String, String> signedHeaders = new HashMap<>(); signedHeaders.put("X-Amz-Date", date); signedHeaders.put("Host", targetHost); return signedHeaders; } }
No need for StringBuilder
vertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/AwsOpsWorksUtil.java
No need for StringBuilder
<ide><path>ertx-deploy-maven-plugin/src/main/java/nl/jpoint/maven/vertx/utils/AwsOpsWorksUtil.java <ide> <ide> String date = compressedIso8601DateFormat.format(new Date()); <ide> <del> StringBuilder payloadBuilder = new StringBuilder("{"); <del> payloadBuilder.append("\"StackId\":\""+stackId+"\""); <del> payloadBuilder.append("}"); <del> <ide> Map<String, String> signedHeaders = this.createDefaultSignedHeaders(date, targetHost); <ide> <del> HttpPost awsPost = awsUtil.createSignedPost(targetHost, signedHeaders, date, payloadBuilder.toString(), AWS_OPSWORKS_SERVICE, "us-east-1", "DescribeInstances"); <add> HttpPost awsPost = awsUtil.createSignedPost(targetHost, signedHeaders, date, "{\"StackId\":\"" + stackId + "\"}", AWS_OPSWORKS_SERVICE, "us-east-1", "DescribeInstances"); <ide> <ide> byte[] result = this.executeRequest(awsPost); <ide> <ide> JsonParser parser = factory.createParser(result); <ide> JsonNode describeResult = mapper.readValue(parser, JsonNode.class); <ide> if (describeResult != null) { <del> //JsonNode layers = describeResult.get("LayerIds"); <del> <del> <ide> JsonNode instances = describeResult.get("Instances"); <ide> if (instances != null) { <ide> Iterator<JsonNode> it = instances.elements();
JavaScript
mit
5d265d3947a323d1b765fb6569caf3e9811908b0
0
chung-edison/Tec_Web_Js_2016_B,chung-edison/Tec_Web_Js_2016_B
/** * UsuarioController * * @description :: Server-side logic for managing Usuarios * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { crearUsuario: function (req, res) { if (req.method == 'POST') { var parametros = req.allParams(); if (parametros.nombres && parametros.apellidos) { var usuarioCrear = { nombres: parametros.nombres, apellidos: paramentros.apellidos, correo: parametros.correo } if (parametros.correo == "") { delete usuarioCrear.correo; } Usuario.create(usuarioCrear).exec(function (err, usuarioCreado) { if (err) { return res.view('vistas/Error', { error: { descripcion: "Fallo al crear un usuario.", rawError: "err", url: "/CrearUsuario" } }) } return res.view('vistas/Usuario/crearUsuario'); }) } else { return res.view('vistas/Error', { error: { descripcion: "Llene todos los parámetros: nombres y apellidos.", rawError: "Fallo en envío de parámetros", url: "/CrearUsuario" } }); } } else { return res.view('vistas/Error', { error: { descripcion: "Error en el uso del método HTTP.", rawError: "HTTP inválido", url: "/CrearUsuario" } }); } } };
Mascotas/api/controllers/UsuarioController.js
/** * UsuarioController * * @description :: Server-side logic for managing Usuarios * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ module.exports = { crearUsuario: function (req, res) { if (req.method == 'POST') { } else { return res.view('vistas/Error', { error: { descripcion: "Error en el uso del método HTTP.", rawError: "HTTP inválido", url: "/CrearUsuario" } }); } } };
Crear usuario en la base de datos
Mascotas/api/controllers/UsuarioController.js
Crear usuario en la base de datos
<ide><path>ascotas/api/controllers/UsuarioController.js <ide> crearUsuario: function (req, res) { <ide> <ide> if (req.method == 'POST') { <del> <add> var parametros = req.allParams(); <add> if (parametros.nombres && parametros.apellidos) { <add> var usuarioCrear = { <add> nombres: parametros.nombres, <add> apellidos: paramentros.apellidos, <add> correo: parametros.correo <add> } <add> if (parametros.correo == "") { <add> delete usuarioCrear.correo; <add> } <add> Usuario.create(usuarioCrear).exec(function (err, usuarioCreado) { <add> if (err) { <add> return res.view('vistas/Error', { <add> error: { <add> descripcion: "Fallo al crear un usuario.", <add> rawError: "err", <add> url: "/CrearUsuario" <add> } <add> }) <add> } <add> return res.view('vistas/Usuario/crearUsuario'); <add> }) <add> } else { <add> return res.view('vistas/Error', { <add> error: { <add> descripcion: "Llene todos los parámetros: nombres y apellidos.", <add> rawError: "Fallo en envío de parámetros", <add> url: "/CrearUsuario" <add> } <add> }); <add> } <ide> } else { <ide> return res.view('vistas/Error', { <ide> error: {
Java
apache-2.0
bb15d797b9f25b34db17bd5f889153213bf3512d
0
sdeleuze/reactor-core,sdeleuze/reactor-core,sdeleuze/reactor-core,sdeleuze/reactor-core,reactor/reactor-core
/* * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.core.publisher; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.function.*; import org.reactivestreams.Subscriber; import reactor.core.flow.*; import reactor.core.subscriber.SignalEmitter; import reactor.core.util.*; import reactor.core.flow.Fuseable.*; /** * Generate signals one-by-one via a function callback. * <p> * <p> * The {@code stateSupplier} may return {@code null} but your {@code stateConsumer} should be prepared to * handle it. * * @param <T> the value type emitted * @param <S> the custom state per subscriber */ /** * {@see <a href='https://github.com/reactor/reactive-streams-commons'>https://github.com/reactor/reactive-streams-commons</a>} * @since 2.5 */ final class FluxGenerate<T, S> extends Flux<T> { final Callable<S> stateSupplier; final BiFunction<S, SignalEmitter<T>, S> generator; final Consumer<? super S> stateConsumer; public FluxGenerate(BiFunction<S, SignalEmitter<T>, S> generator) { this(() -> null, generator, s -> { }); } public FluxGenerate(Callable<S> stateSupplier, BiFunction<S, SignalEmitter<T>, S> generator) { this(stateSupplier, generator, s -> { }); } public FluxGenerate(Callable<S> stateSupplier, BiFunction<S, SignalEmitter<T>, S> generator, Consumer<? super S> stateConsumer) { this.stateSupplier = Objects.requireNonNull(stateSupplier, "stateSupplier"); this.generator = Objects.requireNonNull(generator, "generator"); this.stateConsumer = Objects.requireNonNull(stateConsumer, "stateConsumer"); } @Override public void subscribe(Subscriber<? super T> s) { S state; try { state = stateSupplier.call(); } catch (Throwable e) { EmptySubscription.error(s, e); return; } s.onSubscribe(new GenerateSubscription<>(s, state, generator, stateConsumer)); } static final class GenerateSubscription<T, S> implements QueueSubscription<T>, SignalEmitter<T> { final Subscriber<? super T> actual; final BiFunction<S, SignalEmitter<T>, S> generator; final Consumer<? super S> stateConsumer; volatile boolean cancelled; S state; boolean terminate; boolean hasValue; boolean outputFused; T generatedValue; Throwable generatedError; volatile long requested; @Override public long requestedFromDownstream() { return requested; } @Override public boolean isCancelled() { return cancelled; } @SuppressWarnings("rawtypes") static final AtomicLongFieldUpdater<GenerateSubscription> REQUESTED = AtomicLongFieldUpdater.newUpdater(GenerateSubscription.class, "requested"); public GenerateSubscription(Subscriber<? super T> actual, S state, BiFunction<S, SignalEmitter<T>, S> generator, Consumer<? super S> stateConsumer) { this.actual = actual; this.state = state; this.generator = generator; this.stateConsumer = stateConsumer; } @Override public Emission emit(T t) { if (terminate) { return Emission.CANCELLED; } if (hasValue) { fail(new IllegalStateException("More than one call to onNext")); return Emission.FAILED; } if (t == null) { fail(new NullPointerException("The generator produced a null value")); return Emission.FAILED; } hasValue = true; if (outputFused) { generatedValue = t; } else { actual.onNext(t); } return Emission.OK; } @Override public void fail(Throwable e) { if (terminate) { return; } terminate = true; if (outputFused) { generatedError = e; } else { actual.onError(e); } } @Override public void complete() { if (terminate) { return; } terminate = true; if (!outputFused) { actual.onComplete(); } } @Override public void stop() { if (terminate) { return; } terminate = true; } @Override public void request(long n) { if (BackpressureUtils.validate(n)) { if (BackpressureUtils.getAndAddCap(REQUESTED, this, n) == 0) { if (n == Long.MAX_VALUE) { fastPath(); } else { slowPath(n); } } } } void fastPath() { S s = state; final BiFunction<S, SignalEmitter<T>, S> g = generator; for (; ; ) { if (cancelled) { cleanup(s); return; } try { s = g.apply(s, this); } catch (Throwable e) { cleanup(s); actual.onError(e); return; } if (terminate || cancelled) { cleanup(s); return; } if (!hasValue) { cleanup(s); actual.onError(new IllegalStateException("The generator didn't call any of the " + "SignalEmitter method")); return; } hasValue = false; } } void slowPath(long n) { S s = state; long e = 0L; final BiFunction<S, SignalEmitter<T>, S> g = generator; for (; ; ) { while (e != n) { if (cancelled) { cleanup(s); return; } try { s = g.apply(s, this); } catch (Throwable ex) { cleanup(s); actual.onError(ex); return; } if (terminate || cancelled) { cleanup(s); return; } if (!hasValue) { cleanup(s); actual.onError(new IllegalStateException("The generator didn't call any of the " + "SignalEmitter method")); return; } e++; hasValue = false; } n = requested; if (n == e) { state = s; n = REQUESTED.addAndGet(this, -e); if (n == 0L) { return; } } } } @Override public void cancel() { if (!cancelled) { cancelled = true; if (REQUESTED.getAndIncrement(this) == 0) { cleanup(state); } } } void cleanup(S s) { try { state = null; stateConsumer.accept(s); } catch (Throwable e) { Exceptions.onErrorDropped(e); } } @Override public int requestFusion(int requestedMode) { if ((requestedMode & Fuseable.SYNC) != 0 && (requestedMode & Fuseable.THREAD_BARRIER) == 0) { outputFused = true; return Fuseable.SYNC; } return Fuseable.NONE; } @Override public T poll() { if (terminate) { return null; } S s = state; try { s = generator.apply(s, this); } catch (final Throwable ex) { cleanup(s); throw ex; } Throwable e = generatedError; if (e != null) { cleanup(s); generatedError = null; throw Exceptions.bubble(e); } if (!hasValue) { cleanup(s); if (!terminate) { throw new IllegalStateException("The generator didn't call any of the " + "SignalEmitter method"); } return null; } T v = generatedValue; generatedValue = null; hasValue = false; state = s; return v; } @Override public Throwable getError() { return generatedError; } @Override public boolean isEmpty() { return terminate; } @Override public int size() { return isEmpty() ? 0 : -1; } @Override public void clear() { generatedError = null; generatedValue = null; } } }
src/main/java/reactor/core/publisher/FluxGenerate.java
/* * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.core.publisher; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLongFieldUpdater; import java.util.function.*; import org.reactivestreams.Subscriber; import reactor.core.flow.*; import reactor.core.subscriber.SignalEmitter; import reactor.core.util.*; import reactor.core.flow.Fuseable.*; /** * Generate signals one-by-one via a function callback. * <p> * <p> * The {@code stateSupplier} may return {@code null} but your {@code stateConsumer} should be prepared to * handle it. * * @param <T> the value type emitted * @param <S> the custom state per subscriber */ /** * {@see <a href='https://github.com/reactor/reactive-streams-commons'>https://github.com/reactor/reactive-streams-commons</a>} * @since 2.5 */ final class FluxGenerate<T, S> extends Flux<T> { final Callable<S> stateSupplier; final BiFunction<S, SignalEmitter<T>, S> generator; final Consumer<? super S> stateConsumer; public FluxGenerate(BiFunction<S, SignalEmitter<T>, S> generator) { this(() -> null, generator, s -> { }); } public FluxGenerate(Callable<S> stateSupplier, BiFunction<S, SignalEmitter<T>, S> generator) { this(stateSupplier, generator, s -> { }); } public FluxGenerate(Callable<S> stateSupplier, BiFunction<S, SignalEmitter<T>, S> generator, Consumer<? super S> stateConsumer) { this.stateSupplier = Objects.requireNonNull(stateSupplier, "stateSupplier"); this.generator = Objects.requireNonNull(generator, "generator"); this.stateConsumer = Objects.requireNonNull(stateConsumer, "stateConsumer"); } @Override public void subscribe(Subscriber<? super T> s) { S state; try { state = stateSupplier.call(); } catch (Throwable e) { EmptySubscription.error(s, e); return; } s.onSubscribe(new GenerateSubscription<>(s, state, generator, stateConsumer)); } static final class GenerateSubscription<T, S> implements QueueSubscription<T>, SignalEmitter<T> { final Subscriber<? super T> actual; final BiFunction<S, SignalEmitter<T>, S> generator; final Consumer<? super S> stateConsumer; volatile boolean cancelled; S state; boolean terminate; boolean hasValue; boolean outputFused; T generatedValue; Throwable generatedError; volatile long requested; @Override public long requestedFromDownstream() { return requested; } @Override public boolean isCancelled() { return cancelled; } @SuppressWarnings("rawtypes") static final AtomicLongFieldUpdater<GenerateSubscription> REQUESTED = AtomicLongFieldUpdater.newUpdater(GenerateSubscription.class, "requested"); public GenerateSubscription(Subscriber<? super T> actual, S state, BiFunction<S, SignalEmitter<T>, S> generator, Consumer<? super S> stateConsumer) { this.actual = actual; this.state = state; this.generator = generator; this.stateConsumer = stateConsumer; } @Override public Emission emit(T t) { if (terminate) { return Emission.CANCELLED; } if (hasValue) { fail(new IllegalStateException("More than one call to onNext")); return Emission.FAILED; } if (t == null) { fail(new NullPointerException("The generator produced a null value")); return Emission.FAILED; } hasValue = true; if (outputFused) { generatedValue = t; } else { actual.onNext(t); } return Emission.OK; } @Override public void fail(Throwable e) { if (terminate) { return; } terminate = true; if (outputFused) { generatedError = e; } else { actual.onError(e); } } @Override public void complete() { if (terminate) { return; } terminate = true; if (!outputFused) { actual.onComplete(); } } @Override public void stop() { if (terminate) { return; } terminate = true; } @Override public void request(long n) { if (BackpressureUtils.validate(n)) { if (BackpressureUtils.getAndAddCap(REQUESTED, this, n) == 0) { if (n == Long.MAX_VALUE) { fastPath(); } else { slowPath(n); } } } } void fastPath() { S s = state; final BiFunction<S, SignalEmitter<T>, S> g = generator; for (; ; ) { if (cancelled) { cleanup(s); return; } try { s = g.apply(s, this); } catch (Throwable e) { cleanup(s); actual.onError(e); return; } if (terminate || cancelled) { cleanup(s); return; } if (!hasValue) { cleanup(s); actual.onError(new IllegalStateException("The generator didn't call any of the " + "SignalEmitter method")); return; } hasValue = false; } } void slowPath(long n) { S s = state; long e = 0L; final BiFunction<S, SignalEmitter<T>, S> g = generator; for (; ; ) { while (e != n) { if (cancelled) { cleanup(s); return; } try { s = g.apply(s, this); } catch (Throwable ex) { cleanup(s); actual.onError(ex); return; } if (terminate || cancelled) { cleanup(s); return; } if (!hasValue) { cleanup(s); actual.onError(new IllegalStateException("The generator didn't call any of the " + "SignalEmitter method")); return; } e++; hasValue = false; } n = requested; if (n == e) { state = s; n = REQUESTED.addAndGet(this, -e); if (n == 0L) { return; } } } } @Override public void cancel() { if (!cancelled) { cancelled = true; if (REQUESTED.getAndIncrement(this) == 0) { cleanup(state); } } } void cleanup(S s) { try { state = null; stateConsumer.accept(s); } catch (Throwable e) { Exceptions.onErrorDropped(e); } } @Override public int requestFusion(int requestedMode) { if ((requestedMode & Fuseable.SYNC) != 0 && (requestedMode & Fuseable.THREAD_BARRIER) == 0) { outputFused = true; return Fuseable.SYNC; } return Fuseable.NONE; } @Override public T poll() { if (terminate) { return null; } S s = state; try { s = generator.apply(s, this); } catch (final Throwable ex) { cleanup(s); throw ex; } Throwable e = generatedError; if (e != null) { cleanup(s); generatedError = null; Exceptions.bubble(e); return null; } if (!hasValue) { cleanup(s); if (!terminate) { throw new IllegalStateException("The generator didn't call any of the " + "SignalEmitter method"); } return null; } T v = generatedValue; generatedValue = null; hasValue = false; state = s; return v; } @Override public boolean isEmpty() { return terminate; } @Override public int size() { return isEmpty() ? 0 : -1; } @Override public void clear() { generatedError = null; generatedValue = null; } } }
Tweak bubble
src/main/java/reactor/core/publisher/FluxGenerate.java
Tweak bubble
<ide><path>rc/main/java/reactor/core/publisher/FluxGenerate.java <ide> cleanup(s); <ide> <ide> generatedError = null; <del> Exceptions.bubble(e); <del> return null; <add> throw Exceptions.bubble(e); <ide> } <ide> <ide> if (!hasValue) { <ide> state = s; <ide> return v; <ide> } <del> <add> <add> @Override <add> public Throwable getError() { <add> return generatedError; <add> } <add> <ide> @Override <ide> public boolean isEmpty() { <ide> return terminate;
Java
apache-2.0
f7ff5d59a452eb7e2ff67be33a2a2bc88e90764a
0
ened/ExoPlayer,google/ExoPlayer,androidx/media,google/ExoPlayer,ened/ExoPlayer,ened/ExoPlayer,amzn/exoplayer-amazon-port,androidx/media,amzn/exoplayer-amazon-port,google/ExoPlayer,androidx/media,amzn/exoplayer-amazon-port
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.mediacodec; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.decoder.DecoderInputBuffer; import com.google.android.exoplayer2.testutil.TestUtil; import com.google.common.primitives.Bytes; import java.nio.ByteBuffer; import org.junit.Test; import org.junit.runner.RunWith; /** Unit tests for {@link BatchBuffer}. */ @RunWith(AndroidJUnit4.class) public final class BatchBufferTest { /** Bigger than {@code BatchBuffer.BATCH_SIZE_BYTES} */ private static final int BUFFER_SIZE_LARGER_THAN_BATCH_SIZE_BYTES = 6 * 1000 * 1024; /** Smaller than {@code BatchBuffer.BATCH_SIZE_BYTES} */ private static final int BUFFER_SIZE_MUCH_SMALLER_THAN_BATCH_SIZE_BYTES = 100; private static final byte[] TEST_ACCESS_UNIT = TestUtil.buildTestData(BUFFER_SIZE_MUCH_SMALLER_THAN_BATCH_SIZE_BYTES); private final BatchBuffer batchBuffer = new BatchBuffer(); @Test public void newBatchBuffer_isEmpty() { assertIsCleared(batchBuffer); } @Test public void clear_empty_isEmpty() { batchBuffer.clear(); assertIsCleared(batchBuffer); } @Test public void clear_afterInsertingAccessUnit_isEmpty() { batchBuffer.commitNextAccessUnit(); batchBuffer.clear(); assertIsCleared(batchBuffer); } @Test public void commitNextAccessUnit_addsAccessUnit() { batchBuffer.commitNextAccessUnit(); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(1); } @Test public void commitNextAccessUnit_untilFull_isFullAndNotEmpty() { fillBatchBuffer(batchBuffer); assertThat(batchBuffer.isEmpty()).isFalse(); assertThat(batchBuffer.isFull()).isTrue(); } @Test public void commitNextAccessUnit_whenFull_throws() { batchBuffer.setMaxAccessUnitCount(1); batchBuffer.commitNextAccessUnit(); assertThrows(IllegalStateException.class, batchBuffer::commitNextAccessUnit); } @Test public void commitNextAccessUnit_whenAccessUnitIsDecodeOnly_isDecodeOnly() { batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_DECODE_ONLY); batchBuffer.commitNextAccessUnit(); assertThat(batchBuffer.isDecodeOnly()).isTrue(); } @Test public void commitNextAccessUnit_whenAccessUnitIsEndOfStream_isEndOfSteam() { batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_END_OF_STREAM); batchBuffer.commitNextAccessUnit(); assertThat(batchBuffer.isEndOfStream()).isTrue(); } @Test public void commitNextAccessUnit_whenAccessUnitIsKeyFrame_isKeyFrame() { batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_KEY_FRAME); batchBuffer.commitNextAccessUnit(); assertThat(batchBuffer.isKeyFrame()).isTrue(); } @Test public void commitNextAccessUnit_withData_dataIsCopiedInTheBatch() { batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); batchBuffer.flip(); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(1); assertThat(batchBuffer.data).isEqualTo(ByteBuffer.wrap(TEST_ACCESS_UNIT)); } @Test public void commitNextAccessUnit_nextAccessUnit_isClear() { batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_KEY_FRAME); batchBuffer.commitNextAccessUnit(); DecoderInputBuffer nextAccessUnit = batchBuffer.getNextAccessUnitBuffer(); assertThat(nextAccessUnit.data).isNotNull(); assertThat(nextAccessUnit.data.position()).isEqualTo(0); assertThat(nextAccessUnit.isKeyFrame()).isFalse(); } @Test public void commitNextAccessUnit_twice_bothAccessUnitAreConcatenated() { // Commit TEST_ACCESS_UNIT batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); // Commit TEST_ACCESS_UNIT again batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); batchBuffer.flip(); byte[] expected = Bytes.concat(TEST_ACCESS_UNIT, TEST_ACCESS_UNIT); assertThat(batchBuffer.data).isEqualTo(ByteBuffer.wrap(expected)); } @Test public void commitNextAccessUnit_whenAccessUnitIsHugeAndBatchBufferNotEmpty_isMarkedPending() { batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); byte[] hugeAccessUnit = TestUtil.buildTestData(BUFFER_SIZE_LARGER_THAN_BATCH_SIZE_BYTES); batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(hugeAccessUnit.length); batchBuffer.getNextAccessUnitBuffer().data.put(hugeAccessUnit); batchBuffer.commitNextAccessUnit(); batchBuffer.batchWasConsumed(); batchBuffer.flip(); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(1); assertThat(batchBuffer.data).isEqualTo(ByteBuffer.wrap(hugeAccessUnit)); } @Test public void batchWasConsumed_whenNotEmpty_isEmpty() { batchBuffer.commitNextAccessUnit(); batchBuffer.batchWasConsumed(); assertIsCleared(batchBuffer); } @Test public void batchWasConsumed_whenFull_isEmpty() { fillBatchBuffer(batchBuffer); batchBuffer.batchWasConsumed(); assertIsCleared(batchBuffer); } @Test public void getMaxAccessUnitCount_whenSetToAPositiveValue_returnsIt() { batchBuffer.setMaxAccessUnitCount(20); assertThat(batchBuffer.getMaxAccessUnitCount()).isEqualTo(20); } @Test public void setMaxAccessUnitCount_whenSetToNegative_throws() { assertThrows(IllegalArgumentException.class, () -> batchBuffer.setMaxAccessUnitCount(-19)); } @Test public void setMaxAccessUnitCount_whenSetToZero_throws() { assertThrows(IllegalArgumentException.class, () -> batchBuffer.setMaxAccessUnitCount(0)); } @Test public void setMaxAccessUnitCount_whenSetToTheNumberOfAccessUnitInTheBatch_isFull() { batchBuffer.commitNextAccessUnit(); batchBuffer.setMaxAccessUnitCount(1); assertThat(batchBuffer.isFull()).isTrue(); } @Test public void batchWasConsumed_whenAccessUnitIsPending_pendingAccessUnitIsInTheBatch() { batchBuffer.commitNextAccessUnit(); batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_DECODE_ONLY); batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); batchBuffer.batchWasConsumed(); batchBuffer.flip(); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(1); assertThat(batchBuffer.isDecodeOnly()).isTrue(); assertThat(batchBuffer.data).isEqualTo(ByteBuffer.wrap(TEST_ACCESS_UNIT)); } private static void fillBatchBuffer(BatchBuffer batchBuffer) { int maxAccessUnit = batchBuffer.getMaxAccessUnitCount(); while (!batchBuffer.isFull()) { assertThat(maxAccessUnit--).isNotEqualTo(0); batchBuffer.commitNextAccessUnit(); } } private static void assertIsCleared(BatchBuffer batchBuffer) { assertThat(batchBuffer.getFirstAccessUnitTimeUs()).isEqualTo(C.TIME_UNSET); assertThat(batchBuffer.getLastAccessUnitTimeUs()).isEqualTo(C.TIME_UNSET); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(0); assertThat(batchBuffer.isEmpty()).isTrue(); assertThat(batchBuffer.isFull()).isFalse(); } }
library/core/src/test/java/com/google/android/exoplayer2/mediacodec/BatchBufferTest.java
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.mediacodec; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.exoplayer2.C; import com.google.android.exoplayer2.decoder.DecoderInputBuffer; import com.google.android.exoplayer2.testutil.TestUtil; import com.google.common.primitives.Bytes; import java.nio.ByteBuffer; import org.junit.Test; import org.junit.runner.RunWith; /** Unit tests for {@link BatchBuffer}. */ @RunWith(AndroidJUnit4.class) public final class BatchBufferTest { /** Bigger than {@code BatchBuffer.BATCH_SIZE_BYTES} */ private static final int BUFFER_SIZE_LARGER_THAN_BATCH_SIZE_BYTES = 100 * 1000 * 1000; /** Smaller than {@code BatchBuffer.BATCH_SIZE_BYTES} */ private static final int BUFFER_SIZE_MUCH_SMALLER_THAN_BATCH_SIZE_BYTES = 100; private static final byte[] TEST_ACCESS_UNIT = TestUtil.buildTestData(BUFFER_SIZE_MUCH_SMALLER_THAN_BATCH_SIZE_BYTES); private final BatchBuffer batchBuffer = new BatchBuffer(); @Test public void newBatchBuffer_isEmpty() { assertIsCleared(batchBuffer); } @Test public void clear_empty_isEmpty() { batchBuffer.clear(); assertIsCleared(batchBuffer); } @Test public void clear_afterInsertingAccessUnit_isEmpty() { batchBuffer.commitNextAccessUnit(); batchBuffer.clear(); assertIsCleared(batchBuffer); } @Test public void commitNextAccessUnit_addsAccessUnit() { batchBuffer.commitNextAccessUnit(); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(1); } @Test public void commitNextAccessUnit_untilFull_isFullAndNotEmpty() { fillBatchBuffer(batchBuffer); assertThat(batchBuffer.isEmpty()).isFalse(); assertThat(batchBuffer.isFull()).isTrue(); } @Test public void commitNextAccessUnit_whenFull_throws() { batchBuffer.setMaxAccessUnitCount(1); batchBuffer.commitNextAccessUnit(); assertThrows(IllegalStateException.class, batchBuffer::commitNextAccessUnit); } @Test public void commitNextAccessUnit_whenAccessUnitIsDecodeOnly_isDecodeOnly() { batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_DECODE_ONLY); batchBuffer.commitNextAccessUnit(); assertThat(batchBuffer.isDecodeOnly()).isTrue(); } @Test public void commitNextAccessUnit_whenAccessUnitIsEndOfStream_isEndOfSteam() { batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_END_OF_STREAM); batchBuffer.commitNextAccessUnit(); assertThat(batchBuffer.isEndOfStream()).isTrue(); } @Test public void commitNextAccessUnit_whenAccessUnitIsKeyFrame_isKeyFrame() { batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_KEY_FRAME); batchBuffer.commitNextAccessUnit(); assertThat(batchBuffer.isKeyFrame()).isTrue(); } @Test public void commitNextAccessUnit_withData_dataIsCopiedInTheBatch() { batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); batchBuffer.flip(); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(1); assertThat(batchBuffer.data).isEqualTo(ByteBuffer.wrap(TEST_ACCESS_UNIT)); } @Test public void commitNextAccessUnit_nextAccessUnit_isClear() { batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_KEY_FRAME); batchBuffer.commitNextAccessUnit(); DecoderInputBuffer nextAccessUnit = batchBuffer.getNextAccessUnitBuffer(); assertThat(nextAccessUnit.data).isNotNull(); assertThat(nextAccessUnit.data.position()).isEqualTo(0); assertThat(nextAccessUnit.isKeyFrame()).isFalse(); } @Test public void commitNextAccessUnit_twice_bothAccessUnitAreConcatenated() { // Commit TEST_ACCESS_UNIT batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); // Commit TEST_ACCESS_UNIT again batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); batchBuffer.flip(); byte[] expected = Bytes.concat(TEST_ACCESS_UNIT, TEST_ACCESS_UNIT); assertThat(batchBuffer.data).isEqualTo(ByteBuffer.wrap(expected)); } @Test public void commitNextAccessUnit_whenAccessUnitIsHugeAndBatchBufferNotEmpty_isMarkedPending() { batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); byte[] hugeAccessUnit = TestUtil.buildTestData(BUFFER_SIZE_LARGER_THAN_BATCH_SIZE_BYTES); batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(hugeAccessUnit.length); batchBuffer.getNextAccessUnitBuffer().data.put(hugeAccessUnit); batchBuffer.commitNextAccessUnit(); batchBuffer.batchWasConsumed(); batchBuffer.flip(); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(1); assertThat(batchBuffer.data).isEqualTo(ByteBuffer.wrap(hugeAccessUnit)); } @Test public void batchWasConsumed_whenNotEmpty_isEmpty() { batchBuffer.commitNextAccessUnit(); batchBuffer.batchWasConsumed(); assertIsCleared(batchBuffer); } @Test public void batchWasConsumed_whenFull_isEmpty() { fillBatchBuffer(batchBuffer); batchBuffer.batchWasConsumed(); assertIsCleared(batchBuffer); } @Test public void getMaxAccessUnitCount_whenSetToAPositiveValue_returnsIt() { batchBuffer.setMaxAccessUnitCount(20); assertThat(batchBuffer.getMaxAccessUnitCount()).isEqualTo(20); } @Test public void setMaxAccessUnitCount_whenSetToNegative_throws() { assertThrows(IllegalArgumentException.class, () -> batchBuffer.setMaxAccessUnitCount(-19)); } @Test public void setMaxAccessUnitCount_whenSetToZero_throws() { assertThrows(IllegalArgumentException.class, () -> batchBuffer.setMaxAccessUnitCount(0)); } @Test public void setMaxAccessUnitCount_whenSetToTheNumberOfAccessUnitInTheBatch_isFull() { batchBuffer.commitNextAccessUnit(); batchBuffer.setMaxAccessUnitCount(1); assertThat(batchBuffer.isFull()).isTrue(); } @Test public void batchWasConsumed_whenAccessUnitIsPending_pendingAccessUnitIsInTheBatch() { batchBuffer.commitNextAccessUnit(); batchBuffer.getNextAccessUnitBuffer().setFlags(C.BUFFER_FLAG_DECODE_ONLY); batchBuffer.getNextAccessUnitBuffer().ensureSpaceForWrite(TEST_ACCESS_UNIT.length); batchBuffer.getNextAccessUnitBuffer().data.put(TEST_ACCESS_UNIT); batchBuffer.commitNextAccessUnit(); batchBuffer.batchWasConsumed(); batchBuffer.flip(); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(1); assertThat(batchBuffer.isDecodeOnly()).isTrue(); assertThat(batchBuffer.data).isEqualTo(ByteBuffer.wrap(TEST_ACCESS_UNIT)); } private static void fillBatchBuffer(BatchBuffer batchBuffer) { int maxAccessUnit = batchBuffer.getMaxAccessUnitCount(); while (!batchBuffer.isFull()) { assertThat(maxAccessUnit--).isNotEqualTo(0); batchBuffer.commitNextAccessUnit(); } } private static void assertIsCleared(BatchBuffer batchBuffer) { assertThat(batchBuffer.getFirstAccessUnitTimeUs()).isEqualTo(C.TIME_UNSET); assertThat(batchBuffer.getLastAccessUnitTimeUs()).isEqualTo(C.TIME_UNSET); assertThat(batchBuffer.getAccessUnitCount()).isEqualTo(0); assertThat(batchBuffer.isEmpty()).isTrue(); assertThat(batchBuffer.isFull()).isFalse(); } }
Make BatchBufferTest allocate less memory Setting to 2x BATCH_SIZE_BYTES PiperOrigin-RevId: 331124129
library/core/src/test/java/com/google/android/exoplayer2/mediacodec/BatchBufferTest.java
Make BatchBufferTest allocate less memory
<ide><path>ibrary/core/src/test/java/com/google/android/exoplayer2/mediacodec/BatchBufferTest.java <ide> public final class BatchBufferTest { <ide> <ide> /** Bigger than {@code BatchBuffer.BATCH_SIZE_BYTES} */ <del> private static final int BUFFER_SIZE_LARGER_THAN_BATCH_SIZE_BYTES = 100 * 1000 * 1000; <add> private static final int BUFFER_SIZE_LARGER_THAN_BATCH_SIZE_BYTES = 6 * 1000 * 1024; <ide> /** Smaller than {@code BatchBuffer.BATCH_SIZE_BYTES} */ <ide> private static final int BUFFER_SIZE_MUCH_SMALLER_THAN_BATCH_SIZE_BYTES = 100; <ide>
Java
mit
2b38de99bc1c793a1a283003ad9735cafe73a131
0
eggheadgames/android-in-app-payments
package com.billing; import java.util.Map; public abstract class BillingServiceListener { /** * Callback will be triggered upon obtaining information about product prices * * @param iapKeyPrices - a map with available products */ public void onPricesUpdated(Map<String, String> iapKeyPrices) { } /** * Callback will be triggered when a product purchased successfully * * @param sku - specificator of owned product */ public void onProductPurchased(String sku) { } /** * Callback will be triggered upon owned products restore * * @param sku - specificator of owned product */ public void onProductRestored(String sku) { } /** * Callback will be triggered upon owned subscription restore * * @param sku - specificator of owned subscription */ public void onSubscriptionRestored(String sku) { } /** * Callback will be triggered when a subscription purchased successfully * * @param sku - specificator of purchased subscription */ public void onSubscriptionPurchased(String sku) { } }
library/src/main/java/com/billing/BillingServiceListener.java
package com.billing; import java.util.Map; public interface BillingServiceListener { /** * Callback will be triggered upon obtaining information about product prices * * @param iapKeyPrices - a map with available products */ void onPricesUpdated(Map<String, String> iapKeyPrices); /** * Callback will be triggered when a product purchased successfully * * @param sku - specificator of owned product */ void onProductPurchased(String sku); /** * Callback will be triggered upon owned products restore * * @param sku - specificator of owned product */ void onProductRestored(String sku); /** * Callback will be triggered upon owned subscription restore * * @param sku - specificator of owned subscription */ void onSubscriptionRestored(String sku); /** * Callback will be triggered when a subscription purchased successfully * * @param sku - specificator of purchased subscription */ void onSubscriptionPurchased(String sku); }
changed library listener to be an abstract class
library/src/main/java/com/billing/BillingServiceListener.java
changed library listener to be an abstract class
<ide><path>ibrary/src/main/java/com/billing/BillingServiceListener.java <ide> <ide> import java.util.Map; <ide> <del>public interface BillingServiceListener { <add>public abstract class BillingServiceListener { <ide> <ide> /** <ide> * Callback will be triggered upon obtaining information about product prices <ide> * <ide> * @param iapKeyPrices - a map with available products <ide> */ <del> void onPricesUpdated(Map<String, String> iapKeyPrices); <add> public void onPricesUpdated(Map<String, String> iapKeyPrices) { <add> } <ide> <ide> /** <ide> * Callback will be triggered when a product purchased successfully <ide> * <ide> * @param sku - specificator of owned product <ide> */ <del> void onProductPurchased(String sku); <add> public void onProductPurchased(String sku) { <add> } <ide> <ide> /** <ide> * Callback will be triggered upon owned products restore <ide> * <ide> * @param sku - specificator of owned product <ide> */ <del> void onProductRestored(String sku); <add> public void onProductRestored(String sku) { <add> } <ide> <ide> /** <ide> * Callback will be triggered upon owned subscription restore <ide> * <ide> * @param sku - specificator of owned subscription <ide> */ <del> void onSubscriptionRestored(String sku); <add> public void onSubscriptionRestored(String sku) { <add> } <ide> <ide> /** <ide> * Callback will be triggered when a subscription purchased successfully <ide> * <ide> * @param sku - specificator of purchased subscription <ide> */ <del> void onSubscriptionPurchased(String sku); <del> <add> public void onSubscriptionPurchased(String sku) { <add> } <ide> }
Java
apache-2.0
56f2736ef9402d6e60e74083373e0ce7b726d527
0
ASU-Capstone/uPortal-Forked,stalele/uPortal,Mines-Albi/esup-uportal,ASU-Capstone/uPortal,groybal/uPortal,EsupPortail/esup-uportal,ASU-Capstone/uPortal-Forked,Jasig/uPortal,doodelicious/uPortal,bjagg/uPortal,GIP-RECIA/esco-portail,vbonamy/esup-uportal,timlevett/uPortal,joansmith/uPortal,Jasig/SSP-Platform,Mines-Albi/esup-uportal,phillips1021/uPortal,phillips1021/uPortal,jameswennmacher/uPortal,ASU-Capstone/uPortal,jonathanmtran/uPortal,jhelmer-unicon/uPortal,timlevett/uPortal,ChristianMurphy/uPortal,vbonamy/esup-uportal,Jasig/SSP-Platform,pspaude/uPortal,vbonamy/esup-uportal,phillips1021/uPortal,Jasig/uPortal-start,MichaelVose2/uPortal,jl1955/uPortal5,jonathanmtran/uPortal,cousquer/uPortal,vbonamy/esup-uportal,apetro/uPortal,cousquer/uPortal,mgillian/uPortal,kole9273/uPortal,EdiaEducationTechnology/uPortal,kole9273/uPortal,groybal/uPortal,apetro/uPortal,jl1955/uPortal5,joansmith/uPortal,jhelmer-unicon/uPortal,Mines-Albi/esup-uportal,pspaude/uPortal,timlevett/uPortal,joansmith/uPortal,chasegawa/uPortal,EdiaEducationTechnology/uPortal,mgillian/uPortal,phillips1021/uPortal,Mines-Albi/esup-uportal,vertein/uPortal,groybal/uPortal,GIP-RECIA/esup-uportal,jhelmer-unicon/uPortal,apetro/uPortal,ASU-Capstone/uPortal-Forked,andrewstuart/uPortal,jameswennmacher/uPortal,GIP-RECIA/esup-uportal,andrewstuart/uPortal,doodelicious/uPortal,GIP-RECIA/esco-portail,jl1955/uPortal5,mgillian/uPortal,stalele/uPortal,apetro/uPortal,drewwills/uPortal,stalele/uPortal,vertein/uPortal,jonathanmtran/uPortal,chasegawa/uPortal,drewwills/uPortal,ASU-Capstone/uPortal-Forked,Jasig/SSP-Platform,jl1955/uPortal5,ASU-Capstone/uPortal,MichaelVose2/uPortal,groybal/uPortal,MichaelVose2/uPortal,drewwills/uPortal,vertein/uPortal,stalele/uPortal,doodelicious/uPortal,EdiaEducationTechnology/uPortal,doodelicious/uPortal,jhelmer-unicon/uPortal,groybal/uPortal,jameswennmacher/uPortal,EsupPortail/esup-uportal,chasegawa/uPortal,joansmith/uPortal,timlevett/uPortal,bjagg/uPortal,bjagg/uPortal,MichaelVose2/uPortal,GIP-RECIA/esup-uportal,vertein/uPortal,andrewstuart/uPortal,Jasig/uPortal,EsupPortail/esup-uportal,pspaude/uPortal,apetro/uPortal,Jasig/SSP-Platform,kole9273/uPortal,joansmith/uPortal,Jasig/uPortal,jhelmer-unicon/uPortal,chasegawa/uPortal,stalele/uPortal,drewwills/uPortal,jameswennmacher/uPortal,Mines-Albi/esup-uportal,kole9273/uPortal,EsupPortail/esup-uportal,GIP-RECIA/esup-uportal,Jasig/uPortal-start,MichaelVose2/uPortal,andrewstuart/uPortal,EdiaEducationTechnology/uPortal,pspaude/uPortal,kole9273/uPortal,Jasig/SSP-Platform,GIP-RECIA/esco-portail,chasegawa/uPortal,phillips1021/uPortal,cousquer/uPortal,ChristianMurphy/uPortal,vbonamy/esup-uportal,ChristianMurphy/uPortal,ASU-Capstone/uPortal,GIP-RECIA/esup-uportal,doodelicious/uPortal,ASU-Capstone/uPortal-Forked,jl1955/uPortal5,jameswennmacher/uPortal,ASU-Capstone/uPortal,andrewstuart/uPortal,EsupPortail/esup-uportal
/** * Copyright 2002 The JA-SIG Collaborative. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.jasig.portal.services.stats; import org.jasig.portal.services.LogService; import org.jasig.portal.layout.UserLayoutChannelDescription; import org.jasig.portal.security.IPerson; import org.jasig.portal.UserProfile; import org.jasig.portal.ChannelDefinition; import org.apache.log4j.Priority; /** * Logs portal statistics to the portal's log. Contains * set and get methods to control the log priority. * @author Ken Weiner, [email protected] * @version $Revision$ */ public class LoggingStatsRecorder extends MessageStatsRecorder { // Unfortunately this is tied to Apache's Log4J. // It would be nice if the LogService was // logger implementation agnostic! private Priority priority; public LoggingStatsRecorder() { this.priority = LogService.INFO; } public LoggingStatsRecorder(Priority priority) { this.priority = priority; } public void setPriority(Priority priority) { this.priority = priority; } public Priority getPriority() { return this.priority; } public void recordLogin(IPerson person) { String msg = super.getMessageForLogin(person); LogService.instance().log(priority, msg); } public void recordLogout(IPerson person) { String msg = super.getMessageForLogout(person); LogService.instance().log(priority, msg); } public void recordSessionCreated(IPerson person) { String msg = super.getMessageForSessionCreated(person); LogService.instance().log(priority, msg); } public void recordSessionDestroyed(IPerson person) { String msg = super.getMessageForSessionDestroyed(person); LogService.instance().log(priority, msg); } public void recordChannelDefinitionPublished(IPerson person, ChannelDefinition channelDef) { String msg = super.getMessageForChannelDefinitionPublished(person, channelDef); LogService.instance().log(priority, msg); } public void recordChannelDefinitionModified(IPerson person, ChannelDefinition channelDef) { String msg = super.getMessageForChannelDefinitionModified(person, channelDef); LogService.instance().log(priority, msg); } public void recordChannelDefinitionRemoved(IPerson person, ChannelDefinition channelDef) { String msg = super.getMessageForChannelDefinitionRemoved(person, channelDef); LogService.instance().log(priority, msg); } public void recordChannelAddedToLayout(IPerson person, UserProfile profile, UserLayoutChannelDescription channelDesc) { String msg = super.getMessageForChannelAddedToLayout(person, profile, channelDesc); LogService.instance().log(priority, msg); } public void recordChannelRemovedFromLayout(IPerson person, UserProfile profile, UserLayoutChannelDescription channelDesc) { String msg = super.getMessageForChannelRemovedFromLayout(person, profile, channelDesc); LogService.instance().log(priority, msg); } }
source/org/jasig/portal/services/stats/LoggingStatsRecorder.java
/** * Copyright 2002 The JA-SIG Collaborative. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the JA-SIG Collaborative * (http://www.jasig.org/)." * * THIS SOFTWARE IS PROVIDED BY THE JA-SIG COLLABORATIVE "AS IS" AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JA-SIG COLLABORATIVE OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.jasig.portal.services.stats; import org.jasig.portal.services.LogService; import org.jasig.portal.security.IPerson; import org.jasig.portal.ChannelDefinition; /** * Logs portal statistics to the portal's log. * @author Ken Weiner, [email protected] * @version $Revision$ */ public class LoggingStatsRecorder extends MessageStatsRecorder { public void recordLogin(IPerson person) { String msg = super.getMessageForLogin(person); LogService.instance().log(LogService.INFO, msg); } public void recordLogout(IPerson person) { String msg = super.getMessageForLogout(person); LogService.instance().log(LogService.INFO, msg); } public void recordSessionCreated(IPerson person) { String msg = super.getMessageForSessionCreated(person); LogService.instance().log(LogService.INFO, msg); } public void recordSessionDestroyed(IPerson person) { String msg = super.getMessageForSessionDestroyed(person); LogService.instance().log(LogService.INFO, msg); } public void recordChannelDefinitionPublished(IPerson person, ChannelDefinition channelDef) { String msg = super.getMessageForChannelDefinitionPublished(person, channelDef); LogService.instance().log(LogService.INFO, msg); } public void recordChannelDefinitionModified(IPerson person, ChannelDefinition channelDef) { String msg = super.getMessageForChannelDefinitionModified(person, channelDef); LogService.instance().log(LogService.INFO, msg); } public void recordChannelDefinitionRemoved(IPerson person, ChannelDefinition channelDef) { String msg = super.getMessageForChannelDefinitionRemoved(person, channelDef); LogService.instance().log(LogService.INFO, msg); } }
Added new methods: recordChannelAddedToLayout() and recordChannelRemovedFromLayout() Added ability to specify logging priority. git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@6707 f5dbab47-78f9-eb45-b975-e544023573eb
source/org/jasig/portal/services/stats/LoggingStatsRecorder.java
Added new methods: recordChannelAddedToLayout() and recordChannelRemovedFromLayout() Added ability to specify logging priority.
<ide><path>ource/org/jasig/portal/services/stats/LoggingStatsRecorder.java <ide> package org.jasig.portal.services.stats; <ide> <ide> import org.jasig.portal.services.LogService; <add>import org.jasig.portal.layout.UserLayoutChannelDescription; <ide> import org.jasig.portal.security.IPerson; <add>import org.jasig.portal.UserProfile; <ide> import org.jasig.portal.ChannelDefinition; <add>import org.apache.log4j.Priority; <ide> <ide> /** <del> * Logs portal statistics to the portal's log. <add> * Logs portal statistics to the portal's log. Contains <add> * set and get methods to control the log priority. <ide> * @author Ken Weiner, [email protected] <ide> * @version $Revision$ <ide> */ <ide> public class LoggingStatsRecorder extends MessageStatsRecorder { <ide> <add> // Unfortunately this is tied to Apache's Log4J. <add> // It would be nice if the LogService was <add> // logger implementation agnostic! <add> private Priority priority; <add> <add> public LoggingStatsRecorder() { <add> this.priority = LogService.INFO; <add> } <add> <add> public LoggingStatsRecorder(Priority priority) { <add> this.priority = priority; <add> } <add> <add> public void setPriority(Priority priority) { <add> this.priority = priority; <add> } <add> <add> public Priority getPriority() { <add> return this.priority; <add> } <add> <ide> public void recordLogin(IPerson person) { <ide> String msg = super.getMessageForLogin(person); <del> LogService.instance().log(LogService.INFO, msg); <add> LogService.instance().log(priority, msg); <ide> } <ide> <ide> public void recordLogout(IPerson person) { <ide> String msg = super.getMessageForLogout(person); <del> LogService.instance().log(LogService.INFO, msg); <add> LogService.instance().log(priority, msg); <ide> } <ide> <ide> public void recordSessionCreated(IPerson person) { <ide> String msg = super.getMessageForSessionCreated(person); <del> LogService.instance().log(LogService.INFO, msg); <add> LogService.instance().log(priority, msg); <ide> } <ide> <ide> public void recordSessionDestroyed(IPerson person) { <ide> String msg = super.getMessageForSessionDestroyed(person); <del> LogService.instance().log(LogService.INFO, msg); <add> LogService.instance().log(priority, msg); <ide> } <ide> <ide> public void recordChannelDefinitionPublished(IPerson person, ChannelDefinition channelDef) { <ide> String msg = super.getMessageForChannelDefinitionPublished(person, channelDef); <del> LogService.instance().log(LogService.INFO, msg); <add> LogService.instance().log(priority, msg); <ide> } <ide> <ide> public void recordChannelDefinitionModified(IPerson person, ChannelDefinition channelDef) { <ide> String msg = super.getMessageForChannelDefinitionModified(person, channelDef); <del> LogService.instance().log(LogService.INFO, msg); <add> LogService.instance().log(priority, msg); <ide> } <ide> <ide> public void recordChannelDefinitionRemoved(IPerson person, ChannelDefinition channelDef) { <ide> String msg = super.getMessageForChannelDefinitionRemoved(person, channelDef); <del> LogService.instance().log(LogService.INFO, msg); <add> LogService.instance().log(priority, msg); <ide> } <add> <add> public void recordChannelAddedToLayout(IPerson person, UserProfile profile, UserLayoutChannelDescription channelDesc) { <add> String msg = super.getMessageForChannelAddedToLayout(person, profile, channelDesc); <add> LogService.instance().log(priority, msg); <add> } <add> <add> public void recordChannelRemovedFromLayout(IPerson person, UserProfile profile, UserLayoutChannelDescription channelDesc) { <add> String msg = super.getMessageForChannelRemovedFromLayout(person, profile, channelDesc); <add> LogService.instance().log(priority, msg); <add> } <ide> } <ide> <ide>
Java
apache-2.0
f0ae88e6b659501ebff93ba5d9db80f683046cbc
0
apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat,apache/tomcat,apache/tomcat,Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4
/* * 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.jasper; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; 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.Stack; import java.util.StringTokenizer; import java.util.Vector; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.compiler.Compiler; import org.apache.jasper.compiler.JspConfig; import org.apache.jasper.compiler.JspRuntimeContext; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.compiler.TagPluginManager; import org.apache.jasper.compiler.TldCache; import org.apache.jasper.runtime.JspFactoryImpl; import org.apache.jasper.servlet.JspCServletContext; import org.apache.jasper.servlet.TldScanner; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.util.FileUtils; import org.xml.sax.SAXException; /** * Shell for the jspc compiler. Handles all options associated with the * command line and creates compilation contexts which it then compiles * according to the specified options. * * This version can process files from a _single_ webapp at once, i.e. * a single docbase can be specified. * * It can be used as an Ant task using: * <pre> * &lt;taskdef classname="org.apache.jasper.JspC" name="jasper" &gt; * &lt;classpath&gt; * &lt;pathelement location="${java.home}/../lib/tools.jar"/&gt; * &lt;fileset dir="${ENV.CATALINA_HOME}/lib"&gt; * &lt;include name="*.jar"/&gt; * &lt;/fileset&gt; * &lt;path refid="myjars"/&gt; * &lt;/classpath&gt; * &lt;/taskdef&gt; * * &lt;jasper verbose="0" * package="my.package" * uriroot="${webapps.dir}/${webapp.name}" * webXmlFragment="${build.dir}/generated_web.xml" * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" /&gt; * </pre> * * @author Danno Ferrin * @author Pierre Delisle * @author Costin Manolache * @author Yoav Shapira */ public class JspC extends Task implements Options { static { // the Validator uses this to access the EL ExpressionFactory JspFactory.setDefaultFactory(new JspFactoryImpl()); } public static final String DEFAULT_IE_CLASS_ID = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"; // Logger private static final Log log = LogFactory.getLog(JspC.class); protected static final String SWITCH_VERBOSE = "-v"; protected static final String SWITCH_HELP = "-help"; protected static final String SWITCH_OUTPUT_DIR = "-d"; protected static final String SWITCH_PACKAGE_NAME = "-p"; protected static final String SWITCH_CACHE = "-cache"; protected static final String SWITCH_CLASS_NAME = "-c"; protected static final String SWITCH_FULL_STOP = "--"; protected static final String SWITCH_COMPILE = "-compile"; protected static final String SWITCH_SOURCE = "-source"; protected static final String SWITCH_TARGET = "-target"; protected static final String SWITCH_URI_BASE = "-uribase"; protected static final String SWITCH_URI_ROOT = "-uriroot"; protected static final String SWITCH_FILE_WEBAPP = "-webapp"; protected static final String SWITCH_WEBAPP_INC = "-webinc"; protected static final String SWITCH_WEBAPP_XML = "-webxml"; protected static final String SWITCH_WEBAPP_XML_ENCODING = "-webxmlencoding"; protected static final String SWITCH_ADD_WEBAPP_XML_MAPPINGS = "-addwebxmlmappings"; protected static final String SWITCH_MAPPED = "-mapped"; protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy"; protected static final String SWITCH_TRIM_SPACES = "-trimSpaces"; protected static final String SWITCH_CLASSPATH = "-classpath"; protected static final String SWITCH_DIE = "-die"; protected static final String SWITCH_POOLING = "-poolingEnabled"; protected static final String SWITCH_ENCODING = "-javaEncoding"; protected static final String SWITCH_SMAP = "-smap"; protected static final String SWITCH_DUMP_SMAP = "-dumpsmap"; protected static final String SWITCH_VALIDATE_TLD = "-validateTld"; protected static final String SWITCH_VALIDATE_XML = "-validateXml"; protected static final String SWITCH_NO_BLOCK_EXTERNAL = "-no-blockExternal"; protected static final String SWITCH_NO_STRICT_QUOTE_ESCAPING = "-no-strictQuoteEscaping"; protected static final String SHOW_SUCCESS ="-s"; protected static final String LIST_ERRORS = "-l"; protected static final int INC_WEBXML = 10; protected static final int ALL_WEBXML = 20; protected static final int DEFAULT_DIE_LEVEL = 1; protected static final int NO_DIE_LEVEL = 0; protected static final Set<String> insertBefore = new HashSet<>(); static { insertBefore.add("</web-app>"); insertBefore.add("<servlet-mapping>"); insertBefore.add("<session-config>"); insertBefore.add("<mime-mapping>"); insertBefore.add("<welcome-file-list>"); insertBefore.add("<error-page>"); insertBefore.add("<taglib>"); insertBefore.add("<resource-env-ref>"); insertBefore.add("<resource-ref>"); insertBefore.add("<security-constraint>"); insertBefore.add("<login-config>"); insertBefore.add("<security-role>"); insertBefore.add("<env-entry>"); insertBefore.add("<ejb-ref>"); insertBefore.add("<ejb-local-ref>"); } protected String classPath = null; protected ClassLoader loader = null; protected boolean trimSpaces = false; protected boolean genStringAsCharArray = false; protected boolean validateTld; protected boolean validateXml; protected boolean blockExternal = true; protected boolean strictQuoteEscaping = true; protected boolean xpoweredBy; protected boolean mappedFile = false; protected boolean poolingEnabled = true; protected File scratchDir; protected String ieClassId = DEFAULT_IE_CLASS_ID; protected String targetPackage; protected String targetClassName; protected String uriBase; protected String uriRoot; protected int dieLevel; protected boolean helpNeeded = false; protected boolean compile = false; protected boolean smapSuppressed = true; protected boolean smapDumped = false; protected boolean caching = true; protected final Map<String, TagLibraryInfo> cache = new HashMap<>(); protected String compiler = null; protected String compilerTargetVM = "1.8"; protected String compilerSourceVM = "1.8"; protected boolean classDebugInfo = true; /** * Throw an exception if there's a compilation error, or swallow it. * Default is true to preserve old behavior. */ protected boolean failOnError = true; /** * The file extensions to be handled as JSP files. * Default list is .jsp and .jspx. */ protected List<String> extensions; /** * The pages. */ protected final List<String> pages = new Vector<>(); /** * Needs better documentation, this data member does. * True by default. */ protected boolean errorOnUseBeanInvalidClassAttribute = true; /** * The java file encoding. Default * is UTF-8. Added per bugzilla 19622. */ protected String javaEncoding = "UTF-8"; // Generation of web.xml fragments protected String webxmlFile; protected int webxmlLevel; protected String webxmlEncoding; protected boolean addWebXmlMappings = false; protected Writer mapout; protected CharArrayWriter servletout; protected CharArrayWriter mappingout; /** * The servlet context. */ protected JspCServletContext context; /** * The runtime context. * Maintain a dummy JspRuntimeContext for compiling tag files. */ protected JspRuntimeContext rctxt; /** * Cache for the TLD locations */ protected TldCache tldCache = null; protected JspConfig jspConfig = null; protected TagPluginManager tagPluginManager = null; protected TldScanner scanner = null; protected boolean verbose = false; protected boolean listErrors = false; protected boolean showSuccess = false; protected int argPos; protected boolean fullstop = false; protected String args[]; public static void main(String arg[]) { if (arg.length == 0) { System.out.println(Localizer.getMessage("jspc.usage")); } else { JspC jspc = new JspC(); try { jspc.setArgs(arg); if (jspc.helpNeeded) { System.out.println(Localizer.getMessage("jspc.usage")); } else { jspc.execute(); } } catch (JasperException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } } catch (BuildException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } } } } /** * Apply command-line arguments. * * @param arg * The arguments */ public void setArgs(String[] arg) throws JasperException { args = arg; String tok; dieLevel = NO_DIE_LEVEL; while ((tok = nextArg()) != null) { if (tok.equals(SWITCH_VERBOSE)) { verbose = true; showSuccess = true; listErrors = true; } else if (tok.equals(SWITCH_OUTPUT_DIR)) { tok = nextArg(); setOutputDir( tok ); } else if (tok.equals(SWITCH_PACKAGE_NAME)) { targetPackage = nextArg(); } else if (tok.equals(SWITCH_COMPILE)) { compile=true; } else if (tok.equals(SWITCH_CLASS_NAME)) { targetClassName = nextArg(); } else if (tok.equals(SWITCH_URI_BASE)) { uriBase=nextArg(); } else if (tok.equals(SWITCH_URI_ROOT)) { setUriroot( nextArg()); } else if (tok.equals(SWITCH_FILE_WEBAPP)) { setUriroot( nextArg()); } else if ( tok.equals( SHOW_SUCCESS ) ) { showSuccess = true; } else if ( tok.equals( LIST_ERRORS ) ) { listErrors = true; } else if (tok.equals(SWITCH_WEBAPP_INC)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = INC_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = ALL_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) { setWebXmlEncoding(nextArg()); } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) { setAddWebXmlMappings(true); } else if (tok.equals(SWITCH_MAPPED)) { mappedFile = true; } else if (tok.equals(SWITCH_XPOWERED_BY)) { xpoweredBy = true; } else if (tok.equals(SWITCH_TRIM_SPACES)) { setTrimSpaces(true); } else if (tok.equals(SWITCH_CACHE)) { tok = nextArg(); if ("false".equals(tok)) { caching = false; } else { caching = true; } } else if (tok.equals(SWITCH_CLASSPATH)) { setClassPath(nextArg()); } else if (tok.startsWith(SWITCH_DIE)) { try { dieLevel = Integer.parseInt( tok.substring(SWITCH_DIE.length())); } catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; } } else if (tok.equals(SWITCH_HELP)) { helpNeeded = true; } else if (tok.equals(SWITCH_POOLING)) { tok = nextArg(); if ("false".equals(tok)) { poolingEnabled = false; } else { poolingEnabled = true; } } else if (tok.equals(SWITCH_ENCODING)) { setJavaEncoding(nextArg()); } else if (tok.equals(SWITCH_SOURCE)) { setCompilerSourceVM(nextArg()); } else if (tok.equals(SWITCH_TARGET)) { setCompilerTargetVM(nextArg()); } else if (tok.equals(SWITCH_SMAP)) { smapSuppressed = false; } else if (tok.equals(SWITCH_DUMP_SMAP)) { smapDumped = true; } else if (tok.equals(SWITCH_VALIDATE_TLD)) { setValidateTld(true); } else if (tok.equals(SWITCH_VALIDATE_XML)) { setValidateXml(true); } else if (tok.equals(SWITCH_NO_BLOCK_EXTERNAL)) { setBlockExternal(false); } else if (tok.equals(SWITCH_NO_STRICT_QUOTE_ESCAPING)) { setStrictQuoteEscaping(false); } else { if (tok.startsWith("-")) { throw new JasperException("Unrecognized option: " + tok + ". Use -help for help."); } if (!fullstop) { argPos--; } // Start treating the rest as JSP Pages break; } } // Add all extra arguments to the list of files while( true ) { String file = nextFile(); if( file==null ) { break; } pages.add( file ); } } /** * In JspC this always returns <code>true</code>. * {@inheritDoc} */ @Override public boolean getKeepGenerated() { // isn't this why we are running jspc? return true; } /** * {@inheritDoc} */ @Override public boolean getTrimSpaces() { return trimSpaces; } /** * Sets the option to trim white spaces between directives or actions. */ public void setTrimSpaces(boolean ts) { this.trimSpaces = ts; } /** * {@inheritDoc} */ @Override public boolean isPoolingEnabled() { return poolingEnabled; } /** * Sets the option to enable the tag handler pooling. */ public void setPoolingEnabled(boolean poolingEnabled) { this.poolingEnabled = poolingEnabled; } /** * {@inheritDoc} */ @Override public boolean isXpoweredBy() { return xpoweredBy; } /** * Sets the option to enable generation of X-Powered-By response header. */ public void setXpoweredBy(boolean xpoweredBy) { this.xpoweredBy = xpoweredBy; } /** * In JspC this always returns <code>true</code>. * {@inheritDoc} */ @Override public boolean getDisplaySourceFragment() { return true; } @Override public int getMaxLoadedJsps() { return -1; } @Override public int getJspIdleTimeout() { return -1; } /** * {@inheritDoc} */ @Override public boolean getErrorOnUseBeanInvalidClassAttribute() { return errorOnUseBeanInvalidClassAttribute; } /** * Sets the option to issue a compilation error if the class attribute * specified in useBean action is invalid. */ public void setErrorOnUseBeanInvalidClassAttribute(boolean b) { errorOnUseBeanInvalidClassAttribute = b; } /** * {@inheritDoc} */ @Override public boolean getMappedFile() { return mappedFile; } public void setMappedFile(boolean b) { mappedFile = b; } /** * Sets the option to include debug information in compiled class. */ public void setClassDebugInfo( boolean b ) { classDebugInfo=b; } /** * {@inheritDoc} */ @Override public boolean getClassDebugInfo() { // compile with debug info return classDebugInfo; } /** * {@inheritDoc} */ @Override public boolean isCaching() { return caching; } /** * Sets the option to enable caching. * * @see Options#isCaching() */ public void setCaching(boolean caching) { this.caching = caching; } /** * {@inheritDoc} */ @Override public Map<String, TagLibraryInfo> getCache() { return cache; } /** * In JspC this always returns <code>0</code>. * {@inheritDoc} */ @Override public int getCheckInterval() { return 0; } /** * In JspC this always returns <code>0</code>. * {@inheritDoc} */ @Override public int getModificationTestInterval() { return 0; } /** * In JspC this always returns <code>false</code>. * {@inheritDoc} */ @Override public boolean getRecompileOnFail() { return false; } /** * In JspC this always returns <code>false</code>. * {@inheritDoc} */ @Override public boolean getDevelopment() { return false; } /** * {@inheritDoc} */ @Override public boolean isSmapSuppressed() { return smapSuppressed; } /** * Sets smapSuppressed flag. */ public void setSmapSuppressed(boolean smapSuppressed) { this.smapSuppressed = smapSuppressed; } /** * {@inheritDoc} */ @Override public boolean isSmapDumped() { return smapDumped; } /** * Sets smapDumped flag. * * @see Options#isSmapDumped() */ public void setSmapDumped(boolean smapDumped) { this.smapDumped = smapDumped; } /** * Determines whether text strings are to be generated as char arrays, * which improves performance in some cases. * * @param genStringAsCharArray true if text strings are to be generated as * char arrays, false otherwise */ public void setGenStringAsCharArray(boolean genStringAsCharArray) { this.genStringAsCharArray = genStringAsCharArray; } /** * {@inheritDoc} */ @Override public boolean genStringAsCharArray() { return genStringAsCharArray; } /** * Sets the class-id value to be sent to Internet Explorer when using * &lt;jsp:plugin&gt; tags. * * @param ieClassId * Class-id value */ public void setIeClassId(String ieClassId) { this.ieClassId = ieClassId; } /** * {@inheritDoc} */ @Override public String getIeClassId() { return ieClassId; } /** * {@inheritDoc} */ @Override public File getScratchDir() { return scratchDir; } /** * {@inheritDoc} */ @Override public String getCompiler() { return compiler; } /** * Sets the option to determine what compiler to use. * * @see Options#getCompiler() */ public void setCompiler(String c) { compiler=c; } /** * {@inheritDoc} */ @Override public String getCompilerClassName() { return null; } /** * {@inheritDoc} */ @Override public String getCompilerTargetVM() { return compilerTargetVM; } /** * Sets the compiler target VM. * * @see Options#getCompilerTargetVM() */ public void setCompilerTargetVM(String vm) { compilerTargetVM = vm; } /** * {@inheritDoc} */ @Override public String getCompilerSourceVM() { return compilerSourceVM; } /** * Sets the compiler source VM. * * @see Options#getCompilerSourceVM() */ public void setCompilerSourceVM(String vm) { compilerSourceVM = vm; } /** * {@inheritDoc} */ @Override public TldCache getTldCache() { return tldCache; } /** * Returns the encoding to use for * java files. The default is UTF-8. * * @return String The encoding */ @Override public String getJavaEncoding() { return javaEncoding; } /** * Sets the encoding to use for * java files. * * @param encodingName The name, e.g. "UTF-8" */ public void setJavaEncoding(String encodingName) { javaEncoding = encodingName; } /** * {@inheritDoc} */ @Override public boolean getFork() { return false; } /** * {@inheritDoc} */ @Override public String getClassPath() { if( classPath != null ) return classPath; return System.getProperty("java.class.path"); } /** * Sets the classpath used while compiling the servlets generated from JSP * files */ public void setClassPath(String s) { classPath=s; } /** * Returns the list of file extensions * that are treated as JSP files. * * @return The list of extensions */ public List<String> getExtensions() { return extensions; } /** * Adds the given file extension to the * list of extensions handled as JSP files. * * @param extension The extension to add, e.g. "myjsp" */ protected void addExtension(final String extension) { if(extension != null) { if(extensions == null) { extensions = new Vector<>(); } extensions.add(extension); } } /** * Base dir for the webapp. Used to generate class names and resolve * includes. */ public void setUriroot( String s ) { if (s == null) { uriRoot = null; return; } try { uriRoot = resolveFile(s).getCanonicalPath(); } catch( Exception ex ) { uriRoot = s; } } /** * Parses comma-separated list of JSP files to be processed. If the argument * is null, nothing is done. * * <p>Each file is interpreted relative to uriroot, unless it is absolute, * in which case it must start with uriroot.</p> * * @param jspFiles Comma-separated list of JSP files to be processed */ public void setJspFiles(final String jspFiles) { if(jspFiles == null) { return; } StringTokenizer tok = new StringTokenizer(jspFiles, ","); while (tok.hasMoreTokens()) { pages.add(tok.nextToken()); } } /** * Sets the compile flag. * * @param b Flag value */ public void setCompile( final boolean b ) { compile = b; } /** * Sets the verbosity level. The actual number doesn't * matter: if it's greater than zero, the verbose flag will * be true. * * @param level Positive means verbose */ public void setVerbose( final int level ) { if (level > 0) { verbose = true; showSuccess = true; listErrors = true; } } public void setValidateTld( boolean b ) { this.validateTld = b; } public boolean isValidateTld() { return validateTld; } public void setValidateXml( boolean b ) { this.validateXml = b; } public boolean isValidateXml() { return validateXml; } public void setBlockExternal( boolean b ) { this.blockExternal = b; } public boolean isBlockExternal() { return blockExternal; } public void setStrictQuoteEscaping( boolean b ) { this.strictQuoteEscaping = b; } @Override public boolean getStrictQuoteEscaping() { return strictQuoteEscaping; } public void setListErrors( boolean b ) { listErrors = b; } public void setOutputDir( String s ) { if( s!= null ) { scratchDir = resolveFile(s).getAbsoluteFile(); } else { scratchDir=null; } } /** * Sets the package name to be used for the generated servlet classes. */ public void setPackage( String p ) { targetPackage=p; } /** * Class name of the generated file ( without package ). * Can only be used if a single file is converted. * XXX Do we need this feature ? */ public void setClassName( String p ) { targetClassName=p; } /** * File where we generate a web.xml fragment with the class definitions. */ public void setWebXmlFragment( String s ) { webxmlFile=resolveFile(s).getAbsolutePath(); webxmlLevel=INC_WEBXML; } /** * File where we generate a complete web.xml with the class definitions. */ public void setWebXml( String s ) { webxmlFile=resolveFile(s).getAbsolutePath(); webxmlLevel=ALL_WEBXML; } /** * Sets the encoding to be used to read and write web.xml files. * * <p> * If not specified, defaults to the platform default encoding. * </p> * * @param encoding * Encoding, e.g. "UTF-8". */ public void setWebXmlEncoding(String encoding) { webxmlEncoding = encoding; } /** * Sets the option to merge generated web.xml fragment into the * WEB-INF/web.xml file of the web application that we were processing. * * @param b * <code>true</code> to merge the fragment into the existing * web.xml file of the processed web application * ({uriroot}/WEB-INF/web.xml), <code>false</code> to keep the * generated web.xml fragment */ public void setAddWebXmlMappings(boolean b) { addWebXmlMappings = b; } /** * Sets the option that throws an exception in case of a compilation error. */ public void setFailOnError(final boolean b) { failOnError = b; } /** * Returns true if an exception will be thrown in case of a compilation * error. */ public boolean getFailOnError() { return failOnError; } /** * {@inheritDoc} */ @Override public JspConfig getJspConfig() { return jspConfig; } /** * {@inheritDoc} */ @Override public TagPluginManager getTagPluginManager() { return tagPluginManager; } /** * Adds servlet declaration and mapping for the JSP page servlet to the * generated web.xml fragment. * * @param file * Context-relative path to the JSP file, e.g. * <code>/index.jsp</code> * @param clctxt * Compilation context of the servlet */ public void generateWebMapping( String file, JspCompilationContext clctxt ) throws IOException { if (log.isDebugEnabled()) { log.debug("Generating web mapping for file " + file + " using compilation context " + clctxt); } String className = clctxt.getServletClassName(); String packageName = clctxt.getServletPackageName(); String thisServletName; if ("".equals(packageName)) { thisServletName = className; } else { thisServletName = packageName + '.' + className; } if (servletout != null) { servletout.write("\n <servlet>\n <servlet-name>"); servletout.write(thisServletName); servletout.write("</servlet-name>\n <servlet-class>"); servletout.write(thisServletName); servletout.write("</servlet-class>\n </servlet>\n"); } if (mappingout != null) { mappingout.write("\n <servlet-mapping>\n <servlet-name>"); mappingout.write(thisServletName); mappingout.write("</servlet-name>\n <url-pattern>"); mappingout.write(file.replace('\\', '/')); mappingout.write("</url-pattern>\n </servlet-mapping>\n"); } } /** * Include the generated web.xml inside the webapp's web.xml. */ protected void mergeIntoWebXml() throws IOException { File webappBase = new File(uriRoot); File webXml = new File(webappBase, "WEB-INF/web.xml"); File webXml2 = new File(webappBase, "WEB-INF/web2.xml"); String insertStartMarker = Localizer.getMessage("jspc.webinc.insertStart"); String insertEndMarker = Localizer.getMessage("jspc.webinc.insertEnd"); try (BufferedReader reader = new BufferedReader(openWebxmlReader(webXml)); BufferedReader fragmentReader = new BufferedReader(openWebxmlReader(new File(webxmlFile))); PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2))) { // Insert the <servlet> and <servlet-mapping> declarations boolean inserted = false; int current = reader.read(); while (current > -1) { if (current == '<') { String element = getElement(reader); if (!inserted && insertBefore.contains(element)) { // Insert generated content here writer.println(insertStartMarker); while (true) { String line = fragmentReader.readLine(); if (line == null) { writer.println(); break; } writer.println(line); } writer.println(insertEndMarker); writer.println(); writer.write(element); inserted = true; } else if (element.equals(insertStartMarker)) { // Skip the previous auto-generated content while (true) { current = reader.read(); if (current < 0) { throw new EOFException(); } if (current == '<') { element = getElement(reader); if (element.equals(insertEndMarker)) { break; } } } current = reader.read(); while (current == '\n' || current == '\r') { current = reader.read(); } continue; } else { writer.write(element); } } else { writer.write(current); } current = reader.read(); } } try (FileInputStream fis = new FileInputStream(webXml2); FileOutputStream fos = new FileOutputStream(webXml)) { byte buf[] = new byte[512]; while (true) { int n = fis.read(buf); if (n < 0) { break; } fos.write(buf, 0, n); } } if(!webXml2.delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webXml2.toString())); if (!(new File(webxmlFile)).delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile)); } /* * Assumes valid xml */ private String getElement(Reader reader) throws IOException { StringBuilder result = new StringBuilder(); result.append('<'); boolean done = false; while (!done) { int current = reader.read(); while (current != '>') { if (current < 0) { throw new EOFException(); } result.append((char) current); current = reader.read(); } result.append((char) current); int len = result.length(); if (len > 4 && result.substring(0, 4).equals("<!--")) { // This is a comment - make sure we are at the end if (len >= 7 && result.substring(len - 3, len).equals("-->")) { done = true; } } else { done = true; } } return result.toString(); } protected void processFile(String file) throws JasperException { if (log.isDebugEnabled()) { log.debug("Processing file: " + file); } ClassLoader originalClassLoader = null; try { // set up a scratch/output dir if none is provided if (scratchDir == null) { String temp = System.getProperty("java.io.tmpdir"); if (temp == null) { temp = ""; } scratchDir = new File(new File(temp).getAbsolutePath()); } String jspUri=file.replace('\\','/'); JspCompilationContext clctxt = new JspCompilationContext ( jspUri, this, context, null, rctxt ); /* Override the defaults */ if ((targetClassName != null) && (targetClassName.length() > 0)) { clctxt.setServletClassName(targetClassName); targetClassName = null; } if (targetPackage != null) { clctxt.setServletPackageName(targetPackage); } originalClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(loader); clctxt.setClassLoader(loader); clctxt.setClassPath(classPath); Compiler clc = clctxt.createCompiler(); // If compile is set, generate both .java and .class, if // .jsp file is newer than .class file; // Otherwise only generate .java, if .jsp file is newer than // the .java file if( clc.isOutDated(compile) ) { if (log.isDebugEnabled()) { log.debug(jspUri + " is out dated, compiling..."); } clc.compile(compile, true); } // Generate mapping generateWebMapping( file, clctxt ); if ( showSuccess ) { log.info( "Built File: " + file ); } } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } } catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); } finally { if(originalClassLoader != null) { Thread.currentThread().setContextClassLoader(originalClassLoader); } } } /** * Locate all jsp files in the webapp. Used if no explicit * jsps are specified. */ public void scanFiles( File base ) { Stack<String> dirs = new Stack<>(); dirs.push(base.toString()); // Make sure default extensions are always included if ((getExtensions() == null) || (getExtensions().size() < 2)) { addExtension("jsp"); addExtension("jspx"); } while (!dirs.isEmpty()) { String s = dirs.pop(); File f = new File(s); if (f.exists() && f.isDirectory()) { String[] files = f.list(); String ext; for (int i = 0; (files != null) && i < files.length; i++) { File f2 = new File(s, files[i]); if (f2.isDirectory()) { dirs.push(f2.getPath()); } else { String path = f2.getPath(); String uri = path.substring(uriRoot.length()); ext = files[i].substring(files[i].lastIndexOf('.') +1); if (getExtensions().contains(ext) || jspConfig.isJspPage(uri)) { pages.add(path); } } } } } } /** * Executes the compilation. */ @Override public void execute() { if(log.isDebugEnabled()) { log.debug("execute() starting for " + pages.size() + " pages."); } try { if (uriRoot == null) { if( pages.size() == 0 ) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.missingTarget")); } String firstJsp = pages.get( 0 ); File firstJspF = new File( firstJsp ); if (!firstJspF.exists()) { throw new JasperException( Localizer.getMessage("jspc.error.fileDoesNotExist", firstJsp)); } locateUriRoot( firstJspF ); } if (uriRoot == null) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.no_uriroot")); } File uriRootF = new File(uriRoot); if (!uriRootF.isDirectory()) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.uriroot_not_dir")); } if (loader == null) { loader = initClassLoader(); } if (context == null) { initServletContext(loader); } // No explicit pages, we'll process all .jsp in the webapp if (pages.size() == 0) { scanFiles(uriRootF); } initWebXml(); Iterator<String> iter = pages.iterator(); while (iter.hasNext()) { String nextjsp = iter.next().toString(); File fjsp = new File(nextjsp); if (!fjsp.isAbsolute()) { fjsp = new File(uriRootF, nextjsp); } if (!fjsp.exists()) { if (log.isWarnEnabled()) { log.warn (Localizer.getMessage ("jspc.error.fileDoesNotExist", fjsp.toString())); } continue; } String s = fjsp.getAbsolutePath(); if (s.startsWith(uriRoot)) { nextjsp = s.substring(uriRoot.length()); } if (nextjsp.startsWith("." + File.separatorChar)) { nextjsp = nextjsp.substring(2); } processFile(nextjsp); } completeWebXml(); if (addWebXmlMappings) { mergeIntoWebXml(); } } catch (IOException ioe) { throw new BuildException(ioe); } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw new BuildException(je); } finally { if (loader != null) { LogFactory.release(loader); } } } // ==================== protected utility methods ==================== protected String nextArg() { if ((argPos >= args.length) || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) { return null; } else { return args[argPos++]; } } protected String nextFile() { if (fullstop) argPos++; if (argPos >= args.length) { return null; } else { return args[argPos++]; } } protected void initWebXml() throws JasperException { try { if (webxmlLevel >= INC_WEBXML) { mapout = openWebxmlWriter(new File(webxmlFile)); servletout = new CharArrayWriter(); mappingout = new CharArrayWriter(); } else { mapout = null; servletout = null; mappingout = null; } if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.header")); mapout.flush(); } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.header")); mapout.flush(); } } catch (IOException ioe) { mapout = null; servletout = null; mappingout = null; throw new JasperException(ioe); } } protected void completeWebXml() { if (mapout != null) { try { servletout.writeTo(mapout); mappingout.writeTo(mapout); if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.footer")); } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.footer")); } mapout.close(); } catch (IOException ioe) { // nothing to do if it fails since we are done with it } } } protected void initTldScanner(JspCServletContext context, ClassLoader classLoader) { if (scanner != null) { return; } scanner = newTldScanner(context, true, isValidateTld(), isBlockExternal()); scanner.setClassLoader(classLoader); } protected TldScanner newTldScanner(JspCServletContext context, boolean namespaceAware, boolean validate, boolean blockExternal) { return new TldScanner(context, namespaceAware, validate, blockExternal); } protected void initServletContext(ClassLoader classLoader) throws IOException, JasperException { // TODO: should we use the Ant Project's log? PrintWriter log = new PrintWriter(System.out); URL resourceBase = new File(uriRoot).getCanonicalFile().toURI().toURL(); context = new JspCServletContext(log, resourceBase, classLoader, isValidateXml(), isBlockExternal()); if (isValidateTld()) { context.setInitParameter(Constants.XML_VALIDATION_TLD_INIT_PARAM, "true"); } initTldScanner(context, classLoader); try { scanner.scan(); } catch (SAXException e) { throw new JasperException(e); } tldCache = new TldCache(context, scanner.getUriTldResourcePathMap(), scanner.getTldResourcePathTaglibXmlMap()); context.setAttribute(TldCache.SERVLET_CONTEXT_ATTRIBUTE_NAME, tldCache); rctxt = new JspRuntimeContext(context, this); jspConfig = new JspConfig(context); tagPluginManager = new TagPluginManager(context); } /** * Initializes the classloader as/if needed for the given * compilation context. * * @throws IOException If an error occurs */ protected ClassLoader initClassLoader() throws IOException { classPath = getClassPath(); ClassLoader jspcLoader = getClass().getClassLoader(); if (jspcLoader instanceof AntClassLoader) { classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath(); } // Turn the classPath into URLs ArrayList<URL> urls = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURI().toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } File webappBase = new File(uriRoot); if (webappBase.exists()) { File classes = new File(webappBase, "/WEB-INF/classes"); try { if (classes.exists()) { classPath = classPath + File.pathSeparator + classes.getCanonicalPath(); urls.add(classes.getCanonicalFile().toURI().toURL()); } } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } File lib = new File(webappBase, "/WEB-INF/lib"); if (lib.exists() && lib.isDirectory()) { String[] libs = lib.list(); for (int i = 0; i < libs.length; i++) { if( libs[i].length() <5 ) continue; String ext=libs[i].substring( libs[i].length() - 4 ); if (! ".jar".equalsIgnoreCase(ext)) { if (".tld".equalsIgnoreCase(ext)) { log.warn("TLD files should not be placed in " + "/WEB-INF/lib"); } continue; } try { File libFile = new File(lib, libs[i]); classPath = classPath + File.pathSeparator + libFile.getAbsolutePath(); urls.add(libFile.getAbsoluteFile().toURI().toURL()); } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } } } } URL urlsA[]=new URL[urls.size()]; urls.toArray(urlsA); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); return loader; } /** * Find the WEB-INF dir by looking up in the directory tree. * This is used if no explicit docbase is set, but only files. * XXX Maybe we should require the docbase. */ protected void locateUriRoot( File f ) { String tUriBase = uriBase; if (tUriBase == null) { tUriBase = "/"; } try { if (f.exists()) { f = new File(f.getAbsolutePath()); while (true) { File g = new File(f, "WEB-INF"); if (g.exists() && g.isDirectory()) { uriRoot = f.getCanonicalPath(); uriBase = tUriBase; if (log.isInfoEnabled()) { log.info(Localizer.getMessage( "jspc.implicit.uriRoot", uriRoot)); } break; } if (f.exists() && f.isDirectory()) { tUriBase = "/" + f.getName() + "/" + tUriBase; } String fParent = f.getParent(); if (fParent == null) { break; } else { f = new File(fParent); } // If there is no acceptable candidate, uriRoot will // remain null to indicate to the CompilerContext to // use the current working/user dir. } if (uriRoot != null) { File froot = new File(uriRoot); uriRoot = froot.getCanonicalPath(); } } } catch (IOException ioe) { // since this is an optional default and a null value // for uriRoot has a non-error meaning, we can just // pass straight through } } /** * Resolves the relative or absolute pathname correctly * in both Ant and command-line situations. If Ant launched * us, we should use the basedir of the current project * to resolve relative paths. * * See Bugzilla 35571. * * @param s The file * @return The file resolved */ protected File resolveFile(final String s) { if(getProject() == null) { // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3 return FileUtils.getFileUtils().resolveFile(null, s); } else { return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s); } } private Reader openWebxmlReader(File file) throws IOException { FileInputStream fis = new FileInputStream(file); try { return webxmlEncoding != null ? new InputStreamReader(fis, webxmlEncoding) : new InputStreamReader(fis); } catch (IOException ex) { fis.close(); throw ex; } } private Writer openWebxmlWriter(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { return webxmlEncoding != null ? new OutputStreamWriter(fos, webxmlEncoding) : new OutputStreamWriter(fos); } catch (IOException ex) { fos.close(); throw ex; } } }
java/org/apache/jasper/JspC.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; 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.Stack; import java.util.StringTokenizer; import java.util.Vector; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.compiler.Compiler; import org.apache.jasper.compiler.JspConfig; import org.apache.jasper.compiler.JspRuntimeContext; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.compiler.TagPluginManager; import org.apache.jasper.compiler.TldCache; import org.apache.jasper.runtime.JspFactoryImpl; import org.apache.jasper.servlet.JspCServletContext; import org.apache.jasper.servlet.TldScanner; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.util.FileUtils; import org.xml.sax.SAXException; /** * Shell for the jspc compiler. Handles all options associated with the * command line and creates compilation contexts which it then compiles * according to the specified options. * * This version can process files from a _single_ webapp at once, i.e. * a single docbase can be specified. * * It can be used as an Ant task using: * <pre> * &lt;taskdef classname="org.apache.jasper.JspC" name="jasper" &gt; * &lt;classpath&gt; * &lt;pathelement location="${java.home}/../lib/tools.jar"/&gt; * &lt;fileset dir="${ENV.CATALINA_HOME}/lib"&gt; * &lt;include name="*.jar"/&gt; * &lt;/fileset&gt; * &lt;path refid="myjars"/&gt; * &lt;/classpath&gt; * &lt;/taskdef&gt; * * &lt;jasper verbose="0" * package="my.package" * uriroot="${webapps.dir}/${webapp.name}" * webXmlFragment="${build.dir}/generated_web.xml" * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" /&gt; * </pre> * * @author Danno Ferrin * @author Pierre Delisle * @author Costin Manolache * @author Yoav Shapira */ public class JspC extends Task implements Options { static { // the Validator uses this to access the EL ExpressionFactory JspFactory.setDefaultFactory(new JspFactoryImpl()); } public static final String DEFAULT_IE_CLASS_ID = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"; // Logger private static final Log log = LogFactory.getLog(JspC.class); protected static final String SWITCH_VERBOSE = "-v"; protected static final String SWITCH_HELP = "-help"; protected static final String SWITCH_OUTPUT_DIR = "-d"; protected static final String SWITCH_PACKAGE_NAME = "-p"; protected static final String SWITCH_CACHE = "-cache"; protected static final String SWITCH_CLASS_NAME = "-c"; protected static final String SWITCH_FULL_STOP = "--"; protected static final String SWITCH_COMPILE = "-compile"; protected static final String SWITCH_SOURCE = "-source"; protected static final String SWITCH_TARGET = "-target"; protected static final String SWITCH_URI_BASE = "-uribase"; protected static final String SWITCH_URI_ROOT = "-uriroot"; protected static final String SWITCH_FILE_WEBAPP = "-webapp"; protected static final String SWITCH_WEBAPP_INC = "-webinc"; protected static final String SWITCH_WEBAPP_XML = "-webxml"; protected static final String SWITCH_WEBAPP_XML_ENCODING = "-webxmlencoding"; protected static final String SWITCH_ADD_WEBAPP_XML_MAPPINGS = "-addwebxmlmappings"; protected static final String SWITCH_MAPPED = "-mapped"; protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy"; protected static final String SWITCH_TRIM_SPACES = "-trimSpaces"; protected static final String SWITCH_CLASSPATH = "-classpath"; protected static final String SWITCH_DIE = "-die"; protected static final String SWITCH_POOLING = "-poolingEnabled"; protected static final String SWITCH_ENCODING = "-javaEncoding"; protected static final String SWITCH_SMAP = "-smap"; protected static final String SWITCH_DUMP_SMAP = "-dumpsmap"; protected static final String SWITCH_VALIDATE_TLD = "-validateTld"; protected static final String SWITCH_VALIDATE_XML = "-validateXml"; protected static final String SWITCH_BLOCK_EXTERNAL = "-blockExternal"; protected static final String SWITCH_NO_BLOCK_EXTERNAL = "-no-blockExternal"; protected static final String SWITCH_STRICT_QUOTE_ESCAPING = "-strictQuoteEscaping"; protected static final String SWITCH_NO_STRICT_QUOTE_ESCAPING = "-no-strictQuoteEscaping"; protected static final String SHOW_SUCCESS ="-s"; protected static final String LIST_ERRORS = "-l"; protected static final int INC_WEBXML = 10; protected static final int ALL_WEBXML = 20; protected static final int DEFAULT_DIE_LEVEL = 1; protected static final int NO_DIE_LEVEL = 0; protected static final Set<String> insertBefore = new HashSet<>(); static { insertBefore.add("</web-app>"); insertBefore.add("<servlet-mapping>"); insertBefore.add("<session-config>"); insertBefore.add("<mime-mapping>"); insertBefore.add("<welcome-file-list>"); insertBefore.add("<error-page>"); insertBefore.add("<taglib>"); insertBefore.add("<resource-env-ref>"); insertBefore.add("<resource-ref>"); insertBefore.add("<security-constraint>"); insertBefore.add("<login-config>"); insertBefore.add("<security-role>"); insertBefore.add("<env-entry>"); insertBefore.add("<ejb-ref>"); insertBefore.add("<ejb-local-ref>"); } protected String classPath = null; protected ClassLoader loader = null; protected boolean trimSpaces = false; protected boolean genStringAsCharArray = false; protected boolean validateTld; protected boolean validateXml; protected boolean blockExternal = true; protected boolean strictQuoteEscaping = true; protected boolean xpoweredBy; protected boolean mappedFile = false; protected boolean poolingEnabled = true; protected File scratchDir; protected String ieClassId = DEFAULT_IE_CLASS_ID; protected String targetPackage; protected String targetClassName; protected String uriBase; protected String uriRoot; protected int dieLevel; protected boolean helpNeeded = false; protected boolean compile = false; protected boolean smapSuppressed = true; protected boolean smapDumped = false; protected boolean caching = true; protected final Map<String, TagLibraryInfo> cache = new HashMap<>(); protected String compiler = null; protected String compilerTargetVM = "1.8"; protected String compilerSourceVM = "1.8"; protected boolean classDebugInfo = true; /** * Throw an exception if there's a compilation error, or swallow it. * Default is true to preserve old behavior. */ protected boolean failOnError = true; /** * The file extensions to be handled as JSP files. * Default list is .jsp and .jspx. */ protected List<String> extensions; /** * The pages. */ protected final List<String> pages = new Vector<>(); /** * Needs better documentation, this data member does. * True by default. */ protected boolean errorOnUseBeanInvalidClassAttribute = true; /** * The java file encoding. Default * is UTF-8. Added per bugzilla 19622. */ protected String javaEncoding = "UTF-8"; // Generation of web.xml fragments protected String webxmlFile; protected int webxmlLevel; protected String webxmlEncoding; protected boolean addWebXmlMappings = false; protected Writer mapout; protected CharArrayWriter servletout; protected CharArrayWriter mappingout; /** * The servlet context. */ protected JspCServletContext context; /** * The runtime context. * Maintain a dummy JspRuntimeContext for compiling tag files. */ protected JspRuntimeContext rctxt; /** * Cache for the TLD locations */ protected TldCache tldCache = null; protected JspConfig jspConfig = null; protected TagPluginManager tagPluginManager = null; protected TldScanner scanner = null; protected boolean verbose = false; protected boolean listErrors = false; protected boolean showSuccess = false; protected int argPos; protected boolean fullstop = false; protected String args[]; public static void main(String arg[]) { if (arg.length == 0) { System.out.println(Localizer.getMessage("jspc.usage")); } else { JspC jspc = new JspC(); try { jspc.setArgs(arg); if (jspc.helpNeeded) { System.out.println(Localizer.getMessage("jspc.usage")); } else { jspc.execute(); } } catch (JasperException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } } catch (BuildException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } } } } /** * Apply command-line arguments. * * @param arg * The arguments */ public void setArgs(String[] arg) throws JasperException { args = arg; String tok; dieLevel = NO_DIE_LEVEL; while ((tok = nextArg()) != null) { if (tok.equals(SWITCH_VERBOSE)) { verbose = true; showSuccess = true; listErrors = true; } else if (tok.equals(SWITCH_OUTPUT_DIR)) { tok = nextArg(); setOutputDir( tok ); } else if (tok.equals(SWITCH_PACKAGE_NAME)) { targetPackage = nextArg(); } else if (tok.equals(SWITCH_COMPILE)) { compile=true; } else if (tok.equals(SWITCH_CLASS_NAME)) { targetClassName = nextArg(); } else if (tok.equals(SWITCH_URI_BASE)) { uriBase=nextArg(); } else if (tok.equals(SWITCH_URI_ROOT)) { setUriroot( nextArg()); } else if (tok.equals(SWITCH_FILE_WEBAPP)) { setUriroot( nextArg()); } else if ( tok.equals( SHOW_SUCCESS ) ) { showSuccess = true; } else if ( tok.equals( LIST_ERRORS ) ) { listErrors = true; } else if (tok.equals(SWITCH_WEBAPP_INC)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = INC_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = ALL_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) { setWebXmlEncoding(nextArg()); } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) { setAddWebXmlMappings(true); } else if (tok.equals(SWITCH_MAPPED)) { mappedFile = true; } else if (tok.equals(SWITCH_XPOWERED_BY)) { xpoweredBy = true; } else if (tok.equals(SWITCH_TRIM_SPACES)) { setTrimSpaces(true); } else if (tok.equals(SWITCH_CACHE)) { tok = nextArg(); if ("false".equals(tok)) { caching = false; } else { caching = true; } } else if (tok.equals(SWITCH_CLASSPATH)) { setClassPath(nextArg()); } else if (tok.startsWith(SWITCH_DIE)) { try { dieLevel = Integer.parseInt( tok.substring(SWITCH_DIE.length())); } catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; } } else if (tok.equals(SWITCH_HELP)) { helpNeeded = true; } else if (tok.equals(SWITCH_POOLING)) { tok = nextArg(); if ("false".equals(tok)) { poolingEnabled = false; } else { poolingEnabled = true; } } else if (tok.equals(SWITCH_ENCODING)) { setJavaEncoding(nextArg()); } else if (tok.equals(SWITCH_SOURCE)) { setCompilerSourceVM(nextArg()); } else if (tok.equals(SWITCH_TARGET)) { setCompilerTargetVM(nextArg()); } else if (tok.equals(SWITCH_SMAP)) { smapSuppressed = false; } else if (tok.equals(SWITCH_DUMP_SMAP)) { smapDumped = true; } else if (tok.equals(SWITCH_VALIDATE_TLD)) { setValidateTld(true); } else if (tok.equals(SWITCH_VALIDATE_XML)) { setValidateXml(true); } else if (tok.equals(SWITCH_NO_BLOCK_EXTERNAL)) { setBlockExternal(false); } else if (tok.equals(SWITCH_NO_STRICT_QUOTE_ESCAPING)) { setStrictQuoteEscaping(false); } else { if (tok.startsWith("-")) { throw new JasperException("Unrecognized option: " + tok + ". Use -help for help."); } if (!fullstop) { argPos--; } // Start treating the rest as JSP Pages break; } } // Add all extra arguments to the list of files while( true ) { String file = nextFile(); if( file==null ) { break; } pages.add( file ); } } /** * In JspC this always returns <code>true</code>. * {@inheritDoc} */ @Override public boolean getKeepGenerated() { // isn't this why we are running jspc? return true; } /** * {@inheritDoc} */ @Override public boolean getTrimSpaces() { return trimSpaces; } /** * Sets the option to trim white spaces between directives or actions. */ public void setTrimSpaces(boolean ts) { this.trimSpaces = ts; } /** * {@inheritDoc} */ @Override public boolean isPoolingEnabled() { return poolingEnabled; } /** * Sets the option to enable the tag handler pooling. */ public void setPoolingEnabled(boolean poolingEnabled) { this.poolingEnabled = poolingEnabled; } /** * {@inheritDoc} */ @Override public boolean isXpoweredBy() { return xpoweredBy; } /** * Sets the option to enable generation of X-Powered-By response header. */ public void setXpoweredBy(boolean xpoweredBy) { this.xpoweredBy = xpoweredBy; } /** * In JspC this always returns <code>true</code>. * {@inheritDoc} */ @Override public boolean getDisplaySourceFragment() { return true; } @Override public int getMaxLoadedJsps() { return -1; } @Override public int getJspIdleTimeout() { return -1; } /** * {@inheritDoc} */ @Override public boolean getErrorOnUseBeanInvalidClassAttribute() { return errorOnUseBeanInvalidClassAttribute; } /** * Sets the option to issue a compilation error if the class attribute * specified in useBean action is invalid. */ public void setErrorOnUseBeanInvalidClassAttribute(boolean b) { errorOnUseBeanInvalidClassAttribute = b; } /** * {@inheritDoc} */ @Override public boolean getMappedFile() { return mappedFile; } public void setMappedFile(boolean b) { mappedFile = b; } /** * Sets the option to include debug information in compiled class. */ public void setClassDebugInfo( boolean b ) { classDebugInfo=b; } /** * {@inheritDoc} */ @Override public boolean getClassDebugInfo() { // compile with debug info return classDebugInfo; } /** * {@inheritDoc} */ @Override public boolean isCaching() { return caching; } /** * Sets the option to enable caching. * * @see Options#isCaching() */ public void setCaching(boolean caching) { this.caching = caching; } /** * {@inheritDoc} */ @Override public Map<String, TagLibraryInfo> getCache() { return cache; } /** * In JspC this always returns <code>0</code>. * {@inheritDoc} */ @Override public int getCheckInterval() { return 0; } /** * In JspC this always returns <code>0</code>. * {@inheritDoc} */ @Override public int getModificationTestInterval() { return 0; } /** * In JspC this always returns <code>false</code>. * {@inheritDoc} */ @Override public boolean getRecompileOnFail() { return false; } /** * In JspC this always returns <code>false</code>. * {@inheritDoc} */ @Override public boolean getDevelopment() { return false; } /** * {@inheritDoc} */ @Override public boolean isSmapSuppressed() { return smapSuppressed; } /** * Sets smapSuppressed flag. */ public void setSmapSuppressed(boolean smapSuppressed) { this.smapSuppressed = smapSuppressed; } /** * {@inheritDoc} */ @Override public boolean isSmapDumped() { return smapDumped; } /** * Sets smapDumped flag. * * @see Options#isSmapDumped() */ public void setSmapDumped(boolean smapDumped) { this.smapDumped = smapDumped; } /** * Determines whether text strings are to be generated as char arrays, * which improves performance in some cases. * * @param genStringAsCharArray true if text strings are to be generated as * char arrays, false otherwise */ public void setGenStringAsCharArray(boolean genStringAsCharArray) { this.genStringAsCharArray = genStringAsCharArray; } /** * {@inheritDoc} */ @Override public boolean genStringAsCharArray() { return genStringAsCharArray; } /** * Sets the class-id value to be sent to Internet Explorer when using * &lt;jsp:plugin&gt; tags. * * @param ieClassId * Class-id value */ public void setIeClassId(String ieClassId) { this.ieClassId = ieClassId; } /** * {@inheritDoc} */ @Override public String getIeClassId() { return ieClassId; } /** * {@inheritDoc} */ @Override public File getScratchDir() { return scratchDir; } /** * {@inheritDoc} */ @Override public String getCompiler() { return compiler; } /** * Sets the option to determine what compiler to use. * * @see Options#getCompiler() */ public void setCompiler(String c) { compiler=c; } /** * {@inheritDoc} */ @Override public String getCompilerClassName() { return null; } /** * {@inheritDoc} */ @Override public String getCompilerTargetVM() { return compilerTargetVM; } /** * Sets the compiler target VM. * * @see Options#getCompilerTargetVM() */ public void setCompilerTargetVM(String vm) { compilerTargetVM = vm; } /** * {@inheritDoc} */ @Override public String getCompilerSourceVM() { return compilerSourceVM; } /** * Sets the compiler source VM. * * @see Options#getCompilerSourceVM() */ public void setCompilerSourceVM(String vm) { compilerSourceVM = vm; } /** * {@inheritDoc} */ @Override public TldCache getTldCache() { return tldCache; } /** * Returns the encoding to use for * java files. The default is UTF-8. * * @return String The encoding */ @Override public String getJavaEncoding() { return javaEncoding; } /** * Sets the encoding to use for * java files. * * @param encodingName The name, e.g. "UTF-8" */ public void setJavaEncoding(String encodingName) { javaEncoding = encodingName; } /** * {@inheritDoc} */ @Override public boolean getFork() { return false; } /** * {@inheritDoc} */ @Override public String getClassPath() { if( classPath != null ) return classPath; return System.getProperty("java.class.path"); } /** * Sets the classpath used while compiling the servlets generated from JSP * files */ public void setClassPath(String s) { classPath=s; } /** * Returns the list of file extensions * that are treated as JSP files. * * @return The list of extensions */ public List<String> getExtensions() { return extensions; } /** * Adds the given file extension to the * list of extensions handled as JSP files. * * @param extension The extension to add, e.g. "myjsp" */ protected void addExtension(final String extension) { if(extension != null) { if(extensions == null) { extensions = new Vector<>(); } extensions.add(extension); } } /** * Base dir for the webapp. Used to generate class names and resolve * includes. */ public void setUriroot( String s ) { if (s == null) { uriRoot = null; return; } try { uriRoot = resolveFile(s).getCanonicalPath(); } catch( Exception ex ) { uriRoot = s; } } /** * Parses comma-separated list of JSP files to be processed. If the argument * is null, nothing is done. * * <p>Each file is interpreted relative to uriroot, unless it is absolute, * in which case it must start with uriroot.</p> * * @param jspFiles Comma-separated list of JSP files to be processed */ public void setJspFiles(final String jspFiles) { if(jspFiles == null) { return; } StringTokenizer tok = new StringTokenizer(jspFiles, ","); while (tok.hasMoreTokens()) { pages.add(tok.nextToken()); } } /** * Sets the compile flag. * * @param b Flag value */ public void setCompile( final boolean b ) { compile = b; } /** * Sets the verbosity level. The actual number doesn't * matter: if it's greater than zero, the verbose flag will * be true. * * @param level Positive means verbose */ public void setVerbose( final int level ) { if (level > 0) { verbose = true; showSuccess = true; listErrors = true; } } public void setValidateTld( boolean b ) { this.validateTld = b; } public boolean isValidateTld() { return validateTld; } public void setValidateXml( boolean b ) { this.validateXml = b; } public boolean isValidateXml() { return validateXml; } public void setBlockExternal( boolean b ) { this.blockExternal = b; } public boolean isBlockExternal() { return blockExternal; } public void setStrictQuoteEscaping( boolean b ) { this.strictQuoteEscaping = b; } @Override public boolean getStrictQuoteEscaping() { return strictQuoteEscaping; } public void setListErrors( boolean b ) { listErrors = b; } public void setOutputDir( String s ) { if( s!= null ) { scratchDir = resolveFile(s).getAbsoluteFile(); } else { scratchDir=null; } } /** * Sets the package name to be used for the generated servlet classes. */ public void setPackage( String p ) { targetPackage=p; } /** * Class name of the generated file ( without package ). * Can only be used if a single file is converted. * XXX Do we need this feature ? */ public void setClassName( String p ) { targetClassName=p; } /** * File where we generate a web.xml fragment with the class definitions. */ public void setWebXmlFragment( String s ) { webxmlFile=resolveFile(s).getAbsolutePath(); webxmlLevel=INC_WEBXML; } /** * File where we generate a complete web.xml with the class definitions. */ public void setWebXml( String s ) { webxmlFile=resolveFile(s).getAbsolutePath(); webxmlLevel=ALL_WEBXML; } /** * Sets the encoding to be used to read and write web.xml files. * * <p> * If not specified, defaults to the platform default encoding. * </p> * * @param encoding * Encoding, e.g. "UTF-8". */ public void setWebXmlEncoding(String encoding) { webxmlEncoding = encoding; } /** * Sets the option to merge generated web.xml fragment into the * WEB-INF/web.xml file of the web application that we were processing. * * @param b * <code>true</code> to merge the fragment into the existing * web.xml file of the processed web application * ({uriroot}/WEB-INF/web.xml), <code>false</code> to keep the * generated web.xml fragment */ public void setAddWebXmlMappings(boolean b) { addWebXmlMappings = b; } /** * Sets the option that throws an exception in case of a compilation error. */ public void setFailOnError(final boolean b) { failOnError = b; } /** * Returns true if an exception will be thrown in case of a compilation * error. */ public boolean getFailOnError() { return failOnError; } /** * {@inheritDoc} */ @Override public JspConfig getJspConfig() { return jspConfig; } /** * {@inheritDoc} */ @Override public TagPluginManager getTagPluginManager() { return tagPluginManager; } /** * Adds servlet declaration and mapping for the JSP page servlet to the * generated web.xml fragment. * * @param file * Context-relative path to the JSP file, e.g. * <code>/index.jsp</code> * @param clctxt * Compilation context of the servlet */ public void generateWebMapping( String file, JspCompilationContext clctxt ) throws IOException { if (log.isDebugEnabled()) { log.debug("Generating web mapping for file " + file + " using compilation context " + clctxt); } String className = clctxt.getServletClassName(); String packageName = clctxt.getServletPackageName(); String thisServletName; if ("".equals(packageName)) { thisServletName = className; } else { thisServletName = packageName + '.' + className; } if (servletout != null) { servletout.write("\n <servlet>\n <servlet-name>"); servletout.write(thisServletName); servletout.write("</servlet-name>\n <servlet-class>"); servletout.write(thisServletName); servletout.write("</servlet-class>\n </servlet>\n"); } if (mappingout != null) { mappingout.write("\n <servlet-mapping>\n <servlet-name>"); mappingout.write(thisServletName); mappingout.write("</servlet-name>\n <url-pattern>"); mappingout.write(file.replace('\\', '/')); mappingout.write("</url-pattern>\n </servlet-mapping>\n"); } } /** * Include the generated web.xml inside the webapp's web.xml. */ protected void mergeIntoWebXml() throws IOException { File webappBase = new File(uriRoot); File webXml = new File(webappBase, "WEB-INF/web.xml"); File webXml2 = new File(webappBase, "WEB-INF/web2.xml"); String insertStartMarker = Localizer.getMessage("jspc.webinc.insertStart"); String insertEndMarker = Localizer.getMessage("jspc.webinc.insertEnd"); try (BufferedReader reader = new BufferedReader(openWebxmlReader(webXml)); BufferedReader fragmentReader = new BufferedReader(openWebxmlReader(new File(webxmlFile))); PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2))) { // Insert the <servlet> and <servlet-mapping> declarations boolean inserted = false; int current = reader.read(); while (current > -1) { if (current == '<') { String element = getElement(reader); if (!inserted && insertBefore.contains(element)) { // Insert generated content here writer.println(insertStartMarker); while (true) { String line = fragmentReader.readLine(); if (line == null) { writer.println(); break; } writer.println(line); } writer.println(insertEndMarker); writer.println(); writer.write(element); inserted = true; } else if (element.equals(insertStartMarker)) { // Skip the previous auto-generated content while (true) { current = reader.read(); if (current < 0) { throw new EOFException(); } if (current == '<') { element = getElement(reader); if (element.equals(insertEndMarker)) { break; } } } current = reader.read(); while (current == '\n' || current == '\r') { current = reader.read(); } continue; } else { writer.write(element); } } else { writer.write(current); } current = reader.read(); } } try (FileInputStream fis = new FileInputStream(webXml2); FileOutputStream fos = new FileOutputStream(webXml)) { byte buf[] = new byte[512]; while (true) { int n = fis.read(buf); if (n < 0) { break; } fos.write(buf, 0, n); } } if(!webXml2.delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webXml2.toString())); if (!(new File(webxmlFile)).delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile)); } /* * Assumes valid xml */ private String getElement(Reader reader) throws IOException { StringBuilder result = new StringBuilder(); result.append('<'); boolean done = false; while (!done) { int current = reader.read(); while (current != '>') { if (current < 0) { throw new EOFException(); } result.append((char) current); current = reader.read(); } result.append((char) current); int len = result.length(); if (len > 4 && result.substring(0, 4).equals("<!--")) { // This is a comment - make sure we are at the end if (len >= 7 && result.substring(len - 3, len).equals("-->")) { done = true; } } else { done = true; } } return result.toString(); } protected void processFile(String file) throws JasperException { if (log.isDebugEnabled()) { log.debug("Processing file: " + file); } ClassLoader originalClassLoader = null; try { // set up a scratch/output dir if none is provided if (scratchDir == null) { String temp = System.getProperty("java.io.tmpdir"); if (temp == null) { temp = ""; } scratchDir = new File(new File(temp).getAbsolutePath()); } String jspUri=file.replace('\\','/'); JspCompilationContext clctxt = new JspCompilationContext ( jspUri, this, context, null, rctxt ); /* Override the defaults */ if ((targetClassName != null) && (targetClassName.length() > 0)) { clctxt.setServletClassName(targetClassName); targetClassName = null; } if (targetPackage != null) { clctxt.setServletPackageName(targetPackage); } originalClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(loader); clctxt.setClassLoader(loader); clctxt.setClassPath(classPath); Compiler clc = clctxt.createCompiler(); // If compile is set, generate both .java and .class, if // .jsp file is newer than .class file; // Otherwise only generate .java, if .jsp file is newer than // the .java file if( clc.isOutDated(compile) ) { if (log.isDebugEnabled()) { log.debug(jspUri + " is out dated, compiling..."); } clc.compile(compile, true); } // Generate mapping generateWebMapping( file, clctxt ); if ( showSuccess ) { log.info( "Built File: " + file ); } } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } } catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); } finally { if(originalClassLoader != null) { Thread.currentThread().setContextClassLoader(originalClassLoader); } } } /** * Locate all jsp files in the webapp. Used if no explicit * jsps are specified. */ public void scanFiles( File base ) { Stack<String> dirs = new Stack<>(); dirs.push(base.toString()); // Make sure default extensions are always included if ((getExtensions() == null) || (getExtensions().size() < 2)) { addExtension("jsp"); addExtension("jspx"); } while (!dirs.isEmpty()) { String s = dirs.pop(); File f = new File(s); if (f.exists() && f.isDirectory()) { String[] files = f.list(); String ext; for (int i = 0; (files != null) && i < files.length; i++) { File f2 = new File(s, files[i]); if (f2.isDirectory()) { dirs.push(f2.getPath()); } else { String path = f2.getPath(); String uri = path.substring(uriRoot.length()); ext = files[i].substring(files[i].lastIndexOf('.') +1); if (getExtensions().contains(ext) || jspConfig.isJspPage(uri)) { pages.add(path); } } } } } } /** * Executes the compilation. */ @Override public void execute() { if(log.isDebugEnabled()) { log.debug("execute() starting for " + pages.size() + " pages."); } try { if (uriRoot == null) { if( pages.size() == 0 ) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.missingTarget")); } String firstJsp = pages.get( 0 ); File firstJspF = new File( firstJsp ); if (!firstJspF.exists()) { throw new JasperException( Localizer.getMessage("jspc.error.fileDoesNotExist", firstJsp)); } locateUriRoot( firstJspF ); } if (uriRoot == null) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.no_uriroot")); } File uriRootF = new File(uriRoot); if (!uriRootF.isDirectory()) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.uriroot_not_dir")); } if (loader == null) { loader = initClassLoader(); } if (context == null) { initServletContext(loader); } // No explicit pages, we'll process all .jsp in the webapp if (pages.size() == 0) { scanFiles(uriRootF); } initWebXml(); Iterator<String> iter = pages.iterator(); while (iter.hasNext()) { String nextjsp = iter.next().toString(); File fjsp = new File(nextjsp); if (!fjsp.isAbsolute()) { fjsp = new File(uriRootF, nextjsp); } if (!fjsp.exists()) { if (log.isWarnEnabled()) { log.warn (Localizer.getMessage ("jspc.error.fileDoesNotExist", fjsp.toString())); } continue; } String s = fjsp.getAbsolutePath(); if (s.startsWith(uriRoot)) { nextjsp = s.substring(uriRoot.length()); } if (nextjsp.startsWith("." + File.separatorChar)) { nextjsp = nextjsp.substring(2); } processFile(nextjsp); } completeWebXml(); if (addWebXmlMappings) { mergeIntoWebXml(); } } catch (IOException ioe) { throw new BuildException(ioe); } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw new BuildException(je); } finally { if (loader != null) { LogFactory.release(loader); } } } // ==================== protected utility methods ==================== protected String nextArg() { if ((argPos >= args.length) || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) { return null; } else { return args[argPos++]; } } protected String nextFile() { if (fullstop) argPos++; if (argPos >= args.length) { return null; } else { return args[argPos++]; } } protected void initWebXml() throws JasperException { try { if (webxmlLevel >= INC_WEBXML) { mapout = openWebxmlWriter(new File(webxmlFile)); servletout = new CharArrayWriter(); mappingout = new CharArrayWriter(); } else { mapout = null; servletout = null; mappingout = null; } if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.header")); mapout.flush(); } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.header")); mapout.flush(); } } catch (IOException ioe) { mapout = null; servletout = null; mappingout = null; throw new JasperException(ioe); } } protected void completeWebXml() { if (mapout != null) { try { servletout.writeTo(mapout); mappingout.writeTo(mapout); if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.footer")); } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.footer")); } mapout.close(); } catch (IOException ioe) { // nothing to do if it fails since we are done with it } } } protected void initTldScanner(JspCServletContext context, ClassLoader classLoader) { if (scanner != null) { return; } scanner = newTldScanner(context, true, isValidateTld(), isBlockExternal()); scanner.setClassLoader(classLoader); } protected TldScanner newTldScanner(JspCServletContext context, boolean namespaceAware, boolean validate, boolean blockExternal) { return new TldScanner(context, namespaceAware, validate, blockExternal); } protected void initServletContext(ClassLoader classLoader) throws IOException, JasperException { // TODO: should we use the Ant Project's log? PrintWriter log = new PrintWriter(System.out); URL resourceBase = new File(uriRoot).getCanonicalFile().toURI().toURL(); context = new JspCServletContext(log, resourceBase, classLoader, isValidateXml(), isBlockExternal()); if (isValidateTld()) { context.setInitParameter(Constants.XML_VALIDATION_TLD_INIT_PARAM, "true"); } initTldScanner(context, classLoader); try { scanner.scan(); } catch (SAXException e) { throw new JasperException(e); } tldCache = new TldCache(context, scanner.getUriTldResourcePathMap(), scanner.getTldResourcePathTaglibXmlMap()); context.setAttribute(TldCache.SERVLET_CONTEXT_ATTRIBUTE_NAME, tldCache); rctxt = new JspRuntimeContext(context, this); jspConfig = new JspConfig(context); tagPluginManager = new TagPluginManager(context); } /** * Initializes the classloader as/if needed for the given * compilation context. * * @throws IOException If an error occurs */ protected ClassLoader initClassLoader() throws IOException { classPath = getClassPath(); ClassLoader jspcLoader = getClass().getClassLoader(); if (jspcLoader instanceof AntClassLoader) { classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath(); } // Turn the classPath into URLs ArrayList<URL> urls = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURI().toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } File webappBase = new File(uriRoot); if (webappBase.exists()) { File classes = new File(webappBase, "/WEB-INF/classes"); try { if (classes.exists()) { classPath = classPath + File.pathSeparator + classes.getCanonicalPath(); urls.add(classes.getCanonicalFile().toURI().toURL()); } } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } File lib = new File(webappBase, "/WEB-INF/lib"); if (lib.exists() && lib.isDirectory()) { String[] libs = lib.list(); for (int i = 0; i < libs.length; i++) { if( libs[i].length() <5 ) continue; String ext=libs[i].substring( libs[i].length() - 4 ); if (! ".jar".equalsIgnoreCase(ext)) { if (".tld".equalsIgnoreCase(ext)) { log.warn("TLD files should not be placed in " + "/WEB-INF/lib"); } continue; } try { File libFile = new File(lib, libs[i]); classPath = classPath + File.pathSeparator + libFile.getAbsolutePath(); urls.add(libFile.getAbsoluteFile().toURI().toURL()); } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } } } } URL urlsA[]=new URL[urls.size()]; urls.toArray(urlsA); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); return loader; } /** * Find the WEB-INF dir by looking up in the directory tree. * This is used if no explicit docbase is set, but only files. * XXX Maybe we should require the docbase. */ protected void locateUriRoot( File f ) { String tUriBase = uriBase; if (tUriBase == null) { tUriBase = "/"; } try { if (f.exists()) { f = new File(f.getAbsolutePath()); while (true) { File g = new File(f, "WEB-INF"); if (g.exists() && g.isDirectory()) { uriRoot = f.getCanonicalPath(); uriBase = tUriBase; if (log.isInfoEnabled()) { log.info(Localizer.getMessage( "jspc.implicit.uriRoot", uriRoot)); } break; } if (f.exists() && f.isDirectory()) { tUriBase = "/" + f.getName() + "/" + tUriBase; } String fParent = f.getParent(); if (fParent == null) { break; } else { f = new File(fParent); } // If there is no acceptable candidate, uriRoot will // remain null to indicate to the CompilerContext to // use the current working/user dir. } if (uriRoot != null) { File froot = new File(uriRoot); uriRoot = froot.getCanonicalPath(); } } } catch (IOException ioe) { // since this is an optional default and a null value // for uriRoot has a non-error meaning, we can just // pass straight through } } /** * Resolves the relative or absolute pathname correctly * in both Ant and command-line situations. If Ant launched * us, we should use the basedir of the current project * to resolve relative paths. * * See Bugzilla 35571. * * @param s The file * @return The file resolved */ protected File resolveFile(final String s) { if(getProject() == null) { // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3 return FileUtils.getFileUtils().resolveFile(null, s); } else { return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s); } } private Reader openWebxmlReader(File file) throws IOException { FileInputStream fis = new FileInputStream(file); try { return webxmlEncoding != null ? new InputStreamReader(fis, webxmlEncoding) : new InputStreamReader(fis); } catch (IOException ex) { fis.close(); throw ex; } } private Writer openWebxmlWriter(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { return webxmlEncoding != null ? new OutputStreamWriter(fos, webxmlEncoding) : new OutputStreamWriter(fos); } catch (IOException ex) { fos.close(); throw ex; } } }
Remove now unused constants git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1712774 13f79535-47bb-0310-9956-ffa450edef68
java/org/apache/jasper/JspC.java
Remove now unused constants
<ide><path>ava/org/apache/jasper/JspC.java <ide> protected static final String SWITCH_DUMP_SMAP = "-dumpsmap"; <ide> protected static final String SWITCH_VALIDATE_TLD = "-validateTld"; <ide> protected static final String SWITCH_VALIDATE_XML = "-validateXml"; <del> protected static final String SWITCH_BLOCK_EXTERNAL = "-blockExternal"; <ide> protected static final String SWITCH_NO_BLOCK_EXTERNAL = "-no-blockExternal"; <del> protected static final String SWITCH_STRICT_QUOTE_ESCAPING = "-strictQuoteEscaping"; <ide> protected static final String SWITCH_NO_STRICT_QUOTE_ESCAPING = "-no-strictQuoteEscaping"; <ide> protected static final String SHOW_SUCCESS ="-s"; <ide> protected static final String LIST_ERRORS = "-l";
Java
apache-2.0
68b5a6edaddba1ba76098f6dae6b1848cb0c3737
0
hubrick/vertx-rest-client
/** * Copyright (C) 2015 Etaia AS ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hubrick.vertx.rest.impl; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.io.BaseEncoding; import com.hubrick.vertx.rest.MediaType; import com.hubrick.vertx.rest.RequestCacheOptions; import com.hubrick.vertx.rest.RestClientRequest; import com.hubrick.vertx.rest.RestClientResponse; import com.hubrick.vertx.rest.converter.HttpMessageConverter; import com.hubrick.vertx.rest.exception.HttpClientErrorException; import com.hubrick.vertx.rest.exception.HttpServerErrorException; import com.hubrick.vertx.rest.exception.RestClientException; import com.hubrick.vertx.rest.message.BufferedHttpOutputMessage; import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import org.apache.commons.collections4.keyvalue.MultiKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * The default implementation. * * @author Emir Dizdarevic * @since 1.0.0 */ public class DefaultRestClientRequest<T> implements RestClientRequest<T> { private static final Logger log = LoggerFactory.getLogger(DefaultRestClientRequest.class); private final Vertx vertx; private final DefaultRestClient restClient; private final HttpClient httpClient; private final HttpMethod method; private final String uri; private final BufferedHttpOutputMessage bufferedHttpOutputMessage = new BufferedHttpOutputMessage(); private final List<HttpMessageConverter> httpMessageConverters; private final HttpClientRequest httpClientRequest; private final MultiMap globalHeaders; private final Handler<RestClientResponse<T>> responseHandler; private Handler<Throwable> exceptionHandler; private RequestCacheOptions requestCacheOptions; private Long timeoutInMillis; // Status variables private boolean headersCopied = false; private boolean globalHeadersPopulated = false; private MultiKey cacheKey; public DefaultRestClientRequest(Vertx vertx, DefaultRestClient restClient, HttpClient httpClient, List<HttpMessageConverter> httpMessageConverters, HttpMethod method, String uri, Class<T> responseClass, Handler<RestClientResponse<T>> responseHandler, Long timeoutInMillis, RequestCacheOptions requestCacheOptions, MultiMap globalHeaders, @Nullable Handler<Throwable> exceptionHandler) { checkNotNull(vertx, "vertx must not be null"); checkNotNull(restClient, "restClient must not be null"); checkNotNull(httpClient, "httpClient must not be null"); checkNotNull(httpMessageConverters, "dataMappers must not be null"); checkArgument(!httpMessageConverters.isEmpty(), "dataMappers must not be empty"); checkNotNull(globalHeaders, "globalHeaders must not be null"); this.vertx = vertx; this.restClient = restClient; this.httpClient = httpClient; this.method = method; this.uri = uri; this.httpMessageConverters = httpMessageConverters; this.responseHandler = responseHandler; this.globalHeaders = globalHeaders; httpClientRequest = httpClient.request(method, uri, (HttpClientResponse httpClientResponse) -> { handleResponse(httpClientResponse, responseClass); }); this.requestCacheOptions = requestCacheOptions; this.timeoutInMillis = timeoutInMillis; if (exceptionHandler != null) { exceptionHandler(exceptionHandler); } } private void handleResponse(HttpClientResponse httpClientResponse, Class clazz) { final Integer firstStatusDigit = httpClientResponse.statusCode() / 100; if (firstStatusDigit == 4 || firstStatusDigit == 5) { httpClientResponse.bodyHandler((buffer) -> { httpClientResponse.exceptionHandler(null); if (log.isWarnEnabled()) { final String body = new String(buffer.getBytes(), Charsets.UTF_8); log.warn("Http request to {} FAILED. Return status: {}, message: {}, body: {}", new Object[]{uri, httpClientResponse.statusCode(), httpClientResponse.statusMessage(), body}); } RuntimeException exception = null; switch (firstStatusDigit) { case 4: exception = new HttpClientErrorException(httpClientResponse, httpMessageConverters, buffer.getBytes()); break; case 5: exception = new HttpServerErrorException(httpClientResponse, httpMessageConverters, buffer.getBytes()); break; } if (exceptionHandler != null) { exceptionHandler.handle(exception); } else { throw exception; } }); } else { httpClientResponse.bodyHandler((buffer) -> { httpClientResponse.exceptionHandler(null); if (log.isDebugEnabled()) { final String body = new String(buffer.getBytes(), Charsets.UTF_8); log.debug("Http request to {} SUCCESSFUL. Return status: {}, message: {}, body: {}", new Object[]{uri, httpClientResponse.statusCode(), httpClientResponse.statusMessage(), body}); } try { final RestClientResponse<T> restClientResponse = new DefaultRestClientResponse( httpMessageConverters, clazz, buffer.getBytes(), httpClientResponse, exceptionHandler ); handleResponse(restClientResponse); } catch (Throwable t) { log.error("Failed invoking rest handler", t); if (exceptionHandler != null) { exceptionHandler.handle(t); } else { throw t; } } }); } } private void handleResponse(RestClientResponse<T> restClientResponse) { if (HttpMethod.GET.equals(method) && requestCacheOptions != null) { boolean lastFiredRestClientRequest = false; final Set<DefaultRestClientRequest<T>> restClientRequestsToHandle = new LinkedHashSet<>(); for (DefaultRestClientRequest<T> entry : restClient.getRunningRequests().get(cacheKey)) { if(entry == this) { lastFiredRestClientRequest = true; } else if(entry.requestCacheOptions.getEvictBefore() || entry.requestCacheOptions.getEvictAllBefore()) { lastFiredRestClientRequest = false; break; } if(lastFiredRestClientRequest) { restClientRequestsToHandle.add(entry); } } if(lastFiredRestClientRequest) { cache(restClientResponse); } for (DefaultRestClientRequest<T> entry : restClientRequestsToHandle) { vertx.runOnContext(aVoid -> { log.debug("Handling FUTURE HIT for key {} and restClientRequest {}", cacheKey, entry); entry.responseHandler.handle(restClientResponse); }); } restClient.getRunningRequests().get(cacheKey).removeAll(restClientRequestsToHandle); } else { responseHandler.handle(restClientResponse); } } @Override public RestClientRequest setChunked(boolean chunked) { // Ignore this for now since chunked mode is not supported //httpClientRequest.setChunked(true); return this; } @Override public boolean isChunked() { return httpClientRequest.isChunked(); } @Override public MultiMap headers() { return bufferedHttpOutputMessage.getHeaders(); } @Override public RestClientRequest putHeader(String name, String value) { bufferedHttpOutputMessage.getHeaders().add(name, value); return this; } @Override public RestClientRequest putHeader(CharSequence name, CharSequence value) { bufferedHttpOutputMessage.getHeaders().add(name, value); return this; } @Override public RestClientRequest putHeader(String name, Iterable<String> values) { bufferedHttpOutputMessage.getHeaders().add(name, values); return this; } @Override public RestClientRequest putHeader(CharSequence name, Iterable<CharSequence> values) { bufferedHttpOutputMessage.getHeaders().add(name, values); return this; } @Override public RestClientRequest write(Object requestObject) { handleRequest(requestObject, false); return this; } @Override public RestClientRequest continueHandler(Handler<Void> handler) { httpClientRequest.continueHandler(handler); return this; } @Override public RestClientRequest sendHead() { populateAcceptHeaderIfNotPresent(); copyHeadersToHttpClientRequest(); httpClientRequest.sendHead(); return this; } @Override public void end(Object requestObject) { populateAcceptHeaderIfNotPresent(); handleRequest(requestObject, true); } @Override public void end() { populateAcceptHeaderIfNotPresent(); handleRequest(null, true); } @Override public RestClientRequest setTimeout(long timeoutMs) { checkArgument(timeoutMs >= 0, "timeoutMs must be greater or equal to 0"); this.timeoutInMillis = timeoutMs; return this; } @Override public void setContentType(MediaType contentType) { bufferedHttpOutputMessage.getHeaders().set(HttpHeaders.CONTENT_TYPE, contentType.toString()); } @Override public MediaType getContentType() { return MediaType.parseMediaType(bufferedHttpOutputMessage.getHeaders().get(HttpHeaders.CONTENT_TYPE)); } @Override public RestClientRequest<T> setRequestCache(RequestCacheOptions requestCacheOptions) { this.requestCacheOptions = requestCacheOptions; return this; } @Override public void setAcceptHeader(List<MediaType> mediaTypes) { bufferedHttpOutputMessage.getHeaders().set(HttpHeaders.ACCEPT, formatForAcceptHeader(mediaTypes)); } @Override public List<MediaType> getAcceptHeader() { final String acceptHeader = bufferedHttpOutputMessage.getHeaders().get(HttpHeaders.ACCEPT); if (Strings.isNullOrEmpty(acceptHeader)) { return Collections.emptyList(); } else { return FluentIterable.from(Splitter.on(",").split(acceptHeader)).toList().stream().map(MediaType::parseMediaType).collect(Collectors.toList()); } } @Override public void setBasicAuth(String userPassCombination) { bufferedHttpOutputMessage.getHeaders().set(HttpHeaders.AUTHORIZATION, "Basic " + BaseEncoding.base64().encode(userPassCombination.getBytes(Charsets.UTF_8))); } @Override public String getBasicAuth() { final String base64UserPassCombination = bufferedHttpOutputMessage.getHeaders().get(HttpHeaders.AUTHORIZATION); if (base64UserPassCombination != null && base64UserPassCombination.startsWith("Basic")) { return new String(BaseEncoding.base64().decode(base64UserPassCombination), Charsets.UTF_8).replaceFirst("Basic", "").trim(); } else { return null; } } @Override public RestClientRequest exceptionHandler(Handler<Throwable> exceptionHandler) { final Handler<Throwable> wrapped = (t) -> { log.warn("Error requesting {}: {}", uri, t.getMessage(), t); exceptionHandler.handle(t); }; this.exceptionHandler = wrapped; httpClientRequest.exceptionHandler(wrapped); return this; } private void handleRequest(Object requestObject, Boolean endRequest) { try { if (requestObject == null) { if (endRequest) { endRequest(); } } else { final Class<?> requestType = requestObject.getClass(); final MediaType requestContentType = getContentType(); for (HttpMessageConverter httpMessageConverter : httpMessageConverters) { if (httpMessageConverter.canWrite(requestType, requestContentType)) { httpMessageConverter.write(requestObject, requestContentType, bufferedHttpOutputMessage); if (endRequest) { endRequest(); } return; } } String message = "Could not write request: no suitable HttpMessageConverter found for request type [" + requestType.getName() + "]"; if (requestContentType != null) { message += " and content type [" + requestContentType + "]"; } throw new RestClientException(message); } } catch (Throwable t) { if (exceptionHandler != null) { exceptionHandler.handle(t); } else { log.error("No exceptionHandler found to handler exception.", t); } } } private void logRequest() { if (log.isDebugEnabled()) { final StringBuilder stringBuilder = new StringBuilder(256); for (String headerName : httpClientRequest.headers().names()) { for (String headerValue : httpClientRequest.headers().getAll(headerName)) { stringBuilder.append(headerName); stringBuilder.append(":"); stringBuilder.append(" "); stringBuilder.append(headerValue); stringBuilder.append("\r\n"); } } stringBuilder.append("\r\n"); stringBuilder.append(new String(bufferedHttpOutputMessage.getBody(), Charsets.UTF_8)); log.debug("HTTP Request: \n{}", stringBuilder.toString()); } } private MultiKey createCacheKey(String uri, MultiMap headers, byte[] body) { return new MultiKey( uri, headers.entries().stream().map(e -> e.getKey() + ": " + e.getValue()).sorted().collect(Collectors.toList()), Arrays.hashCode(body) ); } private void cache(RestClientResponse restClientResponse) { if (HttpMethod.GET.equals(method) && requestCacheOptions != null && requestCacheOptions.getCachedStatusCodes().contains(restClientResponse.statusCode())) { log.debug("Caching entry with key {}", cacheKey); cancelOutstandingEvictionTimer(cacheKey); restClient.getRequestCache().put(cacheKey, restClientResponse); createEvictionTimer(cacheKey, requestCacheOptions.getExpiresAfterWriteMillis()); } } private void endRequest() { copyHeadersToHttpClientRequest(); writeContentLength(); cacheKey = createCacheKey(uri, bufferedHttpOutputMessage.getHeaders(), bufferedHttpOutputMessage.getBody()); evictBefore(cacheKey); evictAllBefore(); if (HttpMethod.GET.equals(method) && requestCacheOptions != null) { try { if (requestCacheOptions.getEvictBefore() || requestCacheOptions.getEvictAllBefore()) { log.debug("Cache MISS. Proceeding with request for key {}", cacheKey); finishRequest(Optional.of(cacheKey)); } else { final RestClientResponse cachedRestClientResponse = restClient.getRequestCache().get(cacheKey); if (cachedRestClientResponse != null) { log.debug("Cache HIT. Retrieving entry from cache for key {}", cacheKey); resetExpires(cacheKey); responseHandler.handle(cachedRestClientResponse); } else if (restClient.getRunningRequests().containsKey(cacheKey) && !restClient.getRunningRequests().get(cacheKey).isEmpty()) { log.debug("Cache FUTURE HIT for key {}", cacheKey); restClient.getRunningRequests().put(cacheKey, this); } else { log.debug("Cache MISS. Proceeding with request for key {}", cacheKey); finishRequest(Optional.of(cacheKey)); } } } catch (Throwable t) { log.error("Failed invoking rest handler", t); if (exceptionHandler != null) { exceptionHandler.handle(t); } else { throw t; } } } else { finishRequest(Optional.empty()); } } private void evictBefore(MultiKey key) { if (requestCacheOptions != null && requestCacheOptions.getEvictBefore()) { log.debug("EVICTING entry from cache for key {}", key); cancelOutstandingEvictionTimer(key); restClient.getRequestCache().remove(key); } } private void resetExpires(MultiKey key) { if (requestCacheOptions.getExpiresAfterAccessMillis() > 0) { cancelOutstandingEvictionTimer(key); createEvictionTimer(key, requestCacheOptions.getExpiresAfterAccessMillis()); } } private void evictAllBefore() { if (requestCacheOptions != null && requestCacheOptions.getEvictAllBefore()) { log.debug("EVICTING all entries from cache"); restClient.getRequestCache().clear(); restClient.getEvictionTimersCache().clear(); } } private void cancelOutstandingEvictionTimer(MultiKey multiKey) { final Long outstandingTimer = restClient.getEvictionTimersCache().get(multiKey); if (outstandingTimer != null) { vertx.cancelTimer(outstandingTimer); restClient.getEvictionTimersCache().remove(multiKey); } } private void createEvictionTimer(MultiKey key, long ttl) { final long timerId = vertx.setTimer(ttl, timerIdRef -> { if (restClient.getEvictionTimersCache().containsValue(timerIdRef)) { log.debug("EVICTING entry from cache for key {}", key); restClient.getRequestCache().remove(key); restClient.getEvictionTimersCache().remove(key); } }); restClient.getEvictionTimersCache().put(key, timerId); } private void finishRequest(Optional<MultiKey> key) { if (timeoutInMillis > 0) { httpClientRequest.setTimeout(timeoutInMillis); } httpClientRequest.end(Buffer.buffer(bufferedHttpOutputMessage.getBody())); key.ifPresent(e -> restClient.getRunningRequests().put(e, this)); logRequest(); } private void writeContentLength() { if (!httpClientRequest.isChunked() && Strings.isNullOrEmpty(bufferedHttpOutputMessage.getHeaders().get(HttpHeaders.CONTENT_LENGTH))) { bufferedHttpOutputMessage.getHeaders().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(bufferedHttpOutputMessage.getBody().length)); } } private void copyHeadersToHttpClientRequest() { populateGlobalHeaders(); if (!headersCopied) { for (Map.Entry<String, String> header : bufferedHttpOutputMessage.getHeaders()) { httpClientRequest.putHeader(header.getKey(), header.getValue()); } headersCopied = true; } } private void populateGlobalHeaders() { if (!globalHeadersPopulated) { for (Map.Entry<String, String> header : globalHeaders) { httpClientRequest.putHeader(header.getKey(), header.getValue()); } globalHeadersPopulated = true; } } private void populateAcceptHeaderIfNotPresent() { final String acceptHeader = httpClientRequest.headers().get(HttpHeaders.ACCEPT); if (Strings.isNullOrEmpty(acceptHeader)) { httpClientRequest.headers().set( HttpHeaders.ACCEPT, formatForAcceptHeader( httpMessageConverters .stream() .map(HttpMessageConverter::getSupportedMediaTypes) .reduce(new LinkedList<>(), (a, b) -> { a.addAll(b); return a; } ) ) ); } } private String formatForAcceptHeader(List<MediaType> mediaTypes) { final List<MediaType> formattedMediaTypes = stripDownCharset(mediaTypes); MediaType.sortBySpecificity(formattedMediaTypes); return Joiner.on(",").join(formattedMediaTypes.stream().map(MediaType::toString).collect(Collectors.toList())); } private List<MediaType> stripDownCharset(List<MediaType> mediaTypes) { final List<MediaType> result = new ArrayList<MediaType>(mediaTypes.size()); for (MediaType mediaType : mediaTypes) { if (mediaType.getCharSet() != null) { mediaType = new MediaType(mediaType.getType(), mediaType.getSubtype()); } result.add(mediaType); } return result; } }
src/main/java/com/hubrick/vertx/rest/impl/DefaultRestClientRequest.java
/** * Copyright (C) 2015 Etaia AS ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hubrick.vertx.rest.impl; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.FluentIterable; import com.google.common.io.BaseEncoding; import com.hubrick.vertx.rest.MediaType; import com.hubrick.vertx.rest.RequestCacheOptions; import com.hubrick.vertx.rest.RestClientRequest; import com.hubrick.vertx.rest.RestClientResponse; import com.hubrick.vertx.rest.converter.HttpMessageConverter; import com.hubrick.vertx.rest.exception.HttpClientErrorException; import com.hubrick.vertx.rest.exception.HttpServerErrorException; import com.hubrick.vertx.rest.exception.RestClientException; import com.hubrick.vertx.rest.message.BufferedHttpOutputMessage; import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import org.apache.commons.collections4.keyvalue.MultiKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * The default implementation. * * @author Emir Dizdarevic * @since 1.0.0 */ public class DefaultRestClientRequest<T> implements RestClientRequest<T> { private static final Logger log = LoggerFactory.getLogger(DefaultRestClientRequest.class); private final Vertx vertx; private final DefaultRestClient restClient; private final HttpClient httpClient; private final HttpMethod method; private final String uri; private final BufferedHttpOutputMessage bufferedHttpOutputMessage = new BufferedHttpOutputMessage(); private final List<HttpMessageConverter> httpMessageConverters; private final HttpClientRequest httpClientRequest; private final MultiMap globalHeaders; private final Handler<RestClientResponse<T>> responseHandler; private Handler<Throwable> exceptionHandler; private RequestCacheOptions requestCacheOptions; private Long timeoutInMillis; // Status variables private boolean headersCopied = false; private boolean globalHeadersPopulated = false; public DefaultRestClientRequest(Vertx vertx, DefaultRestClient restClient, HttpClient httpClient, List<HttpMessageConverter> httpMessageConverters, HttpMethod method, String uri, Class<T> responseClass, Handler<RestClientResponse<T>> responseHandler, Long timeoutInMillis, RequestCacheOptions requestCacheOptions, MultiMap globalHeaders, @Nullable Handler<Throwable> exceptionHandler) { checkNotNull(vertx, "vertx must not be null"); checkNotNull(restClient, "restClient must not be null"); checkNotNull(httpClient, "httpClient must not be null"); checkNotNull(httpMessageConverters, "dataMappers must not be null"); checkArgument(!httpMessageConverters.isEmpty(), "dataMappers must not be empty"); checkNotNull(globalHeaders, "globalHeaders must not be null"); this.vertx = vertx; this.restClient = restClient; this.httpClient = httpClient; this.method = method; this.uri = uri; this.httpMessageConverters = httpMessageConverters; this.responseHandler = responseHandler; this.globalHeaders = globalHeaders; httpClientRequest = httpClient.request(method, uri, (HttpClientResponse httpClientResponse) -> { handleResponse(httpClientResponse, responseClass); }); this.requestCacheOptions = requestCacheOptions; this.timeoutInMillis = timeoutInMillis; if (exceptionHandler != null) { exceptionHandler(exceptionHandler); } } private void handleResponse(HttpClientResponse httpClientResponse, Class clazz) { final Integer firstStatusDigit = httpClientResponse.statusCode() / 100; if (firstStatusDigit == 4 || firstStatusDigit == 5) { httpClientResponse.bodyHandler((buffer) -> { httpClientResponse.exceptionHandler(null); if (log.isWarnEnabled()) { final String body = new String(buffer.getBytes(), Charsets.UTF_8); log.warn("Http request to {} FAILED. Return status: {}, message: {}, body: {}", new Object[]{uri, httpClientResponse.statusCode(), httpClientResponse.statusMessage(), body}); } RuntimeException exception = null; switch (firstStatusDigit) { case 4: exception = new HttpClientErrorException(httpClientResponse, httpMessageConverters, buffer.getBytes()); break; case 5: exception = new HttpServerErrorException(httpClientResponse, httpMessageConverters, buffer.getBytes()); break; } if (exceptionHandler != null) { exceptionHandler.handle(exception); } else { throw exception; } }); } else { httpClientResponse.bodyHandler((buffer) -> { httpClientResponse.exceptionHandler(null); if (log.isDebugEnabled()) { final String body = new String(buffer.getBytes(), Charsets.UTF_8); log.debug("Http request to {} SUCCESSFUL. Return status: {}, message: {}, body: {}", new Object[]{uri, httpClientResponse.statusCode(), httpClientResponse.statusMessage(), body}); } try { final RestClientResponse<T> restClientResponse = new DefaultRestClientResponse( httpMessageConverters, clazz, buffer.getBytes(), httpClientResponse, exceptionHandler ); handleResponse(restClientResponse); } catch (Throwable t) { log.error("Failed invoking rest handler", t); if (exceptionHandler != null) { exceptionHandler.handle(t); } else { throw t; } } }); } } private void handleResponse(RestClientResponse<T> restClientResponse) { if (HttpMethod.GET.equals(method) && requestCacheOptions != null) { final MultiKey key = createCacheKey(uri, bufferedHttpOutputMessage.getHeaders(), bufferedHttpOutputMessage.getBody()); boolean lastFiredRestClientRequest = false; final Set<DefaultRestClientRequest<T>> restClientRequestsToHandle = new LinkedHashSet<>(); for (DefaultRestClientRequest<T> entry : restClient.getRunningRequests().get(key)) { if(entry == this) { lastFiredRestClientRequest = true; } else if(entry.requestCacheOptions.getEvictBefore() || entry.requestCacheOptions.getEvictAllBefore()) { lastFiredRestClientRequest = false; break; } if(lastFiredRestClientRequest) { restClientRequestsToHandle.add(entry); } } if(lastFiredRestClientRequest) { cache(restClientResponse, uri, bufferedHttpOutputMessage.getHeaders(), bufferedHttpOutputMessage.getBody()); } for (DefaultRestClientRequest<T> entry : restClientRequestsToHandle) { vertx.runOnContext(aVoid -> { log.debug("Handling FUTURE HIT for key {} and restClientRequest {}", key, entry); entry.responseHandler.handle(restClientResponse); }); } restClient.getRunningRequests().get(key).removeAll(restClientRequestsToHandle); } else { responseHandler.handle(restClientResponse); } } @Override public RestClientRequest setChunked(boolean chunked) { // Ignore this for now since chunked mode is not supported //httpClientRequest.setChunked(true); return this; } @Override public boolean isChunked() { return httpClientRequest.isChunked(); } @Override public MultiMap headers() { return bufferedHttpOutputMessage.getHeaders(); } @Override public RestClientRequest putHeader(String name, String value) { bufferedHttpOutputMessage.getHeaders().add(name, value); return this; } @Override public RestClientRequest putHeader(CharSequence name, CharSequence value) { bufferedHttpOutputMessage.getHeaders().add(name, value); return this; } @Override public RestClientRequest putHeader(String name, Iterable<String> values) { bufferedHttpOutputMessage.getHeaders().add(name, values); return this; } @Override public RestClientRequest putHeader(CharSequence name, Iterable<CharSequence> values) { bufferedHttpOutputMessage.getHeaders().add(name, values); return this; } @Override public RestClientRequest write(Object requestObject) { handleRequest(requestObject, false); return this; } @Override public RestClientRequest continueHandler(Handler<Void> handler) { httpClientRequest.continueHandler(handler); return this; } @Override public RestClientRequest sendHead() { populateAcceptHeaderIfNotPresent(); copyHeadersToHttpClientRequest(); httpClientRequest.sendHead(); return this; } @Override public void end(Object requestObject) { populateAcceptHeaderIfNotPresent(); handleRequest(requestObject, true); } @Override public void end() { populateAcceptHeaderIfNotPresent(); handleRequest(null, true); } @Override public RestClientRequest setTimeout(long timeoutMs) { checkArgument(timeoutMs >= 0, "timeoutMs must be greater or equal to 0"); this.timeoutInMillis = timeoutMs; return this; } @Override public void setContentType(MediaType contentType) { bufferedHttpOutputMessage.getHeaders().set(HttpHeaders.CONTENT_TYPE, contentType.toString()); } @Override public MediaType getContentType() { return MediaType.parseMediaType(bufferedHttpOutputMessage.getHeaders().get(HttpHeaders.CONTENT_TYPE)); } @Override public RestClientRequest<T> setRequestCache(RequestCacheOptions requestCacheOptions) { this.requestCacheOptions = requestCacheOptions; return this; } @Override public void setAcceptHeader(List<MediaType> mediaTypes) { bufferedHttpOutputMessage.getHeaders().set(HttpHeaders.ACCEPT, formatForAcceptHeader(mediaTypes)); } @Override public List<MediaType> getAcceptHeader() { final String acceptHeader = bufferedHttpOutputMessage.getHeaders().get(HttpHeaders.ACCEPT); if (Strings.isNullOrEmpty(acceptHeader)) { return Collections.emptyList(); } else { return FluentIterable.from(Splitter.on(",").split(acceptHeader)).toList().stream().map(MediaType::parseMediaType).collect(Collectors.toList()); } } @Override public void setBasicAuth(String userPassCombination) { bufferedHttpOutputMessage.getHeaders().set(HttpHeaders.AUTHORIZATION, "Basic " + BaseEncoding.base64().encode(userPassCombination.getBytes(Charsets.UTF_8))); } @Override public String getBasicAuth() { final String base64UserPassCombination = bufferedHttpOutputMessage.getHeaders().get(HttpHeaders.AUTHORIZATION); if (base64UserPassCombination != null && base64UserPassCombination.startsWith("Basic")) { return new String(BaseEncoding.base64().decode(base64UserPassCombination), Charsets.UTF_8).replaceFirst("Basic", "").trim(); } else { return null; } } @Override public RestClientRequest exceptionHandler(Handler<Throwable> exceptionHandler) { final Handler<Throwable> wrapped = (t) -> { log.warn("Error requesting {}: {}", uri, t.getMessage(), t); exceptionHandler.handle(t); }; this.exceptionHandler = wrapped; httpClientRequest.exceptionHandler(wrapped); return this; } private void handleRequest(Object requestObject, Boolean endRequest) { try { if (requestObject == null) { if (endRequest) { endRequest(); } } else { final Class<?> requestType = requestObject.getClass(); final MediaType requestContentType = getContentType(); for (HttpMessageConverter httpMessageConverter : httpMessageConverters) { if (httpMessageConverter.canWrite(requestType, requestContentType)) { httpMessageConverter.write(requestObject, requestContentType, bufferedHttpOutputMessage); if (endRequest) { endRequest(); } return; } } String message = "Could not write request: no suitable HttpMessageConverter found for request type [" + requestType.getName() + "]"; if (requestContentType != null) { message += " and content type [" + requestContentType + "]"; } throw new RestClientException(message); } } catch (Throwable t) { if (exceptionHandler != null) { exceptionHandler.handle(t); } else { log.error("No exceptionHandler found to handler exception.", t); } } } private void logRequest() { if (log.isDebugEnabled()) { final StringBuilder stringBuilder = new StringBuilder(256); for (String headerName : httpClientRequest.headers().names()) { for (String headerValue : httpClientRequest.headers().getAll(headerName)) { stringBuilder.append(headerName); stringBuilder.append(":"); stringBuilder.append(" "); stringBuilder.append(headerValue); stringBuilder.append("\r\n"); } } stringBuilder.append("\r\n"); stringBuilder.append(new String(bufferedHttpOutputMessage.getBody(), Charsets.UTF_8)); log.debug("HTTP Request: \n{}", stringBuilder.toString()); } } private MultiKey createCacheKey(String uri, MultiMap headers, byte[] body) { return new MultiKey( uri, headers.entries().stream().map(e -> e.getKey() + ": " + e.getValue()).sorted().collect(Collectors.toList()), Arrays.hashCode(body) ); } private void cache(RestClientResponse restClientResponse, String uri, MultiMap headers, byte[] body) { final MultiKey key = createCacheKey(uri, headers, body); if (HttpMethod.GET.equals(method) && requestCacheOptions != null && requestCacheOptions.getCachedStatusCodes().contains(restClientResponse.statusCode())) { log.debug("Caching entry with key {}", key); cancelOutstandingEvictionTimer(key); restClient.getRequestCache().put(key, restClientResponse); createEvictionTimer(key, requestCacheOptions.getExpiresAfterWriteMillis()); } } private void endRequest() { copyHeadersToHttpClientRequest(); writeContentLength(); final MultiKey key = createCacheKey(uri, bufferedHttpOutputMessage.getHeaders(), bufferedHttpOutputMessage.getBody()); evictBefore(key); evictAllBefore(); if (HttpMethod.GET.equals(method) && requestCacheOptions != null) { try { if (requestCacheOptions.getEvictBefore() || requestCacheOptions.getEvictAllBefore()) { log.debug("Cache MISS. Proceeding with request for key {}", key); finishRequest(Optional.of(key)); } else { final RestClientResponse cachedRestClientResponse = restClient.getRequestCache().get(key); if (cachedRestClientResponse != null) { log.debug("Cache HIT. Retrieving entry from cache for key {}", key); resetExpires(key); responseHandler.handle(cachedRestClientResponse); } else if (restClient.getRunningRequests().containsKey(key) && !restClient.getRunningRequests().get(key).isEmpty()) { log.debug("Cache FUTURE HIT for key {}", key); restClient.getRunningRequests().put(key, this); } else { log.debug("Cache MISS. Proceeding with request for key {}", key); finishRequest(Optional.of(key)); } } } catch (Throwable t) { log.error("Failed invoking rest handler", t); if (exceptionHandler != null) { exceptionHandler.handle(t); } else { throw t; } } } else { finishRequest(Optional.empty()); } } private void evictBefore(MultiKey key) { if (requestCacheOptions != null && requestCacheOptions.getEvictBefore()) { log.debug("EVICTING entry from cache for key {}", key); cancelOutstandingEvictionTimer(key); restClient.getRequestCache().remove(key); } } private void resetExpires(MultiKey key) { if (requestCacheOptions.getExpiresAfterAccessMillis() > 0) { cancelOutstandingEvictionTimer(key); createEvictionTimer(key, requestCacheOptions.getExpiresAfterAccessMillis()); } } private void evictAllBefore() { if (requestCacheOptions != null && requestCacheOptions.getEvictAllBefore()) { log.debug("EVICTING all entries from cache"); restClient.getRequestCache().clear(); restClient.getEvictionTimersCache().clear(); } } private void cancelOutstandingEvictionTimer(MultiKey multiKey) { final Long outstandingTimer = restClient.getEvictionTimersCache().get(multiKey); if (outstandingTimer != null) { vertx.cancelTimer(outstandingTimer); restClient.getEvictionTimersCache().remove(multiKey); } } private void createEvictionTimer(MultiKey key, long ttl) { final long timerId = vertx.setTimer(ttl, timerIdRef -> { if (restClient.getEvictionTimersCache().containsValue(timerIdRef)) { log.debug("EVICTING entry from cache for key {}", key); restClient.getRequestCache().remove(key); restClient.getEvictionTimersCache().remove(key); } }); restClient.getEvictionTimersCache().put(key, timerId); } private void finishRequest(Optional<MultiKey> key) { if (timeoutInMillis > 0) { httpClientRequest.setTimeout(timeoutInMillis); } httpClientRequest.end(Buffer.buffer(bufferedHttpOutputMessage.getBody())); key.ifPresent(e -> restClient.getRunningRequests().put(e, this)); logRequest(); } private void writeContentLength() { if (!httpClientRequest.isChunked() && Strings.isNullOrEmpty(bufferedHttpOutputMessage.getHeaders().get(HttpHeaders.CONTENT_LENGTH))) { bufferedHttpOutputMessage.getHeaders().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(bufferedHttpOutputMessage.getBody().length)); } } private void copyHeadersToHttpClientRequest() { populateGlobalHeaders(); if (!headersCopied) { for (Map.Entry<String, String> header : bufferedHttpOutputMessage.getHeaders()) { httpClientRequest.putHeader(header.getKey(), header.getValue()); } headersCopied = true; } } private void populateGlobalHeaders() { if (!globalHeadersPopulated) { for (Map.Entry<String, String> header : globalHeaders) { httpClientRequest.putHeader(header.getKey(), header.getValue()); } globalHeadersPopulated = true; } } private void populateAcceptHeaderIfNotPresent() { final String acceptHeader = httpClientRequest.headers().get(HttpHeaders.ACCEPT); if (Strings.isNullOrEmpty(acceptHeader)) { httpClientRequest.headers().set( HttpHeaders.ACCEPT, formatForAcceptHeader( httpMessageConverters .stream() .map(HttpMessageConverter::getSupportedMediaTypes) .reduce(new LinkedList<>(), (a, b) -> { a.addAll(b); return a; } ) ) ); } } private String formatForAcceptHeader(List<MediaType> mediaTypes) { final List<MediaType> formattedMediaTypes = stripDownCharset(mediaTypes); MediaType.sortBySpecificity(formattedMediaTypes); return Joiner.on(",").join(formattedMediaTypes.stream().map(MediaType::toString).collect(Collectors.toList())); } private List<MediaType> stripDownCharset(List<MediaType> mediaTypes) { final List<MediaType> result = new ArrayList<MediaType>(mediaTypes.size()); for (MediaType mediaType : mediaTypes) { if (mediaType.getCharSet() != null) { mediaType = new MediaType(mediaType.getType(), mediaType.getSubtype()); } result.add(mediaType); } return result; } }
* Improved cache key calculation performance
src/main/java/com/hubrick/vertx/rest/impl/DefaultRestClientRequest.java
* Improved cache key calculation performance
<ide><path>rc/main/java/com/hubrick/vertx/rest/impl/DefaultRestClientRequest.java <ide> // Status variables <ide> private boolean headersCopied = false; <ide> private boolean globalHeadersPopulated = false; <add> private MultiKey cacheKey; <ide> <ide> public DefaultRestClientRequest(Vertx vertx, <ide> DefaultRestClient restClient, <ide> <ide> private void handleResponse(RestClientResponse<T> restClientResponse) { <ide> if (HttpMethod.GET.equals(method) && requestCacheOptions != null) { <del> final MultiKey key = createCacheKey(uri, bufferedHttpOutputMessage.getHeaders(), bufferedHttpOutputMessage.getBody()); <del> <ide> boolean lastFiredRestClientRequest = false; <ide> final Set<DefaultRestClientRequest<T>> restClientRequestsToHandle = new LinkedHashSet<>(); <del> for (DefaultRestClientRequest<T> entry : restClient.getRunningRequests().get(key)) { <add> for (DefaultRestClientRequest<T> entry : restClient.getRunningRequests().get(cacheKey)) { <ide> if(entry == this) { <ide> lastFiredRestClientRequest = true; <ide> } else if(entry.requestCacheOptions.getEvictBefore() || entry.requestCacheOptions.getEvictAllBefore()) { <ide> } <ide> <ide> if(lastFiredRestClientRequest) { <del> cache(restClientResponse, uri, bufferedHttpOutputMessage.getHeaders(), bufferedHttpOutputMessage.getBody()); <add> cache(restClientResponse); <ide> } <ide> <ide> for (DefaultRestClientRequest<T> entry : restClientRequestsToHandle) { <ide> vertx.runOnContext(aVoid -> { <del> log.debug("Handling FUTURE HIT for key {} and restClientRequest {}", key, entry); <add> log.debug("Handling FUTURE HIT for key {} and restClientRequest {}", cacheKey, entry); <ide> entry.responseHandler.handle(restClientResponse); <ide> }); <ide> } <del> restClient.getRunningRequests().get(key).removeAll(restClientRequestsToHandle); <add> restClient.getRunningRequests().get(cacheKey).removeAll(restClientRequestsToHandle); <ide> } else { <ide> responseHandler.handle(restClientResponse); <ide> } <ide> ); <ide> } <ide> <del> private void cache(RestClientResponse restClientResponse, String uri, MultiMap headers, byte[] body) { <del> final MultiKey key = createCacheKey(uri, headers, body); <del> <add> private void cache(RestClientResponse restClientResponse) { <ide> if (HttpMethod.GET.equals(method) && requestCacheOptions != null && requestCacheOptions.getCachedStatusCodes().contains(restClientResponse.statusCode())) { <del> log.debug("Caching entry with key {}", key); <del> <del> cancelOutstandingEvictionTimer(key); <del> restClient.getRequestCache().put(key, restClientResponse); <del> createEvictionTimer(key, requestCacheOptions.getExpiresAfterWriteMillis()); <add> log.debug("Caching entry with key {}", cacheKey); <add> <add> cancelOutstandingEvictionTimer(cacheKey); <add> restClient.getRequestCache().put(cacheKey, restClientResponse); <add> createEvictionTimer(cacheKey, requestCacheOptions.getExpiresAfterWriteMillis()); <ide> } <ide> } <ide> <ide> private void endRequest() { <ide> copyHeadersToHttpClientRequest(); <ide> writeContentLength(); <del> <del> final MultiKey key = createCacheKey(uri, bufferedHttpOutputMessage.getHeaders(), bufferedHttpOutputMessage.getBody()); <del> evictBefore(key); <add> cacheKey = createCacheKey(uri, bufferedHttpOutputMessage.getHeaders(), bufferedHttpOutputMessage.getBody()); <add> <add> evictBefore(cacheKey); <ide> evictAllBefore(); <ide> <ide> if (HttpMethod.GET.equals(method) && requestCacheOptions != null) { <ide> try { <ide> if (requestCacheOptions.getEvictBefore() || requestCacheOptions.getEvictAllBefore()) { <del> log.debug("Cache MISS. Proceeding with request for key {}", key); <del> finishRequest(Optional.of(key)); <add> log.debug("Cache MISS. Proceeding with request for key {}", cacheKey); <add> finishRequest(Optional.of(cacheKey)); <ide> } else { <del> final RestClientResponse cachedRestClientResponse = restClient.getRequestCache().get(key); <add> final RestClientResponse cachedRestClientResponse = restClient.getRequestCache().get(cacheKey); <ide> if (cachedRestClientResponse != null) { <del> log.debug("Cache HIT. Retrieving entry from cache for key {}", key); <del> resetExpires(key); <add> log.debug("Cache HIT. Retrieving entry from cache for key {}", cacheKey); <add> resetExpires(cacheKey); <ide> responseHandler.handle(cachedRestClientResponse); <del> } else if (restClient.getRunningRequests().containsKey(key) && !restClient.getRunningRequests().get(key).isEmpty()) { <del> log.debug("Cache FUTURE HIT for key {}", key); <del> restClient.getRunningRequests().put(key, this); <add> } else if (restClient.getRunningRequests().containsKey(cacheKey) && !restClient.getRunningRequests().get(cacheKey).isEmpty()) { <add> log.debug("Cache FUTURE HIT for key {}", cacheKey); <add> restClient.getRunningRequests().put(cacheKey, this); <ide> } else { <del> log.debug("Cache MISS. Proceeding with request for key {}", key); <del> finishRequest(Optional.of(key)); <add> log.debug("Cache MISS. Proceeding with request for key {}", cacheKey); <add> finishRequest(Optional.of(cacheKey)); <ide> } <ide> } <ide> } catch (Throwable t) {
JavaScript
mit
16de3c060be725b0c89f2b9ce4ae2c31a4020aaf
0
saguijs/sagui,saguijs/sagui
import { expect } from 'chai' import { join } from 'path' import { HotModuleReplacementPlugin } from 'webpack' import CleanWebpackPlugin from 'clean-webpack-plugin' import plugin from './base' const saguiPath = join(__dirname, '../../../../') const projectPath = join(saguiPath, 'spec/fixtures/simple-project') describe('configure webpack base', function () { it('should add the project\'s `src/` and `node_modules/` to root resolve', function () { const config = plugin.configure({ projectPath, saguiPath, buildTarget: 'dist' }) expect(config.resolve.root).to.eql([ join(projectPath, '/node_modules'), join(saguiPath, '/node_modules'), join(projectPath, '/src') ]) }) it('should have the CleanWebpackPlugin enabled always', function () { const config = plugin.configure({ projectPath, saguiPath, buildTarget: 'dist' }) const commons = config.plugins.filter((plugin) => plugin instanceof CleanWebpackPlugin) expect(commons.length).equal(1) const cleanWebpackPlugin = commons[0] expect(cleanWebpackPlugin.paths).to.eql(['dist']) expect(cleanWebpackPlugin.options.verbose).to.eql(false) expect(cleanWebpackPlugin.options.root).to.eql(projectPath) }) describe('targets', function () { it('should have the HotModuleReplacementPlugin enabled while developing', function () { const config = plugin.configure({ projectPath, saguiPath, buildTarget: 'development' }) const commons = config.plugins.filter((plugin) => plugin instanceof HotModuleReplacementPlugin) expect(commons.length).equal(1) }) }) })
src/webpack/plugins/base.spec.js
import { expect } from 'chai' import { join } from 'path' import { HotModuleReplacementPlugin } from 'webpack' import CleanWebpackPlugin from 'clean-webpack-plugin' import plugin from './base' const saguiPath = join(__dirname, '../../../../') const projectPath = join(saguiPath, 'spec/fixtures/simple-project') describe('configure webpack base', function () { it('should the project\'s `src/` and `node_modules/` in root resolve', function () { const config = plugin.configure({ projectPath, saguiPath, buildTarget: 'dist' }) expect(config.resolve.root).to.eql([ join(projectPath, '/node_modules'), join(saguiPath, '/node_modules'), join(projectPath, '/src') ]) }) it('should have the CleanWebpackPlugin enabled allways', function () { const config = plugin.configure({ projectPath, saguiPath, buildTarget: 'dist' }) const commons = config.plugins.filter((plugin) => plugin instanceof CleanWebpackPlugin) expect(commons.length).equal(1) const cleanWebpackPlugin = commons[0] expect(cleanWebpackPlugin.paths).to.eql(['dist']) expect(cleanWebpackPlugin.options.verbose).to.eql(false) expect(cleanWebpackPlugin.options.root).to.eql(projectPath) }) describe('targets', function () { it('should have the HotModuleReplacementPlugin enabled while developing', function () { const config = plugin.configure({ projectPath, saguiPath, buildTarget: 'development' }) const commons = config.plugins.filter((plugin) => plugin instanceof HotModuleReplacementPlugin) expect(commons.length).equal(1) }) }) })
Fix test description
src/webpack/plugins/base.spec.js
Fix test description
<ide><path>rc/webpack/plugins/base.spec.js <ide> const projectPath = join(saguiPath, 'spec/fixtures/simple-project') <ide> <ide> describe('configure webpack base', function () { <del> it('should the project\'s `src/` and `node_modules/` in root resolve', function () { <add> it('should add the project\'s `src/` and `node_modules/` to root resolve', function () { <ide> const config = plugin.configure({ projectPath, saguiPath, buildTarget: 'dist' }) <ide> <ide> expect(config.resolve.root).to.eql([ <ide> ]) <ide> }) <ide> <del> it('should have the CleanWebpackPlugin enabled allways', function () { <add> it('should have the CleanWebpackPlugin enabled always', function () { <ide> const config = plugin.configure({ projectPath, saguiPath, buildTarget: 'dist' }) <ide> <ide> const commons = config.plugins.filter((plugin) => plugin instanceof CleanWebpackPlugin)
Java
agpl-3.0
99b9708112007c8f9c5b7f815568780325021103
0
RishiGupta12/serial-communication-manager,RishiGupta12/serial-communication-manager,akuhtz/serial-communication-manager,akuhtz/serial-communication-manager,akuhtz/serial-communication-manager,RishiGupta12/serial-communication-manager,RishiGupta12/SerialPundit,akuhtz/serial-communication-manager,RishiGupta12/SerialPundit,RishiGupta12/SerialPundit,RishiGupta12/SerialPundit
package com.embeddedunveiled.serial; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.AfterClass; import org.junit.Test; import com.embeddedunveiled.serial.SerialComManager.BAUDRATE; import com.embeddedunveiled.serial.SerialComManager.DATABITS; import com.embeddedunveiled.serial.SerialComManager.FLOWCONTROL; import com.embeddedunveiled.serial.SerialComManager.PARITY; import com.embeddedunveiled.serial.SerialComManager.STOPBITS; /* * Tested with two FT232 devices with vid, pid, serial combination as : * 0x0403, 0x6001, A70362A3 and * 0x0403, 0x6001, A602RDCH respectively. */ public final class SerialPortConfigurationsTests { static SerialComManager scm; static int osType; static String PORT1; static String PORT2; static Long handle1; static Long handle2; @BeforeClass public static void startup() throws Exception { scm = new SerialComManager(); osType = scm.getOSType(); } @AfterClass public static void shutdown() throws Exception { } @Before public void openPort() throws Exception { if(osType == SerialComManager.OS_LINUX) { PORT1 = "/dev/ttyUSB0"; PORT2 = "/dev/ttyUSB1"; }else if(osType == SerialComManager.OS_WINDOWS) { PORT1 = "COM51"; PORT2 = "COM52"; }else if(osType == SerialComManager.OS_MAC_OS_X) { PORT1 = "/dev/cu.usbserial-A70362A3"; PORT2 = "/dev/cu.usbserial-A602RDCH"; }else if(osType == SerialComManager.OS_SOLARIS) { PORT1 = null; PORT2 = null; }else{ } handle1 = scm.openComPort("/dev/pts/1", true, true, true); handle2 = scm.openComPort("/dev/pts/3", true, true, true); } @After public void validataDataAndclosePort() throws Exception { assertTrue(scm.writeBytes(handle1, "testing".getBytes(), 0)); try { Thread.sleep(500); } catch (InterruptedException e) { } String dataRead = scm.readString(handle2); assertNotNull(dataRead); assertEquals(dataRead, "testing"); scm.closeComPort(handle1); scm.closeComPort(handle2); } /* No flow control, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* No flow control, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* No flow control, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* No flow control, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* Hardware flow control, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Hardware flow control, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Hardware flow control, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Hardware flow control, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Software flow control, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* Software flow control, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* Software flow control,, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* Software flow control, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* No flow control, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* No flow control, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* No flow control, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* No flow control, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000E() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* Hardware flow control, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Hardware flow control, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Hardware flow control, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Hardware flow control, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000HE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Software flow control, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* Software flow control, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* Software flow control,, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* Software flow control, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000SE() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } }
com.embeddedunveiled.serial/junit-tests/com/embeddedunveiled/serial/SerialPortConfigurationsTests.java
package com.embeddedunveiled.serial; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.AfterClass; import org.junit.Test; import com.embeddedunveiled.serial.SerialComManager.BAUDRATE; import com.embeddedunveiled.serial.SerialComManager.DATABITS; import com.embeddedunveiled.serial.SerialComManager.FLOWCONTROL; import com.embeddedunveiled.serial.SerialComManager.PARITY; import com.embeddedunveiled.serial.SerialComManager.STOPBITS; /* * Tested with two FT232 devices with vid, pid, serial combination as : * 0x0403, 0x6001, A70362A3 and * 0x0403, 0x6001, A602RDCH respectively. */ public final class SerialPortConfigurationsTests { static SerialComManager scm; static int osType; static String PORT1; static String PORT2; static Long handle1; static Long handle2; @BeforeClass public static void startup() throws Exception { scm = new SerialComManager(); osType = scm.getOSType(); } @AfterClass public static void shutdown() throws Exception { } @Before public void openPort() throws Exception { if(osType == SerialComManager.OS_LINUX) { PORT1 = "/dev/ttyUSB0"; PORT2 = "/dev/ttyUSB1"; }else if(osType == SerialComManager.OS_WINDOWS) { PORT1 = "COM51"; PORT2 = "COM52"; }else if(osType == SerialComManager.OS_MAC_OS_X) { PORT1 = "/dev/cu.usbserial-A70362A3"; PORT2 = "/dev/cu.usbserial-A602RDCH"; }else if(osType == SerialComManager.OS_SOLARIS) { PORT1 = null; PORT2 = null; }else{ } handle1 = scm.openComPort("/dev/pts/1", true, true, true); handle2 = scm.openComPort("/dev/pts/3", true, true, true); } @After public void validataDataAndclosePort() throws Exception { assertTrue(scm.writeBytes(handle1, "testing".getBytes(), 0)); try { Thread.sleep(500); } catch (InterruptedException e) { } String dataRead = scm.readString(handle2); assertNotNull(dataRead); assertEquals(dataRead, "testing"); scm.closeComPort(handle1); scm.closeComPort(handle2); } /* No flow control, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* No flow control, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* No flow control, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* No flow control, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); } /* Hardware flow control, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Hardware flow control, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Hardware flow control, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Hardware flow control, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000H() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Software flow control,, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Software flow control,, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Software flow control,, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Software flow control,, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); } /* Software flow control,, 8N1 - with different baud rates */ @Test(timeout=100) public void test8N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test8N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* Software flow control,, 5N1 - with different baud rates */ @Test(timeout=100) public void test5N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test5N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* Software flow control,, 6N1 - with different baud rates */ @Test(timeout=100) public void test6N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test6N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } /* Software flow control,, 7N1 - with different baud rates */ @Test(timeout=100) public void test7N10S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N175S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1110S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1134S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1150S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1300S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N19600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N114400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N119200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N128800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N138400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N156000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N157600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1115200S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1128000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1153600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1230400S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1256000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1460800S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1576000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N1921600S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11152000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N11500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N12500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N13500000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } @Test(timeout=100) public void test7N14000000S() throws SerialComException { scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); } }
Junit - even parity, different flow control,different baud rates, 5,6,7,8 data, 1 stop
com.embeddedunveiled.serial/junit-tests/com/embeddedunveiled/serial/SerialPortConfigurationsTests.java
Junit - even parity, different flow control,different baud rates, 5,6,7,8 data, 1 stop
<ide><path>om.embeddedunveiled.serial/junit-tests/com/embeddedunveiled/serial/SerialPortConfigurationsTests.java <ide> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <ide> } <ide> <del> /* Software flow control,, 8N1 - with different baud rates */ <add> /* Software flow control, 8N1 - with different baud rates */ <ide> <ide> @Test(timeout=100) <ide> public void test8N10S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N150S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test8N175S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1110S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1134S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test8N1150S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1300S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test8N1600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N11200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N11800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N12400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N14800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N19600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N114400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N119200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <del> } <del> <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <ide> <ide> @Test(timeout=100) <ide> public void test8N128800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N138400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N156000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N157600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1115200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1128000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1153600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1230400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1256000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1460800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1576000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N1921600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N11000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N11152000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N11500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N12000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N12500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N13000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N13500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test8N14000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <del> } <del> <del> /* Software flow control,, 5N1 - with different baud rates */ <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> /* Software flow control, 5N1 - with different baud rates */ <ide> <ide> @Test(timeout=100) <ide> public void test5N10S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N150S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test5N175S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1110S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1134S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test5N1150S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1300S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test5N1600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N11200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N11800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N12400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N14800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N19600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N114400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N119200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> <ide> @Test(timeout=100) <ide> public void test5N128800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N138400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N156000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N157600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1115200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1128000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1153600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1230400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1256000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1460800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1576000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N1921600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N11000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N11152000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N11500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N12000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N12500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N13000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N13500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test5N14000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> /* Software flow control,, 6N1 - with different baud rates */ <del> <ide> <ide> @Test(timeout=100) <ide> public void test6N10S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N150S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test6N175S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1110S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1134S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test6N1150S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1300S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test6N1600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N11200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N11800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N12400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N14800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N19600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N114400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N119200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> <ide> @Test(timeout=100) <ide> public void test6N128800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N138400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N156000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N157600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1115200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1128000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1153600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1230400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1256000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1460800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1576000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N1921600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N11000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N11152000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N11500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N12000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N12500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N13000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N13500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test6N14000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <del> } <del> <del> /* Software flow control,, 7N1 - with different baud rates */ <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> /* Software flow control, 7N1 - with different baud rates */ <ide> <ide> @Test(timeout=100) <ide> public void test7N10S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N150S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test7N175S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1110S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1134S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test7N1150S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1300S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> @Test(timeout=100) <ide> public void test7N1600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N11200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N11800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N12400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N14800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N19600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N114400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N119200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <del> } <del> <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <ide> <ide> @Test(timeout=100) <ide> public void test7N128800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N138400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N156000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N157600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1115200S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1128000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1153600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1230400S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1256000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1460800S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1576000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N1921600S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N11000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N11152000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N11500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N12000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N12500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N13000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N13500000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> @Test(timeout=100) <ide> public void test7N14000000S() throws SerialComException { <ide> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <del> } <del> <del> /* Software flow control,, 8N1 - with different baud rates */ <del> <del> @Test(timeout=100) <del> public void test8N10S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N150S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test8N175S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1110S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1134S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test8N1150S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1300S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test8N1600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N11200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N11800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N12400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N14800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N19600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N114400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N119200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> <del> @Test(timeout=100) <del> public void test8N128800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N138400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N156000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N157600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1115200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1128000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1153600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1230400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1256000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1460800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1576000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N1921600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N11000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N11152000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N11500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N12000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N12500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N13000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N13500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test8N14000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> /* Software flow control,, 5N1 - with different baud rates */ <del> <del> @Test(timeout=100) <del> public void test5N10S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N150S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test5N175S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1110S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1134S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test5N1150S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1300S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test5N1600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N11200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N11800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N12400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N14800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N19600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N114400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N119200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> <del> @Test(timeout=100) <del> public void test5N128800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N138400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N156000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N157600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1115200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1128000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1153600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1230400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1256000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1460800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1576000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N1921600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N11000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N11152000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N11500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N12000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N12500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N13000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N13500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test5N14000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> /* No flow control, 8N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test8N10E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N150E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test8N175E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1110E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1134E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test8N1150E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1300E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test8N1600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N12400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N14800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N19600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N114400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N119200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> <add> @Test(timeout=100) <add> public void test8N128800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N138400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N156000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N157600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1115200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1128000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1153600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1230400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1256000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1460800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1576000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1921600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11152000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N12000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N12500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N13000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N13500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N14000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> /* No flow control, 5N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test5N10E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N150E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test5N175E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1110E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1134E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test5N1150E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1300E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test5N1600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N12400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N14800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N19600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N114400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N119200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> <add> @Test(timeout=100) <add> public void test5N128800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N138400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N156000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N157600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1115200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1128000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1153600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1230400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1256000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1460800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1576000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1921600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11152000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N12000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N12500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N13000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N13500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N14000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> /* No flow control, 6N1 - with different baud rates */ <add> <add> <add> @Test(timeout=100) <add> public void test6N10E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N150E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test6N175E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1110E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1134E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test6N1150E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1300E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test6N1600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N12400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N14800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N19600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N114400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N119200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> <add> @Test(timeout=100) <add> public void test6N128800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N138400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N156000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N157600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1115200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1128000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1153600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1230400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1256000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1460800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1576000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1921600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11152000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N12000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N12500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N13000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N13500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N14000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> /* No flow control, 7N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test7N10E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N150E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test7N175E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1110E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1134E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test7N1150E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1300E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test7N1600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N12400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N14800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N19600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N114400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N119200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> <add> @Test(timeout=100) <add> public void test7N128800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N138400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N156000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N157600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1115200E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1128000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1153600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1230400E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1256000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1460800E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1576000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1921600E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11152000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N12000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N12500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N13000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N13500000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N14000000E() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.NONE, 'x', 'x', false, false); <add> } <add> <add> /* Hardware flow control, 8N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test8N10HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N150HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test8N175HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1110HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1134HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test8N1150HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1300HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test8N1600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N12400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N14800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N19600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N114400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N119200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> <add> @Test(timeout=100) <add> public void test8N128800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N138400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N156000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N157600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1115200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1128000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1153600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1230400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1256000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1460800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1576000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1921600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11152000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N12000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N12500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N13000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N13500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N14000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> /* Hardware flow control, 5N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test5N10HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N150HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test5N175HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1110HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1134HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test5N1150HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1300HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test5N1600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N12400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N14800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N19600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N114400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N119200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N128800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N138400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N156000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N157600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1115200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1128000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1153600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1230400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1256000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1460800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1576000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1921600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11152000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N12000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N12500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N13000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N13500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N14000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> /* Hardware flow control, 6N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test6N10HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N150HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test6N175HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1110HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1134HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test6N1150HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1300HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test6N1600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N12400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N14800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N19600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N114400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N119200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> <add> @Test(timeout=100) <add> public void test6N128800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N138400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N156000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N157600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1115200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1128000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1153600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1230400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1256000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1460800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1576000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1921600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11152000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N12000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N12500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N13000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N13500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N14000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> /* Hardware flow control, 7N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test7N10HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N150HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test7N175HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1110HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1134HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test7N1150HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1300HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test7N1600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N12400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N14800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N19600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N114400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N119200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> <add> @Test(timeout=100) <add> public void test7N128800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N138400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N156000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N157600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1115200HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1128000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1153600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1230400HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1256000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1460800HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1576000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1921600HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11152000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N12000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N12500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N13000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N13500000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N14000000HE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.HARDWARE, 'x', 'x', false, false); <add> } <add> <add> /* Software flow control, 8N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test8N10SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N150SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test8N175SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1110SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1134SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test8N1150SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1300SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test8N1600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N12400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N14800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N19600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N114400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N119200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N128800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N138400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N156000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N157600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1115200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1128000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1153600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1230400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1256000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1460800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1576000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N1921600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11152000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N11500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N12000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N12500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N13000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N13500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test8N14000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_8, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> /* Software flow control, 5N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test5N10SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N150SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test5N175SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1110SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1134SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test5N1150SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1300SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test5N1600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N12400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N14800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N19600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N114400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N119200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> <add> @Test(timeout=100) <add> public void test5N128800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N138400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N156000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N157600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1115200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1128000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1153600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1230400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1256000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1460800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1576000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N1921600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11152000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N11500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N12000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N12500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N13000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N13500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test5N14000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_5, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <ide> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <ide> } <ide> <ide> /* Software flow control,, 6N1 - with different baud rates */ <ide> <del> <del> @Test(timeout=100) <del> public void test6N10S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N150S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test6N175S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1110S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1134S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test6N1150S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1300S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test6N1600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N11200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N11800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N12400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N14800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N19600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N114400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N119200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> <del> @Test(timeout=100) <del> public void test6N128800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N138400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N156000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N157600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1115200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1128000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1153600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1230400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1256000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1460800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1576000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N1921600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N11000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N11152000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N11500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N12000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N12500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N13000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N13500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test6N14000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> /* Software flow control,, 7N1 - with different baud rates */ <del> <del> @Test(timeout=100) <del> public void test7N10S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B0, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N150S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B50, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test7N175S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B75, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1110S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B110, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1134S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B134, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test7N1150S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B150, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1300S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B300, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> @Test(timeout=100) <del> public void test7N1600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N11200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N11800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N12400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N14800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N19600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B9600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N114400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B14400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N119200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B19200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> <del> @Test(timeout=100) <del> public void test7N128800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B28800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N138400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B38400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N156000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B56000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N157600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B57600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1115200S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B115200, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1128000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B128000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1153600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B153600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1230400S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B230400, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1256000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B256000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1460800S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B460800, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1576000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B576000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N1921600S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B921600, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N11000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N11152000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1152000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N11500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B1500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N12000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N12500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B2500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N13000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N13500000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B3500000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <del> <del> @Test(timeout=100) <del> public void test7N14000000S() throws SerialComException { <del> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_NONE, BAUDRATE.B4000000, 0); <del> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <del> } <add> @Test(timeout=100) <add> public void test6N10SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N150SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test6N175SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1110SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1134SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test6N1150SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1300SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test6N1600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N12400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N14800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N19600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N114400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N119200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> <add> @Test(timeout=100) <add> public void test6N128800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N138400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N156000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N157600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1115200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1128000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1153600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1230400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1256000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1460800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1576000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N1921600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11152000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N11500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N12000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N12500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N13000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N13500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test6N14000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_6, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> /* Software flow control, 7N1 - with different baud rates */ <add> <add> @Test(timeout=100) <add> public void test7N10SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B0, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N150SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B50, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test7N175SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B75, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1110SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B110, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1134SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B134, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test7N1150SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B150, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1300SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B300, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> @Test(timeout=100) <add> public void test7N1600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N12400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N14800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N19600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B9600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N114400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B14400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N119200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B19200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N128800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B28800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N138400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B38400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N156000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B56000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N157600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B57600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1115200SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B115200, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1128000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B128000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1153600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B153600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1230400SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B230400, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1256000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B256000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1460800SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B460800, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1576000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B576000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N1921600SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B921600, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11152000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1152000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N11500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B1500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N12000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N12500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B2500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N13000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N13500000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B3500000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <add> @Test(timeout=100) <add> public void test7N14000000SE() throws SerialComException { <add> scm.configureComPortData(handle1, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle1, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> scm.configureComPortData(handle2, DATABITS.DB_7, STOPBITS.SB_1, PARITY.P_EVEN, BAUDRATE.B4000000, 0); <add> scm.configureComPortControl(handle2, FLOWCONTROL.SOFTWARE, 'x', 'x', false, false); <add> } <add> <ide> }
Java
apache-2.0
b170f51ffeb872f27cd4c1da8683e2133c01c142
0
loskutov/intellij-scala,loskutov/intellij-scala,triplequote/intellij-scala,jeantil/intellij-scala,katejim/intellij-scala,jastice/intellij-scala,advancedxy/intellij-scala,igrocki/intellij-scala,ghik/intellij-scala,whorbowicz/intellij-scala,whorbowicz/intellij-scala,katejim/intellij-scala,Im-dex/intellij-scala,jastice/intellij-scala,double-y/translation-idea-plugin,JetBrains/intellij-scala,ilinum/intellij-scala,advancedxy/intellij-scala,ghik/intellij-scala,whorbowicz/intellij-scala,jeantil/intellij-scala,loskutov/intellij-scala,Im-dex/intellij-scala,jastice/intellij-scala,double-y/translation-idea-plugin,ilinum/intellij-scala,katejim/intellij-scala,ilinum/intellij-scala,igrocki/intellij-scala,ghik/intellij-scala,jeantil/intellij-scala,triplequote/intellij-scala,jastice/intellij-scala,double-y/translation-idea-plugin,JetBrains/intellij-scala,advancedxy/intellij-scala,igrocki/intellij-scala,Im-dex/intellij-scala,triplequote/intellij-scala
/* * Copyright 2000-2008 JetBrains s.r.o. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.scala.lang.lexer; import com.intellij.lexer.Lexer; import com.intellij.lexer.LexerPosition; import com.intellij.lexer.LexerState; import com.intellij.lexer.XmlLexer; import com.intellij.psi.tree.IElementType; import static com.intellij.psi.xml.XmlTokenType.*; import com.intellij.util.containers.Stack; import com.intellij.util.text.CharArrayCharSequence; import gnu.trove.TIntStack; import org.jetbrains.annotations.Nullable; import static org.jetbrains.plugins.scala.lang.lexer.ScalaLexer.TAG_STATE.NONEMPTY; import static org.jetbrains.plugins.scala.lang.lexer.ScalaLexer.TAG_STATE.UNDEFINED; import static org.jetbrains.plugins.scala.lang.lexer.ScalaPlainLexer.SCALA_CORE_MASK; import static org.jetbrains.plugins.scala.lang.lexer.ScalaPlainLexer.SCALA_CORE_SHIFT; import static org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypesEx.*; import org.jetbrains.plugins.scala.lang.lexer.core._ScalaCoreLexer; /** * @author ilyas */ public class ScalaLexer implements Lexer { protected final Lexer myScalaPlainLexer = new ScalaPlainLexer(); private final Lexer myXmlLexer = new XmlLexer(); protected Lexer myCurrentLexer; protected static final int MASK = 0x3F; protected static final int XML_SHIFT = 6; protected TIntStack myBraceStack = new TIntStack(); protected Stack<Stack<MyOpenXmlTag>> myLayeredTagStack = new Stack<Stack<MyOpenXmlTag>>(); protected int myBufferEnd; protected int myBufferStart; protected CharSequence myBuffer; protected int myXmlState; private int myTokenStart; private int myTokenEnd; protected IElementType myTokenType; public final String XML_BEGIN_PATTERN = "<\\w"; public final int SCALA_NEW_LINE_ALLOWED_STATE = (_ScalaCoreLexer.NEW_LINE_ALLOWED & (SCALA_CORE_MASK >> SCALA_CORE_SHIFT)) << SCALA_CORE_SHIFT; public ScalaLexer() { myCurrentLexer = myScalaPlainLexer; } @Deprecated public void start(char[] buffer) { start(buffer, 0, buffer.length); } @Deprecated public void start(char[] buffer, int startOffset, int endOffset) { start(buffer, startOffset, endOffset, 0); } @Deprecated public void start(char[] buffer, int startOffset, int endOffset, int initialState) { start(new CharArrayCharSequence(buffer), startOffset, endOffset, initialState); } public void start(CharSequence buffer, int startOffset, int endOffset, int initialState) { myCurrentLexer = myScalaPlainLexer; myCurrentLexer.start(buffer, startOffset, endOffset, initialState & MASK); myBraceStack.clear(); myLayeredTagStack.clear(); myXmlState = (initialState >> XML_SHIFT) & MASK; myBuffer = buffer; myBufferStart = startOffset; myBufferEnd = endOffset; myTokenType = null; } public int getState() { locateToken(); return myTokenStart == 0 ? 0 : 239; } @Nullable public IElementType getTokenType() { locateToken(); return myTokenType; } private void locateToken() { if (myTokenType == null) { IElementType type = myCurrentLexer.getTokenType(); int start = myCurrentLexer.getTokenStart(); String tokenText = myCurrentLexer.getBufferSequence().subSequence(start, myCurrentLexer.getTokenEnd()).toString(); if (type == SCALA_XML_CONTENT_START) { myCurrentLexer = myXmlLexer; myCurrentLexer.start(getBufferSequence(), start, myBufferEnd, myXmlState); myLayeredTagStack.push(new Stack<MyOpenXmlTag>()); myLayeredTagStack.peek().push(new MyOpenXmlTag()); myTokenType = myCurrentLexer.getTokenType(); locateTextRange(); } else if ((type == XML_ATTRIBUTE_VALUE_TOKEN || type == XML_DATA_CHARACTERS) && tokenText.startsWith("{") && !tokenText.startsWith("{{")) { myXmlState = myCurrentLexer.getState(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start, myBufferEnd, 0); locateTextRange(); myBraceStack.push(1); myTokenType = SCALA_IN_XML_INJECTION_START; } else if (type == ScalaTokenTypes.tRBRACE && myBraceStack.size() > 0) { int currentLayer = myBraceStack.pop(); if (currentLayer == 1) { locateTextRange(); (myCurrentLexer = myXmlLexer).start(getBufferSequence(), start + 1, myBufferEnd, myXmlState); myTokenType = SCALA_IN_XML_INJECTION_END; } else { myBraceStack.push(--currentLayer); } } else if (type == ScalaTokenTypes.tLBRACE && myBraceStack.size() > 0) { int currentLayer = myBraceStack.pop(); myBraceStack.push(++currentLayer); } else if ((XML_START_TAG_START == type || XML_COMMENT_START == type || XML_CDATA_START == type || XML_PI_START == type)&& !myLayeredTagStack.isEmpty()) { myLayeredTagStack.peek().push(new MyOpenXmlTag()); } else if (XML_EMPTY_ELEMENT_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == UNDEFINED) { myLayeredTagStack.peek().pop(); if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 2, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_EMPTY_ELEMENT_END; } } else if (XML_TAG_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty()) { MyOpenXmlTag tag = myLayeredTagStack.peek().peek(); if (tag.state == UNDEFINED) { tag.state = NONEMPTY; } else if (tag.state == NONEMPTY) { myLayeredTagStack.peek().pop(); } if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 1, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_TAG_END; } } else if (XML_PI_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == UNDEFINED) { myLayeredTagStack.peek().pop(); if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 2, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_PI_END; } } else if (XML_COMMENT_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == UNDEFINED) { myLayeredTagStack.peek().pop(); if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 3, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_COMMENT_END; } } else if (XML_CDATA_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == UNDEFINED) { myLayeredTagStack.peek().pop(); if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 3, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_CDATA_END; } } else if (type == XML_DATA_CHARACTERS && tokenText.indexOf('{')!=-1) { int scalaToken = tokenText.indexOf('{'); while (scalaToken != -1 && scalaToken+1 < tokenText.length() && tokenText.charAt(scalaToken+1)=='{') scalaToken = tokenText.indexOf('{', scalaToken + 2); if (scalaToken != -1) { myTokenType = XML_DATA_CHARACTERS; myTokenStart = myCurrentLexer.getTokenStart(); myTokenEnd = myTokenStart + scalaToken; myCurrentLexer.start(getBufferSequence(),myTokenEnd,myBufferEnd,myCurrentLexer.getState()); } } else if ((type == XML_REAL_WHITE_SPACE || type == XML_WHITE_SPACE || type == TAG_WHITE_SPACE) && tokenText.matches("\\s*\n(\n|\\s)*")) { type = ScalaTokenTypes.tWHITE_SPACE_IN_LINE; } if (myTokenType == null) { myTokenType = type; if (myTokenType == null) return; locateTextRange(); } myCurrentLexer.advance(); } } private void locateTextRange() { myTokenStart = myCurrentLexer.getTokenStart(); myTokenEnd = myCurrentLexer.getTokenEnd(); } private boolean checkNotNextXmlBegin(Lexer lexer) { String text = lexer.getBufferSequence().toString(); int beginIndex = lexer.getTokenEnd(); if (beginIndex < text.length()) { text = text.substring(beginIndex).trim(); if (text.length() > 2) { text = text.substring(0, 2); } return !text.matches(XML_BEGIN_PATTERN); } return true; } public int getTokenStart() { locateToken(); return myTokenStart; } public int getTokenEnd() { locateToken(); return myTokenEnd; } public void advance() { myTokenType = null; } public LexerPosition getCurrentPosition() { return new MyPosition( myTokenStart, myTokenEnd, new MyState( myXmlState, 0, myBraceStack, myCurrentLexer, myLayeredTagStack)); } public void restore(LexerPosition position) { MyPosition pos = (MyPosition) position; myBraceStack = pos.state.braceStack; myCurrentLexer = pos.state.currentLexer; myTokenStart = pos.getOffset(); myTokenEnd = pos.end; myLayeredTagStack = pos.state.tagStack; myCurrentLexer.start(myCurrentLexer.getBufferSequence(), myTokenStart, myBufferEnd, myCurrentLexer instanceof XmlLexer ? pos.state.xmlState : 0); } @Deprecated public char[] getBuffer() { return myCurrentLexer.getBuffer(); } public CharSequence getBufferSequence() { return myBuffer; } public int getBufferEnd() { return myBufferEnd; } private static class MyState implements LexerState { public TIntStack braceStack; public Stack<Stack<MyOpenXmlTag>> tagStack; public Lexer currentLexer; public int xmlState; public int scalaState; public MyState(final int xmlState, final int scalaState, TIntStack braceStack, Lexer lexer, Stack<Stack<MyOpenXmlTag>> tagStack) { this.braceStack = braceStack; this.tagStack = tagStack; this.currentLexer = lexer; this.xmlState = xmlState; this.scalaState = scalaState; } public short intern() { return 0; } } private static class MyPosition implements LexerPosition { public int start; public int end; public MyState state; public MyPosition(final int start, final int end, final MyState state) { this.start = start; this.end = end; this.state = state; } public int getOffset() { return start; } public int getState() { return state.currentLexer.getState(); } } protected static enum TAG_STATE { UNDEFINED, EMPTY, NONEMPTY } private static class MyOpenXmlTag { public TAG_STATE state = UNDEFINED; } }
scala_core/src/org/jetbrains/plugins/scala/lang/lexer/ScalaLexer.java
/* * Copyright 2000-2008 JetBrains s.r.o. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.scala.lang.lexer; import com.intellij.lexer.Lexer; import com.intellij.lexer.LexerPosition; import com.intellij.lexer.LexerState; import com.intellij.lexer.XmlLexer; import com.intellij.psi.tree.IElementType; import static com.intellij.psi.xml.XmlTokenType.*; import com.intellij.util.containers.Stack; import com.intellij.util.text.CharArrayCharSequence; import gnu.trove.TIntStack; import org.jetbrains.annotations.Nullable; import static org.jetbrains.plugins.scala.lang.lexer.ScalaLexer.TAG_STATE.NONEMPTY; import static org.jetbrains.plugins.scala.lang.lexer.ScalaLexer.TAG_STATE.UNDEFINED; import static org.jetbrains.plugins.scala.lang.lexer.ScalaPlainLexer.SCALA_CORE_MASK; import static org.jetbrains.plugins.scala.lang.lexer.ScalaPlainLexer.SCALA_CORE_SHIFT; import static org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypesEx.*; import org.jetbrains.plugins.scala.lang.lexer.core._ScalaCoreLexer; /** * @author ilyas */ public class ScalaLexer implements Lexer { protected final Lexer myScalaPlainLexer = new ScalaPlainLexer(); private final Lexer myXmlLexer = new XmlLexer(); protected Lexer myCurrentLexer; protected static final int MASK = 0x3F; protected static final int XML_SHIFT = 6; protected TIntStack myBraceStack = new TIntStack(); protected Stack<Stack<MyOpenXmlTag>> myLayeredTagStack = new Stack<Stack<MyOpenXmlTag>>(); protected int myBufferEnd; protected int myBufferStart; protected CharSequence myBuffer; protected int myXmlState; private int myTokenStart; private int myTokenEnd; protected IElementType myTokenType; public final String XML_BEGIN_PATTERN = "<\\w"; public final int SCALA_NEW_LINE_ALLOWED_STATE = (_ScalaCoreLexer.NEW_LINE_ALLOWED & (SCALA_CORE_MASK >> SCALA_CORE_SHIFT)) << SCALA_CORE_SHIFT; public ScalaLexer() { myCurrentLexer = myScalaPlainLexer; } @Deprecated public void start(char[] buffer) { start(buffer, 0, buffer.length); } @Deprecated public void start(char[] buffer, int startOffset, int endOffset) { start(buffer, startOffset, endOffset, 0); } @Deprecated public void start(char[] buffer, int startOffset, int endOffset, int initialState) { start(new CharArrayCharSequence(buffer), startOffset, endOffset, initialState); } public void start(CharSequence buffer, int startOffset, int endOffset, int initialState) { myCurrentLexer = myScalaPlainLexer; myCurrentLexer.start(buffer, startOffset, endOffset, initialState & MASK); myBraceStack.clear(); myLayeredTagStack.clear(); myXmlState = (initialState >> XML_SHIFT) & MASK; myBuffer = buffer; myBufferStart = startOffset; myBufferEnd = endOffset; myTokenType = null; } public int getState() { locateToken(); return myTokenStart == 0 ? 0 : 239; } @Nullable public IElementType getTokenType() { locateToken(); return myTokenType; } private void locateToken() { if (myTokenType == null) { IElementType type = myCurrentLexer.getTokenType(); int start = myCurrentLexer.getTokenStart(); String tokenText = myCurrentLexer.getBufferSequence().subSequence(start, myCurrentLexer.getTokenEnd()).toString(); if (type == SCALA_XML_CONTENT_START) { myCurrentLexer = myXmlLexer; myCurrentLexer.start(getBufferSequence(), start, myBufferEnd, myXmlState); myLayeredTagStack.push(new Stack<MyOpenXmlTag>()); myLayeredTagStack.peek().push(new MyOpenXmlTag()); myTokenType = myCurrentLexer.getTokenType(); locateTextRange(); } else if ((type == XML_ATTRIBUTE_VALUE_TOKEN || type == XML_DATA_CHARACTERS) && tokenText.startsWith("{") && !tokenText.startsWith("{{")) { myXmlState = myCurrentLexer.getState(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start, myBufferEnd, 0); locateTextRange(); myBraceStack.push(1); myTokenType = SCALA_IN_XML_INJECTION_START; } else if (type == ScalaTokenTypes.tRBRACE && myBraceStack.size() > 0) { int currentLayer = myBraceStack.pop(); if (currentLayer == 1) { locateTextRange(); (myCurrentLexer = myXmlLexer).start(getBufferSequence(), start + 1, myBufferEnd, myXmlState); myTokenType = SCALA_IN_XML_INJECTION_END; } else { myBraceStack.push(--currentLayer); } } else if (type == ScalaTokenTypes.tLBRACE && myBraceStack.size() > 0) { int currentLayer = myBraceStack.pop(); myBraceStack.push(++currentLayer); } else if ((XML_START_TAG_START == type || XML_COMMENT_START == type || XML_CDATA_START == type || XML_PI_START == type)&& !myLayeredTagStack.isEmpty()) { myLayeredTagStack.peek().push(new MyOpenXmlTag()); } else if (XML_EMPTY_ELEMENT_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == UNDEFINED) { myLayeredTagStack.peek().pop(); if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 2, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_EMPTY_ELEMENT_END; } } else if (XML_TAG_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty()) { MyOpenXmlTag tag = myLayeredTagStack.peek().peek(); if (tag.state == UNDEFINED) { tag.state = NONEMPTY; } else if (tag.state == NONEMPTY) { myLayeredTagStack.peek().pop(); } if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 1, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_TAG_END; } } else if (XML_PI_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == UNDEFINED) { myLayeredTagStack.peek().pop(); if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 2, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_PI_END; } } else if (XML_COMMENT_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == UNDEFINED) { myLayeredTagStack.peek().pop(); if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 3, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_COMMENT_END; } } else if (XML_CDATA_END == type && !myLayeredTagStack.isEmpty() && !myLayeredTagStack.peek().isEmpty() && myLayeredTagStack.peek().peek().state == UNDEFINED) { myLayeredTagStack.peek().pop(); if (myLayeredTagStack.peek().isEmpty() && checkNotNextXmlBegin(myCurrentLexer)) { myLayeredTagStack.pop(); locateTextRange(); (myCurrentLexer = myScalaPlainLexer).start(getBufferSequence(), start + 3, myBufferEnd, SCALA_NEW_LINE_ALLOWED_STATE); myTokenType = XML_CDATA_END; } } else if (type == XML_DATA_CHARACTERS && tokenText.indexOf('{')!=-1) { int scalaToken = tokenText.indexOf('{'); while (scalaToken != -1 && scalaToken+1 < tokenText.length() && tokenText.charAt(scalaToken+1)=='{') scalaToken = tokenText.indexOf('{', scalaToken + 2); if (scalaToken != -1) { myTokenType = XML_DATA_CHARACTERS; myTokenStart = myCurrentLexer.getTokenStart(); myTokenEnd = myTokenStart + scalaToken; myCurrentLexer.start(getBufferSequence(),myTokenEnd,myBufferEnd,myCurrentLexer.getState()); } } /*else if (type == XML_REAL_WHITE_SPACE || type == XML_WHITE_SPACE || type == XmlTokenType.TAG_WHITE_SPACE) { //type = ScalaTokenTypes.tWHITE_SPACE_IN_LINE; }*/ if (myTokenType == null) { myTokenType = type; if (myTokenType == null) return; locateTextRange(); } myCurrentLexer.advance(); } } private void locateTextRange() { myTokenStart = myCurrentLexer.getTokenStart(); myTokenEnd = myCurrentLexer.getTokenEnd(); } private boolean checkNotNextXmlBegin(Lexer lexer) { String text = lexer.getBufferSequence().toString(); int beginIndex = lexer.getTokenEnd(); if (beginIndex < text.length()) { text = text.substring(beginIndex).trim(); if (text.length() > 2) { text = text.substring(0, 2); } return !text.matches(XML_BEGIN_PATTERN); } return true; } public int getTokenStart() { locateToken(); return myTokenStart; } public int getTokenEnd() { locateToken(); return myTokenEnd; } public void advance() { myTokenType = null; } public LexerPosition getCurrentPosition() { return new MyPosition( myTokenStart, myTokenEnd, new MyState( myXmlState, 0, myBraceStack, myCurrentLexer, myLayeredTagStack)); } public void restore(LexerPosition position) { MyPosition pos = (MyPosition) position; myBraceStack = pos.state.braceStack; myCurrentLexer = pos.state.currentLexer; myTokenStart = pos.getOffset(); myTokenEnd = pos.end; myLayeredTagStack = pos.state.tagStack; myCurrentLexer.start(myCurrentLexer.getBufferSequence(), myTokenStart, myBufferEnd, myCurrentLexer instanceof XmlLexer ? pos.state.xmlState : 0); } @Deprecated public char[] getBuffer() { return myCurrentLexer.getBuffer(); } public CharSequence getBufferSequence() { return myBuffer; } public int getBufferEnd() { return myBufferEnd; } private static class MyState implements LexerState { public TIntStack braceStack; public Stack<Stack<MyOpenXmlTag>> tagStack; public Lexer currentLexer; public int xmlState; public int scalaState; public MyState(final int xmlState, final int scalaState, TIntStack braceStack, Lexer lexer, Stack<Stack<MyOpenXmlTag>> tagStack) { this.braceStack = braceStack; this.tagStack = tagStack; this.currentLexer = lexer; this.xmlState = xmlState; this.scalaState = scalaState; } public short intern() { return 0; } } private static class MyPosition implements LexerPosition { public int start; public int end; public MyState state; public MyPosition(final int start, final int end, final MyState state) { this.start = start; this.end = end; this.state = state; } public int getOffset() { return start; } public int getState() { return state.currentLexer.getState(); } } protected static enum TAG_STATE { UNDEFINED, EMPTY, NONEMPTY } private static class MyOpenXmlTag { public TAG_STATE state = UNDEFINED; } }
Xml lexing altered git-svn-id: ba81b6bd3dd9830eeafada3de57364a31f808d18@16862 59f64563-22e8-0310-8d2c-98a15e1539f2
scala_core/src/org/jetbrains/plugins/scala/lang/lexer/ScalaLexer.java
Xml lexing altered
<ide><path>cala_core/src/org/jetbrains/plugins/scala/lang/lexer/ScalaLexer.java <ide> myTokenEnd = myTokenStart + scalaToken; <ide> myCurrentLexer.start(getBufferSequence(),myTokenEnd,myBufferEnd,myCurrentLexer.getState()); <ide> } <del> } /*else if (type == XML_REAL_WHITE_SPACE || <add> } else if ((type == XML_REAL_WHITE_SPACE || <ide> type == XML_WHITE_SPACE || <del> type == XmlTokenType.TAG_WHITE_SPACE) { <del> //type = ScalaTokenTypes.tWHITE_SPACE_IN_LINE; <del> }*/ <add> type == TAG_WHITE_SPACE) && <add> tokenText.matches("\\s*\n(\n|\\s)*")) { <add> type = ScalaTokenTypes.tWHITE_SPACE_IN_LINE; <add> } <ide> if (myTokenType == null) { <ide> myTokenType = type; <ide> if (myTokenType == null) return;
Java
apache-2.0
ac5175d892dbcd1ef7652a3ce0e038ad0ba731a2
0
toBeNewbie/moblileSafe
package com.example.mobilesafe; import android.app.Activity; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.view.Menu; import android.view.Window; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.widget.RelativeLayout; import android.widget.TextView; /** * @author Administrator *@company Newbie *@date 2016-8-15 *@des 初始化Splash界面。 */ public class SplashActivity extends Activity { private TextView splash_version_name; private RelativeLayout rl_splash_root; private String versionName; private AnimationSet mAnimationSet; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); //初始化界面。 initView(); //显示数据到界面。 initDate(); initEvent(); //设置动画 initAnimation(); } private void initAnimation() { RotateAnimation ra = new RotateAnimation(0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); ra.setDuration(2000); ra.setFillAfter(true); ScaleAnimation sa = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); sa.setDuration(2000); sa.setFillAfter(true); AlphaAnimation aa=new AlphaAnimation(0.0f, 1.0f); aa.setDuration(2000); aa.setFillAfter(true); mAnimationSet = new AnimationSet(false); mAnimationSet.addAnimation(sa); mAnimationSet.addAnimation(ra); mAnimationSet.addAnimation(aa); rl_splash_root.startAnimation(mAnimationSet); } /** * 初始化splash界面 */ private void initView() { // TODO Auto-generated method stub setContentView(R.layout.activity_splash); rl_splash_root = (RelativeLayout) findViewById(R.id.rl_splash_root); splash_version_name = (TextView) findViewById(R.id.tv_splash_version_name); } /** * 填充splash界面初始化数据 */ private void initDate() { // TODO Auto-generated method stub try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); versionName = packageInfo.versionName; splash_version_name.setText(versionName); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void initEvent() { // TODO Auto-generated method stub } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
src/com/example/mobilesafe/SplashActivity.java
package com.example.mobilesafe; import android.app.Activity; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.view.Menu; import android.view.Window; import android.widget.RelativeLayout; import android.widget.TextView; /** * @author Administrator *@company Newbie *@date 2016-8-15 *@des 初始化Splash界面。 */ public class SplashActivity extends Activity { private TextView splash_version_name; private RelativeLayout rl_splash_root; private String versionName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); initView(); initDate(); initEvent(); } /** * 初始化splash界面 */ private void initView() { // TODO Auto-generated method stub setContentView(R.layout.activity_splash); rl_splash_root = (RelativeLayout) findViewById(R.id.rl_splash_root); splash_version_name = (TextView) findViewById(R.id.tv_splash_version_name); } /** * 填充splash界面初始化数据 */ private void initDate() { // TODO Auto-generated method stub try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); versionName = packageInfo.versionName; splash_version_name.setText(versionName); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void initEvent() { // TODO Auto-generated method stub } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
设置splash相关动画。
src/com/example/mobilesafe/SplashActivity.java
设置splash相关动画。
<ide><path>rc/com/example/mobilesafe/SplashActivity.java <ide> package com.example.mobilesafe; <ide> <ide> import android.app.Activity; <del>import android.content.pm.ApplicationInfo; <ide> import android.content.pm.PackageInfo; <ide> import android.content.pm.PackageManager.NameNotFoundException; <ide> import android.os.Bundle; <ide> import android.view.Menu; <ide> import android.view.Window; <add>import android.view.animation.AlphaAnimation; <add>import android.view.animation.Animation; <add>import android.view.animation.AnimationSet; <add>import android.view.animation.RotateAnimation; <add>import android.view.animation.ScaleAnimation; <ide> import android.widget.RelativeLayout; <ide> import android.widget.TextView; <ide> <ide> private TextView splash_version_name; <ide> private RelativeLayout rl_splash_root; <ide> private String versionName; <add> private AnimationSet mAnimationSet; <ide> <ide> @Override <ide> protected void onCreate(Bundle savedInstanceState) { <ide> super.onCreate(savedInstanceState); <ide> requestWindowFeature(Window.FEATURE_NO_TITLE); <ide> <add> //初始化界面。 <ide> initView(); <del> <add> //显示数据到界面。 <ide> initDate(); <ide> <ide> initEvent(); <add> <add> //设置动画 <add> initAnimation(); <ide> } <add> <add> private void initAnimation() { <add> RotateAnimation ra = new RotateAnimation(0.0f, 360.0f, <add> Animation.RELATIVE_TO_SELF, 0.5f, <add> Animation.RELATIVE_TO_SELF, 0.5f); <add> ra.setDuration(2000); <add> ra.setFillAfter(true); <add> <add> ScaleAnimation sa = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, <add> Animation.RELATIVE_TO_SELF, 0.5f, <add> Animation.RELATIVE_TO_SELF, 0.5f); <add> sa.setDuration(2000); <add> sa.setFillAfter(true); <add> <add> AlphaAnimation aa=new AlphaAnimation(0.0f, 1.0f); <add> aa.setDuration(2000); <add> aa.setFillAfter(true); <add> <add> <add> mAnimationSet = new AnimationSet(false); <add> mAnimationSet.addAnimation(sa); <add> mAnimationSet.addAnimation(ra); <add> mAnimationSet.addAnimation(aa); <add> rl_splash_root.startAnimation(mAnimationSet); <add> } <ide> <ide> /** <ide> * 初始化splash界面
Java
epl-1.0
f06b54b5364dcec0ab34126c544752bb5d78d399
0
codenvy/codenvy,codenvy/codenvy,codenvy/codenvy,codenvy/codenvy,codenvy/codenvy,codenvy/codenvy
/* * Copyright (c) [2012] - [2017] Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package com.codenvy.machine; import static com.codenvy.machine.MaintenanceConstraintProvider.MAINTENANCE_CONSTRAINT_KEY; import static com.codenvy.machine.MaintenanceConstraintProvider.MAINTENANCE_CONSTRAINT_VALUE; import static java.lang.String.format; import static org.slf4j.LoggerFactory.getLogger; import com.codenvy.machine.authentication.server.MachineTokenRegistry; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Named; import org.eclipse.che.api.core.NotFoundException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.jsonrpc.commons.RequestTransmitter; import org.eclipse.che.api.core.model.machine.ServerConf; import org.eclipse.che.api.core.util.FileCleaner; import org.eclipse.che.api.core.util.JsonRpcEndpointToMachineNameHolder; import org.eclipse.che.api.environment.server.model.CheServiceImpl; import org.eclipse.che.api.machine.server.exception.MachineException; import org.eclipse.che.api.machine.server.exception.SourceNotFoundException; import org.eclipse.che.commons.annotation.Nullable; import org.eclipse.che.commons.env.EnvironmentContext; import org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler; import org.eclipse.che.commons.lang.os.WindowsPathEscaper; import org.eclipse.che.plugin.docker.client.DockerConnector; import org.eclipse.che.plugin.docker.client.DockerConnectorProvider; import org.eclipse.che.plugin.docker.client.ProgressMonitor; import org.eclipse.che.plugin.docker.client.UserSpecificDockerRegistryCredentialsProvider; import org.eclipse.che.plugin.docker.client.exception.ContainerNotFoundException; import org.eclipse.che.plugin.docker.client.exception.DockerException; import org.eclipse.che.plugin.docker.client.exception.ImageNotFoundException; import org.eclipse.che.plugin.docker.client.json.ContainerConfig; import org.eclipse.che.plugin.docker.client.params.BuildImageParams; import org.eclipse.che.plugin.docker.machine.DockerInstanceStopDetector; import org.eclipse.che.plugin.docker.machine.DockerMachineFactory; import org.eclipse.che.plugin.docker.machine.MachineProviderImpl; import org.slf4j.Logger; /** * Specific implementation of {@link MachineProviderImpl} needed for hosted environment. * * <p>This implementation: <br> * - provides compose services with environment context that contains the specific machine token * instead of user token <br> * - workarounds buggy pulling on swarm by replacing it with build <br> * - add constraints to build to avoid docker image building on a node under maintenance * * @author Anton Korneta * @author Roman Iuvshyn * @author Alexander Garagatyi * @author Mykola Morhun */ public class HostedMachineProviderImpl extends MachineProviderImpl { private static final Logger LOG = getLogger(HostedMachineProviderImpl.class); @VisibleForTesting static int SWARM_WAIT_BEFORE_REPEAT_WORKAROUND_TIME_MS = 5_000; private final DockerConnector docker; private final UserSpecificDockerRegistryCredentialsProvider dockerCredentials; private final MachineTokenRegistry tokenRegistry; private final String cpusetCpus; private final long cpuPeriod; private final long cpuQuota; private final Map<String, String> buildArgs; private final ScheduledExecutorService snapshotImagesCleanerService; @Inject public HostedMachineProviderImpl( DockerConnectorProvider dockerConnectorProvider, UserSpecificDockerRegistryCredentialsProvider dockerCredentials, DockerMachineFactory dockerMachineFactory, DockerInstanceStopDetector dockerInstanceStopDetector, WindowsPathEscaper windowsPathEscaper, RequestTransmitter requestTransmitter, JsonRpcEndpointToMachineNameHolder endpointIdsHolder, @Named("machine.docker.dev_machine.machine_servers") Set<ServerConf> devMachineServers, @Named("machine.docker.machine_servers") Set<ServerConf> allMachinesServers, @Named("machine.docker.dev_machine.machine_volumes") Set<String> devMachineSystemVolumes, @Named("machine.docker.machine_volumes") Set<String> allMachinesSystemVolumes, @Named("che.docker.always_pull_image") boolean doForcePullOnBuild, @Named("che.docker.privileged") boolean privilegedMode, @Named("che.docker.pids_limit") int pidsLimit, @Named("machine.docker.dev_machine.machine_env") Set<String> devMachineEnvVariables, @Named("machine.docker.machine_env") Set<String> allMachinesEnvVariables, @Named("che.docker.registry_for_snapshots") boolean snapshotUseRegistry, @Named("che.docker.swap") double memorySwapMultiplier, MachineTokenRegistry tokenRegistry, @Named("machine.docker.networks") Set<Set<String>> additionalNetworks, @Nullable @Named("che.docker.network_driver") String networkDriver, @Nullable @Named("che.docker.parent_cgroup") String parentCgroup, @Nullable @Named("che.docker.cpuset_cpus") String cpusetCpus, @Named("che.docker.cpu_period") long cpuPeriod, @Named("che.docker.cpu_quota") long cpuQuota, @Named("che.docker.extra_hosts") Set<Set<String>> additionalHosts, @Nullable @Named("che.docker.dns_resolvers") String[] dnsResolvers, @Named("che.docker.build_args") Map<String, String> buildArgs) throws IOException { super( dockerConnectorProvider, dockerCredentials, dockerMachineFactory, dockerInstanceStopDetector, requestTransmitter, endpointIdsHolder, devMachineServers, allMachinesServers, devMachineSystemVolumes, allMachinesSystemVolumes, doForcePullOnBuild, privilegedMode, pidsLimit, devMachineEnvVariables, allMachinesEnvVariables, snapshotUseRegistry, memorySwapMultiplier, additionalNetworks, networkDriver, parentCgroup, cpusetCpus, cpuPeriod, cpuQuota, windowsPathEscaper, additionalHosts, dnsResolvers, buildArgs); this.docker = dockerConnectorProvider.get(); this.dockerCredentials = dockerCredentials; this.tokenRegistry = tokenRegistry; this.cpusetCpus = cpusetCpus; this.cpuPeriod = cpuPeriod; this.cpuQuota = cpuQuota; this.buildArgs = new HashMap<>(buildArgs); // don't build an image on a node under maintenance this.buildArgs.put(MAINTENANCE_CONSTRAINT_KEY, MAINTENANCE_CONSTRAINT_VALUE); this.snapshotImagesCleanerService = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("SnapshotImagesCleaner") .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .setDaemon(false) .build()); } @Override protected String getUserToken(String wsId) { String userToken = null; try { userToken = tokenRegistry.getOrCreateToken( EnvironmentContext.getCurrent().getSubject().getUserId(), wsId); } catch (NotFoundException ignore) { } return MoreObjects.firstNonNull(userToken, ""); } /** * Origin pull image is unstable with swarm. This method workarounds that with performing docker * build instead of docker pull. * * <p>{@inheritDoc} */ @Override protected void pullImage( CheServiceImpl service, String machineImageName, ProgressMonitor progressMonitor) throws MachineException { String image = service.getImage(); File workDir = null; try { // build docker image workDir = Files.createTempDirectory(null).toFile(); final File dockerfileFile = new File(workDir, "Dockerfile"); try (FileWriter output = new FileWriter(dockerfileFile)) { output.append("FROM ").append(image); } docker.buildImage( BuildImageParams.create(dockerfileFile) .withForceRemoveIntermediateContainers(true) .withRepository(machineImageName) .withAuthConfigs(dockerCredentials.getCredentials()) .withDoForcePull(true) .withMemoryLimit(service.getMemLimit()) .withMemorySwapLimit(-1) .withCpusetCpus(cpusetCpus) .withCpuPeriod(cpuPeriod) .withCpuQuota(cpuQuota) .withBuildArgs(buildArgs), progressMonitor); } catch (ImageNotFoundException e) { throw new SourceNotFoundException(format("Failed to get image: %s. Cause: %s", image, e.getLocalizedMessage()), e); } catch (DockerException e) { // Check whether image to pull is a snapshot and if so then fallback to workspace recipe. if (image != null && SNAPSHOT_LOCATION_PATTERN.matcher(image).matches()) { throw new SourceNotFoundException(format("Failed to get snapshot image: %s. Cause: %s", image, e.getLocalizedMessage()), e); } throw new MachineException(e.getLocalizedMessage(), e); } catch (IOException e) { throw new MachineException(e.getLocalizedMessage(), e); } finally { if (workDir != null) { FileCleaner.addFile(workDir); } // When new image is being built it pulls base image. This operation is performed by docker build command. // So, after build it is needed to cleanup base image if it is a snapshot. if (service.getImage().contains(MACHINE_SNAPSHOT_PREFIX)) { submitCleanSnapshotImageTask(service.getImage()); } } } /** * Sometimes swarm cannot delete image after its pull during a few seconds. To workaround that * problem and avoid redundant delay on workspace start we must clean up snapshot image in * separate thread after some delay. * * @param image image to clean, e.g. 172.11.12.13:5000/machine_snapshot_abcdef1234567890:latest */ private void submitCleanSnapshotImageTask(String image) { // TODO replace this method by docker.removeImage(image) call after fix of the problem in pure Docker Swarm snapshotImagesCleanerService.schedule( () -> { try { docker.removeImage(image); } catch (IOException e) { if (!e.getMessage() .contains("No such image")) { // ignore error if image already deleted LOG.error("Failed to delete pulled snapshot: " + image); } } }, 10L, TimeUnit.SECONDS); } /** * This method adds constraint to build args for support 'scheduled for maintenance' labels of * nodes. * * <p>{@inheritDoc} */ @Override protected void buildImage( CheServiceImpl service, String machineImageName, boolean doForcePullOnBuild, ProgressMonitor progressMonitor) throws MachineException { File workDir = null; try { BuildImageParams buildImageParams; if (service.getBuild() != null && service.getBuild().getDockerfileContent() != null) { workDir = Files.createTempDirectory(null).toFile(); final File dockerfileFile = new File(workDir, "Dockerfile"); try (FileWriter output = new FileWriter(dockerfileFile)) { output.append(service.getBuild().getDockerfileContent()); } buildImageParams = BuildImageParams.create(dockerfileFile); } else { buildImageParams = BuildImageParams.create(service.getBuild().getContext()) .withDockerfile(service.getBuild().getDockerfilePath()); } Map<String, String> buildArgs; if (service.getBuild().getArgs() == null || service.getBuild().getArgs().isEmpty()) { buildArgs = this.buildArgs; } else { buildArgs = new HashMap<>(this.buildArgs); buildArgs.putAll(service.getBuild().getArgs()); } buildImageParams .withForceRemoveIntermediateContainers(true) .withRepository(machineImageName) .withAuthConfigs(dockerCredentials.getCredentials()) .withDoForcePull(doForcePullOnBuild) .withMemoryLimit(service.getMemLimit()) .withMemorySwapLimit(-1) .withCpusetCpus(cpusetCpus) .withCpuPeriod(cpuPeriod) .withCpuQuota(cpuQuota) .withBuildArgs(buildArgs); docker.buildImage(buildImageParams, progressMonitor); } catch (IOException e) { throw new MachineException(e.getLocalizedMessage(), e); } finally { if (workDir != null) { FileCleaner.addFile(workDir); } } } @Override protected void setNonExitingContainerCommandIfNeeded(ContainerConfig containerConfig) throws IOException { // Sometimes Swarm doesn't see newly created images for several seconds. // Here we retry operation to ensure that such behavior of Swarm doesn't affect the product. try { super.setNonExitingContainerCommandIfNeeded(containerConfig); } catch (ImageNotFoundException e) { try { Thread.sleep(SWARM_WAIT_BEFORE_REPEAT_WORKAROUND_TIME_MS); super.setNonExitingContainerCommandIfNeeded(containerConfig); } catch (InterruptedException ignored) { // throw original error throw e; } } } @Override protected void checkContainerIsRunning(String container) throws IOException, ServerException { // Sometimes Swarm doesn't see newly created containers for several seconds. // Here we retry operation to ensure that such behavior of Swarm doesn't affect the product. try { super.checkContainerIsRunning(container); } catch (ContainerNotFoundException e) { try { Thread.sleep(SWARM_WAIT_BEFORE_REPEAT_WORKAROUND_TIME_MS); super.checkContainerIsRunning(container); } catch (InterruptedException ignored) { // throw original error throw e; } } } @PreDestroy private void finalizeSnapshotImagesCleaner() { snapshotImagesCleanerService.shutdown(); try { if (!snapshotImagesCleanerService.awaitTermination(30L, TimeUnit.SECONDS)) { snapshotImagesCleanerService.shutdownNow(); if (!snapshotImagesCleanerService.awaitTermination(10L, TimeUnit.SECONDS)) { LOG.warn("Failed to terminate SnapshotImagesCleaner scheduler"); } } } catch (InterruptedException e) { snapshotImagesCleanerService.shutdownNow(); Thread.currentThread().interrupt(); } } }
plugins/plugin-hosted/codenvy-machine-hosted/src/main/java/com/codenvy/machine/HostedMachineProviderImpl.java
/* * Copyright (c) [2012] - [2017] Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation */ package com.codenvy.machine; import static com.codenvy.machine.MaintenanceConstraintProvider.MAINTENANCE_CONSTRAINT_KEY; import static com.codenvy.machine.MaintenanceConstraintProvider.MAINTENANCE_CONSTRAINT_VALUE; import static org.slf4j.LoggerFactory.getLogger; import com.codenvy.machine.authentication.server.MachineTokenRegistry; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Named; import org.eclipse.che.api.core.NotFoundException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.jsonrpc.commons.RequestTransmitter; import org.eclipse.che.api.core.model.machine.ServerConf; import org.eclipse.che.api.core.util.FileCleaner; import org.eclipse.che.api.core.util.JsonRpcEndpointToMachineNameHolder; import org.eclipse.che.api.environment.server.model.CheServiceImpl; import org.eclipse.che.api.machine.server.exception.MachineException; import org.eclipse.che.api.machine.server.exception.SourceNotFoundException; import org.eclipse.che.commons.annotation.Nullable; import org.eclipse.che.commons.env.EnvironmentContext; import org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler; import org.eclipse.che.commons.lang.os.WindowsPathEscaper; import org.eclipse.che.plugin.docker.client.DockerConnector; import org.eclipse.che.plugin.docker.client.DockerConnectorProvider; import org.eclipse.che.plugin.docker.client.ProgressMonitor; import org.eclipse.che.plugin.docker.client.UserSpecificDockerRegistryCredentialsProvider; import org.eclipse.che.plugin.docker.client.exception.ContainerNotFoundException; import org.eclipse.che.plugin.docker.client.exception.DockerException; import org.eclipse.che.plugin.docker.client.exception.ImageNotFoundException; import org.eclipse.che.plugin.docker.client.json.ContainerConfig; import org.eclipse.che.plugin.docker.client.params.BuildImageParams; import org.eclipse.che.plugin.docker.machine.DockerInstanceStopDetector; import org.eclipse.che.plugin.docker.machine.DockerMachineFactory; import org.eclipse.che.plugin.docker.machine.MachineProviderImpl; import org.slf4j.Logger; /** * Specific implementation of {@link MachineProviderImpl} needed for hosted environment. * * <p>This implementation: <br> * - provides compose services with environment context that contains the specific machine token * instead of user token <br> * - workarounds buggy pulling on swarm by replacing it with build <br> * - add constraints to build to avoid docker image building on a node under maintenance * * @author Anton Korneta * @author Roman Iuvshyn * @author Alexander Garagatyi * @author Mykola Morhun */ public class HostedMachineProviderImpl extends MachineProviderImpl { private static final Logger LOG = getLogger(HostedMachineProviderImpl.class); @VisibleForTesting static int SWARM_WAIT_BEFORE_REPEAT_WORKAROUND_TIME_MS = 5_000; private final DockerConnector docker; private final UserSpecificDockerRegistryCredentialsProvider dockerCredentials; private final MachineTokenRegistry tokenRegistry; private final String cpusetCpus; private final long cpuPeriod; private final long cpuQuota; private final Map<String, String> buildArgs; private final ScheduledExecutorService snapshotImagesCleanerService; @Inject public HostedMachineProviderImpl( DockerConnectorProvider dockerConnectorProvider, UserSpecificDockerRegistryCredentialsProvider dockerCredentials, DockerMachineFactory dockerMachineFactory, DockerInstanceStopDetector dockerInstanceStopDetector, WindowsPathEscaper windowsPathEscaper, RequestTransmitter requestTransmitter, JsonRpcEndpointToMachineNameHolder endpointIdsHolder, @Named("machine.docker.dev_machine.machine_servers") Set<ServerConf> devMachineServers, @Named("machine.docker.machine_servers") Set<ServerConf> allMachinesServers, @Named("machine.docker.dev_machine.machine_volumes") Set<String> devMachineSystemVolumes, @Named("machine.docker.machine_volumes") Set<String> allMachinesSystemVolumes, @Named("che.docker.always_pull_image") boolean doForcePullOnBuild, @Named("che.docker.privileged") boolean privilegedMode, @Named("che.docker.pids_limit") int pidsLimit, @Named("machine.docker.dev_machine.machine_env") Set<String> devMachineEnvVariables, @Named("machine.docker.machine_env") Set<String> allMachinesEnvVariables, @Named("che.docker.registry_for_snapshots") boolean snapshotUseRegistry, @Named("che.docker.swap") double memorySwapMultiplier, MachineTokenRegistry tokenRegistry, @Named("machine.docker.networks") Set<Set<String>> additionalNetworks, @Nullable @Named("che.docker.network_driver") String networkDriver, @Nullable @Named("che.docker.parent_cgroup") String parentCgroup, @Nullable @Named("che.docker.cpuset_cpus") String cpusetCpus, @Named("che.docker.cpu_period") long cpuPeriod, @Named("che.docker.cpu_quota") long cpuQuota, @Named("che.docker.extra_hosts") Set<Set<String>> additionalHosts, @Nullable @Named("che.docker.dns_resolvers") String[] dnsResolvers, @Named("che.docker.build_args") Map<String, String> buildArgs) throws IOException { super( dockerConnectorProvider, dockerCredentials, dockerMachineFactory, dockerInstanceStopDetector, requestTransmitter, endpointIdsHolder, devMachineServers, allMachinesServers, devMachineSystemVolumes, allMachinesSystemVolumes, doForcePullOnBuild, privilegedMode, pidsLimit, devMachineEnvVariables, allMachinesEnvVariables, snapshotUseRegistry, memorySwapMultiplier, additionalNetworks, networkDriver, parentCgroup, cpusetCpus, cpuPeriod, cpuQuota, windowsPathEscaper, additionalHosts, dnsResolvers, buildArgs); this.docker = dockerConnectorProvider.get(); this.dockerCredentials = dockerCredentials; this.tokenRegistry = tokenRegistry; this.cpusetCpus = cpusetCpus; this.cpuPeriod = cpuPeriod; this.cpuQuota = cpuQuota; this.buildArgs = new HashMap<>(buildArgs); // don't build an image on a node under maintenance this.buildArgs.put(MAINTENANCE_CONSTRAINT_KEY, MAINTENANCE_CONSTRAINT_VALUE); this.snapshotImagesCleanerService = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("SnapshotImagesCleaner") .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .setDaemon(false) .build()); } @Override protected String getUserToken(String wsId) { String userToken = null; try { userToken = tokenRegistry.getOrCreateToken( EnvironmentContext.getCurrent().getSubject().getUserId(), wsId); } catch (NotFoundException ignore) { } return MoreObjects.firstNonNull(userToken, ""); } /** * Origin pull image is unstable with swarm. This method workarounds that with performing docker * build instead of docker pull. * * <p>{@inheritDoc} */ @Override protected void pullImage( CheServiceImpl service, String machineImageName, ProgressMonitor progressMonitor) throws MachineException { String image = service.getImage(); File workDir = null; try { // build docker image workDir = Files.createTempDirectory(null).toFile(); final File dockerfileFile = new File(workDir, "Dockerfile"); try (FileWriter output = new FileWriter(dockerfileFile)) { output.append("FROM ").append(image); } docker.buildImage( BuildImageParams.create(dockerfileFile) .withForceRemoveIntermediateContainers(true) .withRepository(machineImageName) .withAuthConfigs(dockerCredentials.getCredentials()) .withDoForcePull(true) .withMemoryLimit(service.getMemLimit()) .withMemorySwapLimit(-1) .withCpusetCpus(cpusetCpus) .withCpuPeriod(cpuPeriod) .withCpuQuota(cpuQuota) .withBuildArgs(buildArgs), progressMonitor); } catch (ImageNotFoundException e) { throw new SourceNotFoundException(e.getLocalizedMessage(), e); } catch (DockerException e) { // Check whether image to pull is a snapshot and if so then fallback to workspace recipe. if (image != null && SNAPSHOT_LOCATION_PATTERN.matcher(image).matches()) { throw new SourceNotFoundException(e.getLocalizedMessage(), e); } throw new MachineException(e.getLocalizedMessage(), e); } catch (IOException e) { throw new MachineException(e.getLocalizedMessage(), e); } finally { if (workDir != null) { FileCleaner.addFile(workDir); } // When new image is being built it pulls base image. This operation is performed by docker build command. // So, after build it is needed to cleanup base image if it is a snapshot. if (service.getImage().contains(MACHINE_SNAPSHOT_PREFIX)) { submitCleanSnapshotImageTask(service.getImage()); } } } /** * Sometimes swarm cannot delete image after its pull during a few seconds. To workaround that * problem and avoid redundant delay on workspace start we must clean up snapshot image in * separate thread after some delay. * * @param image image to clean, e.g. 172.11.12.13:5000/machine_snapshot_abcdef1234567890:latest */ private void submitCleanSnapshotImageTask(String image) { // TODO replace this method by docker.removeImage(image) call after fix of the problem in pure Docker Swarm snapshotImagesCleanerService.schedule( () -> { try { docker.removeImage(image); } catch (IOException e) { if (!e.getMessage() .contains("No such image")) { // ignore error if image already deleted LOG.error("Failed to delete pulled snapshot: " + image); } } }, 10L, TimeUnit.SECONDS); } /** * This method adds constraint to build args for support 'scheduled for maintenance' labels of * nodes. * * <p>{@inheritDoc} */ @Override protected void buildImage( CheServiceImpl service, String machineImageName, boolean doForcePullOnBuild, ProgressMonitor progressMonitor) throws MachineException { File workDir = null; try { BuildImageParams buildImageParams; if (service.getBuild() != null && service.getBuild().getDockerfileContent() != null) { workDir = Files.createTempDirectory(null).toFile(); final File dockerfileFile = new File(workDir, "Dockerfile"); try (FileWriter output = new FileWriter(dockerfileFile)) { output.append(service.getBuild().getDockerfileContent()); } buildImageParams = BuildImageParams.create(dockerfileFile); } else { buildImageParams = BuildImageParams.create(service.getBuild().getContext()) .withDockerfile(service.getBuild().getDockerfilePath()); } Map<String, String> buildArgs; if (service.getBuild().getArgs() == null || service.getBuild().getArgs().isEmpty()) { buildArgs = this.buildArgs; } else { buildArgs = new HashMap<>(this.buildArgs); buildArgs.putAll(service.getBuild().getArgs()); } buildImageParams .withForceRemoveIntermediateContainers(true) .withRepository(machineImageName) .withAuthConfigs(dockerCredentials.getCredentials()) .withDoForcePull(doForcePullOnBuild) .withMemoryLimit(service.getMemLimit()) .withMemorySwapLimit(-1) .withCpusetCpus(cpusetCpus) .withCpuPeriod(cpuPeriod) .withCpuQuota(cpuQuota) .withBuildArgs(buildArgs); docker.buildImage(buildImageParams, progressMonitor); } catch (IOException e) { throw new MachineException(e.getLocalizedMessage(), e); } finally { if (workDir != null) { FileCleaner.addFile(workDir); } } } @Override protected void setNonExitingContainerCommandIfNeeded(ContainerConfig containerConfig) throws IOException { // Sometimes Swarm doesn't see newly created images for several seconds. // Here we retry operation to ensure that such behavior of Swarm doesn't affect the product. try { super.setNonExitingContainerCommandIfNeeded(containerConfig); } catch (ImageNotFoundException e) { try { Thread.sleep(SWARM_WAIT_BEFORE_REPEAT_WORKAROUND_TIME_MS); super.setNonExitingContainerCommandIfNeeded(containerConfig); } catch (InterruptedException ignored) { // throw original error throw e; } } } @Override protected void checkContainerIsRunning(String container) throws IOException, ServerException { // Sometimes Swarm doesn't see newly created containers for several seconds. // Here we retry operation to ensure that such behavior of Swarm doesn't affect the product. try { super.checkContainerIsRunning(container); } catch (ContainerNotFoundException e) { try { Thread.sleep(SWARM_WAIT_BEFORE_REPEAT_WORKAROUND_TIME_MS); super.checkContainerIsRunning(container); } catch (InterruptedException ignored) { // throw original error throw e; } } } @PreDestroy private void finalizeSnapshotImagesCleaner() { snapshotImagesCleanerService.shutdown(); try { if (!snapshotImagesCleanerService.awaitTermination(30L, TimeUnit.SECONDS)) { snapshotImagesCleanerService.shutdownNow(); if (!snapshotImagesCleanerService.awaitTermination(10L, TimeUnit.SECONDS)) { LOG.warn("Failed to terminate SnapshotImagesCleaner scheduler"); } } } catch (InterruptedException e) { snapshotImagesCleanerService.shutdownNow(); Thread.currentThread().interrupt(); } } }
CODENVY-2284: Add additional logs (#2406)
plugins/plugin-hosted/codenvy-machine-hosted/src/main/java/com/codenvy/machine/HostedMachineProviderImpl.java
CODENVY-2284: Add additional logs (#2406)
<ide><path>lugins/plugin-hosted/codenvy-machine-hosted/src/main/java/com/codenvy/machine/HostedMachineProviderImpl.java <ide> <ide> import static com.codenvy.machine.MaintenanceConstraintProvider.MAINTENANCE_CONSTRAINT_KEY; <ide> import static com.codenvy.machine.MaintenanceConstraintProvider.MAINTENANCE_CONSTRAINT_VALUE; <add>import static java.lang.String.format; <ide> import static org.slf4j.LoggerFactory.getLogger; <ide> <ide> import com.codenvy.machine.authentication.server.MachineTokenRegistry; <ide> .withBuildArgs(buildArgs), <ide> progressMonitor); <ide> } catch (ImageNotFoundException e) { <del> throw new SourceNotFoundException(e.getLocalizedMessage(), e); <add> throw new SourceNotFoundException(format("Failed to get image: %s. Cause: %s", <add> image, <add> e.getLocalizedMessage()), <add> e); <ide> } catch (DockerException e) { <ide> // Check whether image to pull is a snapshot and if so then fallback to workspace recipe. <ide> if (image != null && SNAPSHOT_LOCATION_PATTERN.matcher(image).matches()) { <del> throw new SourceNotFoundException(e.getLocalizedMessage(), e); <add> throw new SourceNotFoundException(format("Failed to get snapshot image: %s. Cause: %s", <add> image, <add> e.getLocalizedMessage()), <add> e); <ide> } <ide> throw new MachineException(e.getLocalizedMessage(), e); <ide> } catch (IOException e) {
Java
apache-2.0
e7884aec26a67f1fb7d0f7c1fbbce0b97277de14
0
rjcorrig/FreeRDP,DavBfr/FreeRDP,ivan-83/FreeRDP,nfedera/FreeRDP,mfleisz/FreeRDP,yurashek/FreeRDP,erbth/FreeRDP,DavBfr/FreeRDP,chipitsine/FreeRDP,mfleisz/FreeRDP,FreeRDP/FreeRDP,cloudbase/FreeRDP-dev,bjcollins/FreeRDP,chipitsine/FreeRDP,mfleisz/FreeRDP,cloudbase/FreeRDP-dev,chipitsine/FreeRDP,ondrejholy/FreeRDP,cedrozor/FreeRDP,bmiklautz/FreeRDP,ilammy/FreeRDP,DavBfr/FreeRDP,cloudbase/FreeRDP-dev,mfleisz/FreeRDP,cedrozor/FreeRDP,awakecoding/FreeRDP,ilammy/FreeRDP,bmiklautz/FreeRDP,nfedera/FreeRDP,DavBfr/FreeRDP,awakecoding/FreeRDP,chipitsine/FreeRDP,oshogbo/FreeRDP,rjcorrig/FreeRDP,oshogbo/FreeRDP,rjcorrig/FreeRDP,yurashek/FreeRDP,DavBfr/FreeRDP,ondrejholy/FreeRDP,yurashek/FreeRDP,bjcollins/FreeRDP,cloudbase/FreeRDP-dev,eledoux/FreeRDP,akallabeth/FreeRDP,ivan-83/FreeRDP,ilammy/FreeRDP,erbth/FreeRDP,nfedera/FreeRDP,awakecoding/FreeRDP,awakecoding/FreeRDP,awakecoding/FreeRDP,erbth/FreeRDP,DavBfr/FreeRDP,cloudbase/FreeRDP-dev,Devolutions/FreeRDP,ondrejholy/FreeRDP,bmiklautz/FreeRDP,Devolutions/FreeRDP,nfedera/FreeRDP,FreeRDP/FreeRDP,chipitsine/FreeRDP,akallabeth/FreeRDP,mfleisz/FreeRDP,ilammy/FreeRDP,FreeRDP/FreeRDP,bjcollins/FreeRDP,awakecoding/FreeRDP,RangeeGmbH/FreeRDP,erbth/FreeRDP,yurashek/FreeRDP,RangeeGmbH/FreeRDP,ivan-83/FreeRDP,bjcollins/FreeRDP,nfedera/FreeRDP,eledoux/FreeRDP,RangeeGmbH/FreeRDP,DavBfr/FreeRDP,mfleisz/FreeRDP,ilammy/FreeRDP,rjcorrig/FreeRDP,rjcorrig/FreeRDP,eledoux/FreeRDP,ilammy/FreeRDP,ondrejholy/FreeRDP,Devolutions/FreeRDP,rjcorrig/FreeRDP,ondrejholy/FreeRDP,eledoux/FreeRDP,chipitsine/FreeRDP,bmiklautz/FreeRDP,bmiklautz/FreeRDP,oshogbo/FreeRDP,rjcorrig/FreeRDP,bjcollins/FreeRDP,oshogbo/FreeRDP,ivan-83/FreeRDP,awakecoding/FreeRDP,chipitsine/FreeRDP,yurashek/FreeRDP,Devolutions/FreeRDP,Devolutions/FreeRDP,ivan-83/FreeRDP,ondrejholy/FreeRDP,eledoux/FreeRDP,akallabeth/FreeRDP,cedrozor/FreeRDP,RangeeGmbH/FreeRDP,cedrozor/FreeRDP,oshogbo/FreeRDP,bmiklautz/FreeRDP,erbth/FreeRDP,RangeeGmbH/FreeRDP,FreeRDP/FreeRDP,cedrozor/FreeRDP,cedrozor/FreeRDP,ondrejholy/FreeRDP,akallabeth/FreeRDP,FreeRDP/FreeRDP,awakecoding/FreeRDP,erbth/FreeRDP,RangeeGmbH/FreeRDP,akallabeth/FreeRDP,bmiklautz/FreeRDP,eledoux/FreeRDP,ivan-83/FreeRDP,yurashek/FreeRDP,erbth/FreeRDP,akallabeth/FreeRDP,cedrozor/FreeRDP,cloudbase/FreeRDP-dev,yurashek/FreeRDP,akallabeth/FreeRDP,rjcorrig/FreeRDP,cloudbase/FreeRDP-dev,DavBfr/FreeRDP,bmiklautz/FreeRDP,FreeRDP/FreeRDP,bjcollins/FreeRDP,nfedera/FreeRDP,RangeeGmbH/FreeRDP,nfedera/FreeRDP,ilammy/FreeRDP,eledoux/FreeRDP,Devolutions/FreeRDP,oshogbo/FreeRDP,ilammy/FreeRDP,bjcollins/FreeRDP,FreeRDP/FreeRDP,Devolutions/FreeRDP,RangeeGmbH/FreeRDP,oshogbo/FreeRDP,mfleisz/FreeRDP,Devolutions/FreeRDP,FreeRDP/FreeRDP,nfedera/FreeRDP,ivan-83/FreeRDP,yurashek/FreeRDP,ondrejholy/FreeRDP,ivan-83/FreeRDP,eledoux/FreeRDP,erbth/FreeRDP,oshogbo/FreeRDP,chipitsine/FreeRDP,cedrozor/FreeRDP,mfleisz/FreeRDP,bjcollins/FreeRDP,akallabeth/FreeRDP
/* Android FreeRDP JNI Wrapper Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.freerdp.freerdpcore.services; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.support.v4.util.LongSparseArray; import android.util.Log; import com.freerdp.freerdpcore.application.GlobalApp; import com.freerdp.freerdpcore.application.SessionState; import com.freerdp.freerdpcore.domain.BookmarkBase; import com.freerdp.freerdpcore.domain.ManualBookmark; import com.freerdp.freerdpcore.presentation.ApplicationSettingsActivity; import java.util.ArrayList; public class LibFreeRDP { private static final String TAG = "LibFreeRDP"; private static EventListener listener; private static boolean mHasH264 = true; private static final LongSparseArray<Boolean> mInstanceState = new LongSparseArray<>(); static { final String h264 = "openh264"; final String[] libraries = { h264, "freerdp-openssl", "jpeg", "winpr2", "freerdp2", "freerdp-client2", "freerdp-android2"}; final String LD_PATH = System.getProperty("java.library.path"); for (String lib : libraries) { try { Log.v(TAG, "Trying to load library " + lib + " from LD_PATH: " + LD_PATH); System.loadLibrary(lib); } catch (UnsatisfiedLinkError e) { Log.e(TAG, "Failed to load library " + lib + ": " + e.toString()); if (lib.equals(h264)) { mHasH264 = false; } } } } public static boolean hasH264Support() { return mHasH264; } private static native String freerdp_get_jni_version(); private static native String freerdp_get_version(); private static native String freerdp_get_build_date(); private static native String freerdp_get_build_revision(); private static native String freerdp_get_build_config(); private static native long freerdp_new(Context context); private static native void freerdp_free(long inst); private static native boolean freerdp_parse_arguments(long inst, String[] args); private static native boolean freerdp_connect(long inst); private static native boolean freerdp_disconnect(long inst); private static native boolean freerdp_update_graphics(long inst, Bitmap bitmap, int x, int y, int width, int height); private static native boolean freerdp_send_cursor_event(long inst, int x, int y, int flags); private static native boolean freerdp_send_key_event(long inst, int keycode, boolean down); private static native boolean freerdp_send_unicodekey_event(long inst, int keycode); private static native boolean freerdp_send_clipboard_data(long inst, String data); public static void setEventListener(EventListener l) { listener = l; } public static long newInstance(Context context) { return freerdp_new(context); } public static void freeInstance(long inst) { synchronized (mInstanceState) { if (mInstanceState.get(inst, false)) { freerdp_disconnect(inst); } while(mInstanceState.get(inst, false)) { try { mInstanceState.wait(); } catch (InterruptedException e) { throw new RuntimeException(); } } } freerdp_free(inst); } public static boolean connect(long inst) { synchronized (mInstanceState) { if (mInstanceState.get(inst, false)) { throw new RuntimeException("instance already connected"); } } return freerdp_connect(inst); } public static boolean disconnect(long inst) { synchronized (mInstanceState) { if (mInstanceState.get(inst, false)) { return freerdp_disconnect(inst); } return true; } } public static boolean cancelConnection(long inst) { synchronized (mInstanceState) { if (mInstanceState.get(inst, false)) { return freerdp_disconnect(inst); } return true; } } private static String addFlag(String name, boolean enabled) { if (enabled) { return "+" + name; } return "-" + name; } public static boolean setConnectionInfo(Context context, long inst, BookmarkBase bookmark) { BookmarkBase.ScreenSettings screenSettings = bookmark.getActiveScreenSettings(); BookmarkBase.AdvancedSettings advanced = bookmark.getAdvancedSettings(); BookmarkBase.DebugSettings debug = bookmark.getDebugSettings(); String arg; ArrayList<String> args = new ArrayList<String>(); args.add(TAG); args.add("/gdi:sw"); final String clientName = ApplicationSettingsActivity.getClientName(context); if (!clientName.isEmpty()) { args.add("/client-hostname:" + clientName); } String certName = ""; if (bookmark.getType() != BookmarkBase.TYPE_MANUAL) { return false; } int port = bookmark.<ManualBookmark>get().getPort(); String hostname = bookmark.<ManualBookmark>get().getHostname(); args.add("/v:" + hostname); args.add("/port:" + String.valueOf(port)); arg = bookmark.getUsername(); if (!arg.isEmpty()) { args.add("/u:" + arg); } arg = bookmark.getDomain(); if (!arg.isEmpty()) { args.add("/d:" + arg); } arg = bookmark.getPassword(); if (!arg.isEmpty()) { args.add("/p:" + arg); } args.add(String.format("/size:%dx%d", screenSettings.getWidth(), screenSettings.getHeight())); args.add("/bpp:" + String.valueOf(screenSettings.getColors())); if (advanced.getConsoleMode()) { args.add("/admin"); } switch (advanced.getSecurity()) { case 3: // NLA args.add("/sec-nla"); break; case 2: // TLS args.add("/sec-tls"); break; case 1: // RDP args.add("/sec-rdp"); break; default: break; } if (!certName.isEmpty()) { args.add("/cert-name:" + certName); } BookmarkBase.PerformanceFlags flags = bookmark.getActivePerformanceFlags(); if (flags.getRemoteFX()) { args.add("/rfx"); } if (flags.getGfx()) { args.add("/gfx"); } if (flags.getH264() && mHasH264) { args.add("/gfx:AVC444"); } args.add(addFlag("wallpaper", flags.getWallpaper())); args.add(addFlag("window-drag", flags.getFullWindowDrag())); args.add(addFlag("menu-anims", flags.getMenuAnimations())); args.add(addFlag("themes", flags.getTheming())); args.add(addFlag("fonts", flags.getFontSmoothing())); args.add(addFlag("aero", flags.getDesktopComposition())); args.add(addFlag("glyph-cache", false)); if (!advanced.getRemoteProgram().isEmpty()) { args.add("/shell:" + advanced.getRemoteProgram()); } if (!advanced.getWorkDir().isEmpty()) { args.add("/shell-dir:" + advanced.getWorkDir()); } args.add(addFlag("async-channels", debug.getAsyncChannel())); //args.add(addFlag("async-transport", debug.getAsyncTransport())); args.add(addFlag("async-input", debug.getAsyncInput())); args.add(addFlag("async-update", debug.getAsyncUpdate())); if (advanced.getRedirectSDCard()) { String path = android.os.Environment.getExternalStorageDirectory().getPath(); args.add("/drive:sdcard," + path); } args.add("/clipboard"); // Gateway enabled? if (bookmark.getType() == BookmarkBase.TYPE_MANUAL && bookmark.<ManualBookmark>get().getEnableGatewaySettings()) { ManualBookmark.GatewaySettings gateway = bookmark.<ManualBookmark>get().getGatewaySettings(); args.add(String.format("/g:%s:%d", gateway.getHostname(), gateway.getPort())); arg = gateway.getUsername(); if (!arg.isEmpty()) { args.add("/gu:" + arg); } arg = gateway.getDomain(); if (!arg.isEmpty()) { args.add("/gd:" + arg); } arg = gateway.getPassword(); if (!arg.isEmpty()) { args.add("/gp:" + arg); } } /* 0 ... local 1 ... remote 2 ... disable */ args.add("/audio-mode:" + String.valueOf(advanced.getRedirectSound())); if (advanced.getRedirectSound() == 0) { args.add("/sound"); } if (advanced.getRedirectMicrophone()) { args.add("/microphone"); } args.add("/cert-ignore"); args.add("/log-level:" + debug.getDebugLevel()); String[] arrayArgs = args.toArray(new String[args.size()]); return freerdp_parse_arguments(inst, arrayArgs); } public static boolean setConnectionInfo(Context context, long inst, Uri openUri) { ArrayList<String> args = new ArrayList<>(); // Parse URI from query string. Same key overwrite previous one // freerdp://user@ip:port/connect?sound=&rfx=&p=password&clipboard=%2b&themes=- // Now we only support Software GDI args.add(TAG); args.add("/gdi:sw"); final String clientName = ApplicationSettingsActivity.getClientName(context); if (!clientName.isEmpty()) { args.add("/client-hostname:" + clientName); } // Parse hostname and port. Set to 'v' argument String hostname = openUri.getHost(); int port = openUri.getPort(); if (hostname != null) { hostname = hostname + ((port == -1) ? "" : (":" + String.valueOf(port))); args.add("/v:" + hostname); } String user = openUri.getUserInfo(); if (user != null) { args.add("/u:" + user); } for (String key : openUri.getQueryParameterNames()) { String value = openUri.getQueryParameter(key); if (value.isEmpty()) { // Query: key= // To freerdp argument: /key args.add("/" + key); } else if (value.equals("-") || value.equals("+")) { // Query: key=- or key=+ // To freerdp argument: -key or +key args.add(value + key); } else { // Query: key=value // To freerdp argument: /key:value if (key.equals("drive") && value.equals("sdcard")) { // Special for sdcard redirect String path = android.os.Environment.getExternalStorageDirectory().getPath(); value = "sdcard," + path; } args.add("/" + key + ":" + value); } } String[] arrayArgs = args.toArray(new String[args.size()]); return freerdp_parse_arguments(inst, arrayArgs); } public static boolean updateGraphics(long inst, Bitmap bitmap, int x, int y, int width, int height) { return freerdp_update_graphics(inst, bitmap, x, y, width, height); } public static boolean sendCursorEvent(long inst, int x, int y, int flags) { return freerdp_send_cursor_event(inst, x, y, flags); } public static boolean sendKeyEvent(long inst, int keycode, boolean down) { return freerdp_send_key_event(inst, keycode, down); } public static boolean sendUnicodeKeyEvent(long inst, int keycode) { return freerdp_send_unicodekey_event(inst, keycode); } public static boolean sendClipboardData(long inst, String data) { return freerdp_send_clipboard_data(inst, data); } private static void OnConnectionSuccess(long inst) { if (listener != null) listener.OnConnectionSuccess(inst); synchronized (mInstanceState) { mInstanceState.append(inst, true); mInstanceState.notifyAll(); } } private static void OnConnectionFailure(long inst) { if (listener != null) listener.OnConnectionFailure(inst); } private static void OnPreConnect(long inst) { if (listener != null) listener.OnPreConnect(inst); } private static void OnDisconnecting(long inst) { if (listener != null) listener.OnDisconnecting(inst); synchronized (mInstanceState) { mInstanceState.remove(inst); mInstanceState.notifyAll(); } } private static void OnDisconnected(long inst) { if (listener != null) listener.OnDisconnected(inst); } private static void OnSettingsChanged(long inst, int width, int height, int bpp) { SessionState s = GlobalApp.getSession(inst); if (s == null) return; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) uiEventListener.OnSettingsChanged(width, height, bpp); } private static boolean OnAuthenticate(long inst, StringBuilder username, StringBuilder domain, StringBuilder password) { SessionState s = GlobalApp.getSession(inst); if (s == null) return false; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) return uiEventListener.OnAuthenticate(username, domain, password); return false; } private static boolean OnGatewayAuthenticate(long inst, StringBuilder username, StringBuilder domain, StringBuilder password) { SessionState s = GlobalApp.getSession(inst); if (s == null) return false; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) return uiEventListener.OnGatewayAuthenticate(username, domain, password); return false; } private static int OnVerifyCertificate(long inst, String commonName, String subject, String issuer, String fingerprint, boolean hostMismatch) { SessionState s = GlobalApp.getSession(inst); if (s == null) return 0; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) return uiEventListener.OnVerifiyCertificate(commonName, subject, issuer, fingerprint, hostMismatch); return 0; } private static int OnVerifyChangedCertificate(long inst, String commonName, String subject, String issuer, String fingerprint, String oldSubject, String oldIssuer, String oldFingerprint) { SessionState s = GlobalApp.getSession(inst); if (s == null) return 0; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) return uiEventListener.OnVerifyChangedCertificate(commonName, subject, issuer, fingerprint, oldSubject, oldIssuer, oldFingerprint); return 0; } private static void OnGraphicsUpdate(long inst, int x, int y, int width, int height) { SessionState s = GlobalApp.getSession(inst); if (s == null) return; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) uiEventListener.OnGraphicsUpdate(x, y, width, height); } private static void OnGraphicsResize(long inst, int width, int height, int bpp) { SessionState s = GlobalApp.getSession(inst); if (s == null) return; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) uiEventListener.OnGraphicsResize(width, height, bpp); } private static void OnRemoteClipboardChanged(long inst, String data) { SessionState s = GlobalApp.getSession(inst); if (s == null) return; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) uiEventListener.OnRemoteClipboardChanged(data); } public static String getVersion() { return freerdp_get_version(); } public static interface EventListener { void OnPreConnect(long instance); void OnConnectionSuccess(long instance); void OnConnectionFailure(long instance); void OnDisconnecting(long instance); void OnDisconnected(long instance); } public static interface UIEventListener { void OnSettingsChanged(int width, int height, int bpp); boolean OnAuthenticate(StringBuilder username, StringBuilder domain, StringBuilder password); boolean OnGatewayAuthenticate(StringBuilder username, StringBuilder domain, StringBuilder password); int OnVerifiyCertificate(String commonName, String subject, String issuer, String fingerprint, boolean mismatch); int OnVerifyChangedCertificate(String commonName, String subject, String issuer, String fingerprint, String oldSubject, String oldIssuer, String oldFingerprint); void OnGraphicsUpdate(int x, int y, int width, int height); void OnGraphicsResize(int width, int height, int bpp); void OnRemoteClipboardChanged(String data); } }
client/Android/Studio/freeRDPCore/src/main/java/com/freerdp/freerdpcore/services/LibFreeRDP.java
/* Android FreeRDP JNI Wrapper Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.freerdp.freerdpcore.services; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.support.v4.util.LongSparseArray; import android.util.Log; import com.freerdp.freerdpcore.application.GlobalApp; import com.freerdp.freerdpcore.application.SessionState; import com.freerdp.freerdpcore.domain.BookmarkBase; import com.freerdp.freerdpcore.domain.ManualBookmark; import com.freerdp.freerdpcore.presentation.ApplicationSettingsActivity; import java.util.ArrayList; public class LibFreeRDP { private static final String TAG = "LibFreeRDP"; private static EventListener listener; private static boolean mHasH264 = true; private static final LongSparseArray<Boolean> mInstanceState = new LongSparseArray<>(); static { final String h264 = "openh264"; final String[] libraries = { h264, "freerdp-openssl", "jpeg", "winpr2", "freerdp2", "freerdp-client2", "freerdp-android2"}; final String LD_PATH = System.getProperty("java.library.path"); for (String lib : libraries) { try { Log.v(TAG, "Trying to load library " + lib + " from LD_PATH: " + LD_PATH); System.loadLibrary(lib); } catch (UnsatisfiedLinkError e) { Log.e(TAG, "Failed to load library " + lib + ": " + e.toString()); if (lib.equals(h264)) { mHasH264 = false; } } } } public static boolean hasH264Support() { return mHasH264; } private static native String freerdp_get_jni_version(); private static native String freerdp_get_version(); private static native String freerdp_get_build_date(); private static native String freerdp_get_build_revision(); private static native String freerdp_get_build_config(); private static native long freerdp_new(Context context); private static native void freerdp_free(long inst); private static native boolean freerdp_parse_arguments(long inst, String[] args); private static native boolean freerdp_connect(long inst); private static native boolean freerdp_disconnect(long inst); private static native boolean freerdp_update_graphics(long inst, Bitmap bitmap, int x, int y, int width, int height); private static native boolean freerdp_send_cursor_event(long inst, int x, int y, int flags); private static native boolean freerdp_send_key_event(long inst, int keycode, boolean down); private static native boolean freerdp_send_unicodekey_event(long inst, int keycode); private static native boolean freerdp_send_clipboard_data(long inst, String data); public static void setEventListener(EventListener l) { listener = l; } public static long newInstance(Context context) { return freerdp_new(context); } public static void freeInstance(long inst) { synchronized (mInstanceState) { if (mInstanceState.get(inst, false)) { freerdp_disconnect(inst); } while(mInstanceState.get(inst)) { try { mInstanceState.wait(); } catch (InterruptedException e) { throw new RuntimeException(); } } } freerdp_free(inst); } public static boolean connect(long inst) { synchronized (mInstanceState) { if (mInstanceState.get(inst, false)) { throw new RuntimeException("instance already connected"); } } return freerdp_connect(inst); } public static boolean disconnect(long inst) { synchronized (mInstanceState) { if (mInstanceState.get(inst)) { return freerdp_disconnect(inst); } return true; } } public static boolean cancelConnection(long inst) { synchronized (mInstanceState) { if (mInstanceState.get(inst)) { return freerdp_disconnect(inst); } return true; } } private static String addFlag(String name, boolean enabled) { if (enabled) { return "+" + name; } return "-" + name; } public static boolean setConnectionInfo(Context context, long inst, BookmarkBase bookmark) { BookmarkBase.ScreenSettings screenSettings = bookmark.getActiveScreenSettings(); BookmarkBase.AdvancedSettings advanced = bookmark.getAdvancedSettings(); BookmarkBase.DebugSettings debug = bookmark.getDebugSettings(); String arg; ArrayList<String> args = new ArrayList<String>(); args.add(TAG); args.add("/gdi:sw"); final String clientName = ApplicationSettingsActivity.getClientName(context); if (!clientName.isEmpty()) { args.add("/client-hostname:" + clientName); } String certName = ""; if (bookmark.getType() != BookmarkBase.TYPE_MANUAL) { return false; } int port = bookmark.<ManualBookmark>get().getPort(); String hostname = bookmark.<ManualBookmark>get().getHostname(); args.add("/v:" + hostname); args.add("/port:" + String.valueOf(port)); arg = bookmark.getUsername(); if (!arg.isEmpty()) { args.add("/u:" + arg); } arg = bookmark.getDomain(); if (!arg.isEmpty()) { args.add("/d:" + arg); } arg = bookmark.getPassword(); if (!arg.isEmpty()) { args.add("/p:" + arg); } args.add(String.format("/size:%dx%d", screenSettings.getWidth(), screenSettings.getHeight())); args.add("/bpp:" + String.valueOf(screenSettings.getColors())); if (advanced.getConsoleMode()) { args.add("/admin"); } switch (advanced.getSecurity()) { case 3: // NLA args.add("/sec-nla"); break; case 2: // TLS args.add("/sec-tls"); break; case 1: // RDP args.add("/sec-rdp"); break; default: break; } if (!certName.isEmpty()) { args.add("/cert-name:" + certName); } BookmarkBase.PerformanceFlags flags = bookmark.getActivePerformanceFlags(); if (flags.getRemoteFX()) { args.add("/rfx"); } if (flags.getGfx()) { args.add("/gfx"); } if (flags.getH264() && mHasH264) { args.add("/gfx:AVC444"); } args.add(addFlag("wallpaper", flags.getWallpaper())); args.add(addFlag("window-drag", flags.getFullWindowDrag())); args.add(addFlag("menu-anims", flags.getMenuAnimations())); args.add(addFlag("themes", flags.getTheming())); args.add(addFlag("fonts", flags.getFontSmoothing())); args.add(addFlag("aero", flags.getDesktopComposition())); args.add(addFlag("glyph-cache", false)); if (!advanced.getRemoteProgram().isEmpty()) { args.add("/shell:" + advanced.getRemoteProgram()); } if (!advanced.getWorkDir().isEmpty()) { args.add("/shell-dir:" + advanced.getWorkDir()); } args.add(addFlag("async-channels", debug.getAsyncChannel())); //args.add(addFlag("async-transport", debug.getAsyncTransport())); args.add(addFlag("async-input", debug.getAsyncInput())); args.add(addFlag("async-update", debug.getAsyncUpdate())); if (advanced.getRedirectSDCard()) { String path = android.os.Environment.getExternalStorageDirectory().getPath(); args.add("/drive:sdcard," + path); } args.add("/clipboard"); // Gateway enabled? if (bookmark.getType() == BookmarkBase.TYPE_MANUAL && bookmark.<ManualBookmark>get().getEnableGatewaySettings()) { ManualBookmark.GatewaySettings gateway = bookmark.<ManualBookmark>get().getGatewaySettings(); args.add(String.format("/g:%s:%d", gateway.getHostname(), gateway.getPort())); arg = gateway.getUsername(); if (!arg.isEmpty()) { args.add("/gu:" + arg); } arg = gateway.getDomain(); if (!arg.isEmpty()) { args.add("/gd:" + arg); } arg = gateway.getPassword(); if (!arg.isEmpty()) { args.add("/gp:" + arg); } } /* 0 ... local 1 ... remote 2 ... disable */ args.add("/audio-mode:" + String.valueOf(advanced.getRedirectSound())); if (advanced.getRedirectSound() == 0) { args.add("/sound"); } if (advanced.getRedirectMicrophone()) { args.add("/microphone"); } args.add("/cert-ignore"); args.add("/log-level:" + debug.getDebugLevel()); String[] arrayArgs = args.toArray(new String[args.size()]); return freerdp_parse_arguments(inst, arrayArgs); } public static boolean setConnectionInfo(Context context, long inst, Uri openUri) { ArrayList<String> args = new ArrayList<>(); // Parse URI from query string. Same key overwrite previous one // freerdp://user@ip:port/connect?sound=&rfx=&p=password&clipboard=%2b&themes=- // Now we only support Software GDI args.add(TAG); args.add("/gdi:sw"); final String clientName = ApplicationSettingsActivity.getClientName(context); if (!clientName.isEmpty()) { args.add("/client-hostname:" + clientName); } // Parse hostname and port. Set to 'v' argument String hostname = openUri.getHost(); int port = openUri.getPort(); if (hostname != null) { hostname = hostname + ((port == -1) ? "" : (":" + String.valueOf(port))); args.add("/v:" + hostname); } String user = openUri.getUserInfo(); if (user != null) { args.add("/u:" + user); } for (String key : openUri.getQueryParameterNames()) { String value = openUri.getQueryParameter(key); if (value.isEmpty()) { // Query: key= // To freerdp argument: /key args.add("/" + key); } else if (value.equals("-") || value.equals("+")) { // Query: key=- or key=+ // To freerdp argument: -key or +key args.add(value + key); } else { // Query: key=value // To freerdp argument: /key:value if (key.equals("drive") && value.equals("sdcard")) { // Special for sdcard redirect String path = android.os.Environment.getExternalStorageDirectory().getPath(); value = "sdcard," + path; } args.add("/" + key + ":" + value); } } String[] arrayArgs = args.toArray(new String[args.size()]); return freerdp_parse_arguments(inst, arrayArgs); } public static boolean updateGraphics(long inst, Bitmap bitmap, int x, int y, int width, int height) { return freerdp_update_graphics(inst, bitmap, x, y, width, height); } public static boolean sendCursorEvent(long inst, int x, int y, int flags) { return freerdp_send_cursor_event(inst, x, y, flags); } public static boolean sendKeyEvent(long inst, int keycode, boolean down) { return freerdp_send_key_event(inst, keycode, down); } public static boolean sendUnicodeKeyEvent(long inst, int keycode) { return freerdp_send_unicodekey_event(inst, keycode); } public static boolean sendClipboardData(long inst, String data) { return freerdp_send_clipboard_data(inst, data); } private static void OnConnectionSuccess(long inst) { if (listener != null) listener.OnConnectionSuccess(inst); synchronized (mInstanceState) { mInstanceState.append(inst, true); mInstanceState.notifyAll(); } } private static void OnConnectionFailure(long inst) { if (listener != null) listener.OnConnectionFailure(inst); } private static void OnPreConnect(long inst) { if (listener != null) listener.OnPreConnect(inst); } private static void OnDisconnecting(long inst) { if (listener != null) listener.OnDisconnecting(inst); synchronized (mInstanceState) { mInstanceState.remove(inst); mInstanceState.notifyAll(); } } private static void OnDisconnected(long inst) { if (listener != null) listener.OnDisconnected(inst); } private static void OnSettingsChanged(long inst, int width, int height, int bpp) { SessionState s = GlobalApp.getSession(inst); if (s == null) return; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) uiEventListener.OnSettingsChanged(width, height, bpp); } private static boolean OnAuthenticate(long inst, StringBuilder username, StringBuilder domain, StringBuilder password) { SessionState s = GlobalApp.getSession(inst); if (s == null) return false; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) return uiEventListener.OnAuthenticate(username, domain, password); return false; } private static boolean OnGatewayAuthenticate(long inst, StringBuilder username, StringBuilder domain, StringBuilder password) { SessionState s = GlobalApp.getSession(inst); if (s == null) return false; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) return uiEventListener.OnGatewayAuthenticate(username, domain, password); return false; } private static int OnVerifyCertificate(long inst, String commonName, String subject, String issuer, String fingerprint, boolean hostMismatch) { SessionState s = GlobalApp.getSession(inst); if (s == null) return 0; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) return uiEventListener.OnVerifiyCertificate(commonName, subject, issuer, fingerprint, hostMismatch); return 0; } private static int OnVerifyChangedCertificate(long inst, String commonName, String subject, String issuer, String fingerprint, String oldSubject, String oldIssuer, String oldFingerprint) { SessionState s = GlobalApp.getSession(inst); if (s == null) return 0; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) return uiEventListener.OnVerifyChangedCertificate(commonName, subject, issuer, fingerprint, oldSubject, oldIssuer, oldFingerprint); return 0; } private static void OnGraphicsUpdate(long inst, int x, int y, int width, int height) { SessionState s = GlobalApp.getSession(inst); if (s == null) return; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) uiEventListener.OnGraphicsUpdate(x, y, width, height); } private static void OnGraphicsResize(long inst, int width, int height, int bpp) { SessionState s = GlobalApp.getSession(inst); if (s == null) return; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) uiEventListener.OnGraphicsResize(width, height, bpp); } private static void OnRemoteClipboardChanged(long inst, String data) { SessionState s = GlobalApp.getSession(inst); if (s == null) return; UIEventListener uiEventListener = s.getUIEventListener(); if (uiEventListener != null) uiEventListener.OnRemoteClipboardChanged(data); } public static String getVersion() { return freerdp_get_version(); } public static interface EventListener { void OnPreConnect(long instance); void OnConnectionSuccess(long instance); void OnConnectionFailure(long instance); void OnDisconnecting(long instance); void OnDisconnected(long instance); } public static interface UIEventListener { void OnSettingsChanged(int width, int height, int bpp); boolean OnAuthenticate(StringBuilder username, StringBuilder domain, StringBuilder password); boolean OnGatewayAuthenticate(StringBuilder username, StringBuilder domain, StringBuilder password); int OnVerifiyCertificate(String commonName, String subject, String issuer, String fingerprint, boolean mismatch); int OnVerifyChangedCertificate(String commonName, String subject, String issuer, String fingerprint, String oldSubject, String oldIssuer, String oldFingerprint); void OnGraphicsUpdate(int x, int y, int width, int height); void OnGraphicsResize(int width, int height, int bpp); void OnRemoteClipboardChanged(String data); } }
Added default return if instance not in list.
client/Android/Studio/freeRDPCore/src/main/java/com/freerdp/freerdpcore/services/LibFreeRDP.java
Added default return if instance not in list.
<ide><path>lient/Android/Studio/freeRDPCore/src/main/java/com/freerdp/freerdpcore/services/LibFreeRDP.java <ide> if (mInstanceState.get(inst, false)) { <ide> freerdp_disconnect(inst); <ide> } <del> while(mInstanceState.get(inst)) { <add> while(mInstanceState.get(inst, false)) { <ide> try { <ide> mInstanceState.wait(); <ide> } catch (InterruptedException e) { <ide> <ide> public static boolean disconnect(long inst) { <ide> synchronized (mInstanceState) { <del> if (mInstanceState.get(inst)) { <add> if (mInstanceState.get(inst, false)) { <ide> return freerdp_disconnect(inst); <ide> } <ide> return true; <ide> <ide> public static boolean cancelConnection(long inst) { <ide> synchronized (mInstanceState) { <del> if (mInstanceState.get(inst)) { <add> if (mInstanceState.get(inst, false)) { <ide> return freerdp_disconnect(inst); <ide> } <ide> return true;
Java
apache-2.0
c5ac1e89218f13022a1721bfe0d0cdc9aed6afb5
0
finmath/finmath-lib,finmath/finmath-lib
/* * (c) Copyright Christian P. Fries, Germany. Contact: [email protected]. * * Created on 23.02.2004 */ package net.finmath.functions; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.linear.DecompositionSolver; import org.apache.commons.math3.linear.EigenDecomposition; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.QRDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.SingularValueDecomposition; /** * This class implements some methods from linear algebra (e.g. solution of a linear equation, PCA). * * It is basically a functional wrapper using either the Apache commons math or JBlas * * @author Christian Fries * @version 1.6 */ public class LinearAlgebra { private static boolean isEigenvalueDecompositionViaSVD = Boolean.parseBoolean(System.getProperty("net.finmath.functions.LinearAlgebra.isEigenvalueDecompositionViaSVD","false")); private static boolean isSolverUseApacheCommonsMath; private static boolean isJBlasAvailable; static { // Default value is true, in which case we will NOT use jblas boolean isSolverUseApacheCommonsMath = Boolean.parseBoolean(System.getProperty("net.finmath.functions.LinearAlgebra.isUseApacheCommonsMath","true")); /* * Check if jblas is available */ if(!isSolverUseApacheCommonsMath) { try { double[] x = org.jblas.Solve.solve(new org.jblas.DoubleMatrix(2, 2, 1.0, 1.0, 0.0, 1.0), new org.jblas.DoubleMatrix(2, 1, 1.0, 1.0)).data; // The following should not happen. if(x[0] != 1.0 || x[1] != 0.0) { isJBlasAvailable = false; } else { isJBlasAvailable = true; } } catch(java.lang.UnsatisfiedLinkError e) { isJBlasAvailable = false; } } if(!isJBlasAvailable) isSolverUseApacheCommonsMath = true; LinearAlgebra.isSolverUseApacheCommonsMath = isSolverUseApacheCommonsMath; } /** * Find a solution of the linear equation A x = b where * <ul> * <li>A is an n x m - matrix given as double[n][m]</li> * <li>b is an m - vector given as double[m],</li> * <li>x is an n - vector given as double[n],</li> * </ul> * * @param matrixA The matrix A (left hand side of the linear equation). * @param b The vector (right hand of the linear equation). * @return A solution x to A x = b. */ public static double[] solveLinearEquation(double[][] matrixA, double[] b) { if(isSolverUseApacheCommonsMath) { Array2DRowRealMatrix matrix = new Array2DRowRealMatrix(matrixA); DecompositionSolver solver; if(matrix.getColumnDimension() == matrix.getRowDimension()) { solver = new LUDecomposition(matrix).getSolver(); } else { solver = new QRDecomposition(new Array2DRowRealMatrix(matrixA)).getSolver(); } // Using SVD - very slow // solver = new SingularValueDecomposition(new Array2DRowRealMatrix(A)).getSolver(); return solver.solve(new Array2DRowRealMatrix(b)).getColumn(0); } else { return org.jblas.Solve.solve(new org.jblas.DoubleMatrix(matrixA), new org.jblas.DoubleMatrix(b)).data; // For use of colt: // cern.colt.matrix.linalg.Algebra linearAlgebra = new cern.colt.matrix.linalg.Algebra(); // return linearAlgebra.solve(new DenseDoubleMatrix2D(A), linearAlgebra.transpose(new DenseDoubleMatrix2D(new double[][] { b }))).viewColumn(0).toArray(); // For use of parallel colt: // return new cern.colt.matrix.tdouble.algo.decomposition.DenseDoubleLUDecomposition(new cern.colt.matrix.tdouble.impl.DenseDoubleMatrix2D(A)).solve(new cern.colt.matrix.tdouble.impl.DenseDoubleMatrix1D(b)).toArray(); } } /** * Returns the inverse of a given matrix. * * @param matrix A matrix given as double[n][n]. * @return The inverse of the given matrix. */ public static double[][] invert(double[][] matrix) { if(isSolverUseApacheCommonsMath) { // Use LU from common math LUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix)); double[][] matrixInverse = lu.getSolver().getInverse().getData(); return matrixInverse; } else { return org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2(); } } /** * Find a solution of the linear equation A x = b where * <ul> * <li>A is an symmetric n x n - matrix given as double[n][n]</li> * <li>b is an n - vector given as double[n],</li> * <li>x is an n - vector given as double[n],</li> * </ul> * * @param matrix The matrix A (left hand side of the linear equation). * @param vector The vector b (right hand of the linear equation). * @return A solution x to A x = b. */ public static double[] solveLinearEquationSymmetric(double[][] matrix, double[] vector) { if(isSolverUseApacheCommonsMath) { DecompositionSolver solver = new LUDecomposition(new Array2DRowRealMatrix(matrix)).getSolver(); return solver.solve(new Array2DRowRealMatrix(vector)).getColumn(0); } else { return org.jblas.Solve.solveSymmetric(new org.jblas.DoubleMatrix(matrix), new org.jblas.DoubleMatrix(vector)).data; /* To use the linear algebra package colt from cern. cern.colt.matrix.linalg.Algebra linearAlgebra = new cern.colt.matrix.linalg.Algebra(); double[] x = linearAlgebra.solve(new DenseDoubleMatrix2D(A), linearAlgebra.transpose(new DenseDoubleMatrix2D(new double[][] { b }))).viewColumn(0).toArray(); return x; */ } } /** * Find a solution of the linear equation A x = b in the least square sense where * <ul> * <li>A is an n x m - matrix given as double[n][m]</li> * <li>b is an m - vector given as double[m],</li> * <li>x is an n - vector given as double[n],</li> * </ul> * * @param matrix The matrix A (left hand side of the linear equation). * @param vector The vector b (right hand of the linear equation). * @return A solution x to A x = b. */ public static double[] solveLinearEquationLeastSquare(double[][] matrix, double[] vector) { // We use the linear algebra package apache commons math DecompositionSolver solver = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix, false)).getSolver(); return solver.solve(new ArrayRealVector(vector)).toArray(); } /** * Find a solution of the linear equation A X = B in the least square sense where * <ul> * <li>A is an n x m - matrix given as double[n][m]</li> * <li>B is an m x k - matrix given as double[m][k],</li> * <li>X is an n x k - matrix given as double[n][k],</li> * </ul> * * @param matrix The matrix A (left hand side of the linear equation). * @param rhs The matrix B (right hand of the linear equation). * @return A solution X to A X = B. */ public static double[][] solveLinearEquationLeastSquare(double[][] matrix, double[][] rhs) { // We use the linear algebra package apache commons math DecompositionSolver solver = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix, false)).getSolver(); return solver.solve(new Array2DRowRealMatrix(rhs)).getData(); } /** * Returns the matrix of the n Eigenvectors corresponding to the first n largest Eigenvalues of a correlation matrix. * These Eigenvectors can also be interpreted as "principal components" (i.e., the method implements the PCA). * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (eigenvectors). * @return Matrix of n Eigenvectors (columns) (matrix is given as double[n][numberOfFactors], where n is the number of rows of the correlationMatrix. */ public static double[][] getFactorMatrix(double[][] correlationMatrix, int numberOfFactors) { return getFactorMatrixUsingCommonsMath(correlationMatrix, numberOfFactors); } /** * Returns a correlation matrix which has rank &lt; n and for which the first n factors agree with the factors of correlationMatrix. * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (Eigenvectors). * @return Factor reduced correlation matrix. */ public static double[][] factorReduction(double[][] correlationMatrix, int numberOfFactors) { return factorReductionUsingCommonsMath(correlationMatrix, numberOfFactors); } /** * Returns the matrix of the n Eigenvectors corresponding to the first n largest Eigenvalues of a correlation matrix. * These eigenvectors can also be interpreted as "principal components" (i.e., the method implements the PCA). * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (Eigenvectors). * @return Matrix of n Eigenvectors (columns) (matrix is given as double[n][numberOfFactors], where n is the number of rows of the correlationMatrix. */ private static double[][] getFactorMatrixUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { /* * Factor reduction */ // Create an eigen vector decomposition of the correlation matrix double[] eigenValues; double[][] eigenVectorMatrix; if(isEigenvalueDecompositionViaSVD) { SingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(correlationMatrix)); eigenValues = svd.getSingularValues(); eigenVectorMatrix = svd.getV().getData(); } else { EigenDecomposition eigenDecomp = new EigenDecomposition(new Array2DRowRealMatrix(correlationMatrix, false)); eigenValues = eigenDecomp.getRealEigenvalues(); eigenVectorMatrix = eigenDecomp.getV().getData(); } class EigenValueIndex implements Comparable<EigenValueIndex> { private int index; private Double value; EigenValueIndex(int index, double value) { this.index = index; this.value = value; } @Override public int compareTo(EigenValueIndex o) { return o.value.compareTo(value); } } List<EigenValueIndex> eigenValueIndices = new ArrayList<>(); for(int i=0; i<eigenValues.length; i++) { eigenValueIndices.add(i,new EigenValueIndex(i,eigenValues[i])); } Collections.sort(eigenValueIndices); // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = new double[eigenValues.length][numberOfFactors]; for (int factor = 0; factor < numberOfFactors; factor++) { int eigenVectorIndex = eigenValueIndices.get(factor).index; double eigenValue = eigenValues[eigenVectorIndex]; double signChange = eigenVectorMatrix[0][eigenVectorIndex] > 0.0 ? 1.0 : -1.0; // Convention: Have first entry of eigenvector positive. This is to make results more consistent. double eigenVectorNormSquared = 0.0; for (int row = 0; row < eigenValues.length; row++) { eigenVectorNormSquared += eigenVectorMatrix[row][eigenVectorIndex] * eigenVectorMatrix[row][eigenVectorIndex]; } eigenValue = Math.max(eigenValue,0.0); for (int row = 0; row < eigenValues.length; row++) { factorMatrix[row][factor] = signChange * Math.sqrt(eigenValue/eigenVectorNormSquared) * eigenVectorMatrix[row][eigenVectorIndex]; } } return factorMatrix; } /** * Returns a correlation matrix which has rank &lt; n and for which the first n factors agree with the factors of correlationMatrix. * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (Eigenvectors). * @return Factor reduced correlation matrix. */ public static double[][] factorReductionUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = getFactorMatrix(correlationMatrix, numberOfFactors); // Renormalize rows for (int row = 0; row < correlationMatrix.length; row++) { double sumSquared = 0; for (int factor = 0; factor < numberOfFactors; factor++) { sumSquared += factorMatrix[row][factor] * factorMatrix[row][factor]; } if(sumSquared != 0) { for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = factorMatrix[row][factor] / Math.sqrt(sumSquared); } } else { // This is a rare case: The factor reduction of a completely decorrelated system to 1 factor for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = 1.0; } } } // Orthogonalized again double[][] reducedCorrelationMatrix = (new Array2DRowRealMatrix(factorMatrix).multiply(new Array2DRowRealMatrix(factorMatrix).transpose())).getData(); return getFactorMatrix(reducedCorrelationMatrix, numberOfFactors); } /** * Calculate the "matrix exponential" (expm). * * Note: The function currently requires jblas. If jblas is not availabe on your system, an exception will be thrown. * A future version of this function may implement a fall back. * * @param matrix The given matrix. * @return The exp(matrix). */ public double[][] exp(double[][] matrix) { return org.jblas.MatrixFunctions.expm(new org.jblas.DoubleMatrix(matrix)).toArray2(); } /** * Calculate the "matrix exponential" (expm). * * Note: The function currently requires jblas. If jblas is not availabe on your system, an exception will be thrown. * A future version of this function may implement a fall back. * * @param matrix The given matrix. * @return The exp(matrix). */ public RealMatrix exp(RealMatrix matrix) { return new Array2DRowRealMatrix(exp(matrix.getData())); } /** * Transpose a matrix * * @param matrix The given matrix. * @return The transposed matrix. */ public static double[][] transpose(double[][] matrix){ //Get number of rows and columns of matrix int numberOfRows = matrix.length; int numberOfCols = matrix[0].length; //Instantiate a unitMatrix of dimension dim double[][] transpose = new double[numberOfCols][numberOfRows]; //Create unit matrix for(int rowIndex = 0; rowIndex < numberOfRows; rowIndex++) { for(int colIndex = 0; colIndex < numberOfCols; colIndex++) { transpose[colIndex][rowIndex] = matrix[rowIndex][colIndex]; } } return transpose; } /** * Pseudo-Inverse of a matrix calculated in the least square sense. * * @param matrix The given matrix A. * @return pseudoInverse The pseudo-inverse matrix P, such that A*P*A = A and P*A*P = P */ public static double[][] pseudoInverse(double[][] matrix){ return invert(matrix); } /** * Generates a diagonal matrix with the input vector on its diagonal * * @param vector The given matrix A. * @return diagonalMatrix The matrix with the vectors entries on its diagonal */ public static double[][] diag(double[] vector){ // Note: According to the Java Language spec, an array is initialized with the default value, here 0. double[][] diagonalMatrix = new double[vector.length][vector.length]; for(int index = 0; index < vector.length; index++) { diagonalMatrix[index][index] = vector[index]; } return diagonalMatrix; } /** * Multiplication of two matrices. * * @param left The matrix A. * @param right The matrix B * @return product The matrix product of A*B (if suitable) */ public static double[][] multMatrices(double[][] left, double[][] right){ if(isSolverUseApacheCommonsMath) { return new Array2DRowRealMatrix(left).multiply(new Array2DRowRealMatrix(right)).getData(); } else { return new org.jblas.DoubleMatrix(left).mmul(new org.jblas.DoubleMatrix(right)).toArray2(); } } }
src/main/java/net/finmath/functions/LinearAlgebra.java
/* * (c) Copyright Christian P. Fries, Germany. Contact: [email protected]. * * Created on 23.02.2004 */ package net.finmath.functions; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.linear.DecompositionSolver; import org.apache.commons.math3.linear.EigenDecomposition; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.QRDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.SingularValueDecomposition; /** * This class implements some methods from linear algebra (e.g. solution of a linear equation, PCA). * * It is basically a functional wrapper using either the Apache commons math or JBlas * * @author Christian Fries * @version 1.6 */ public class LinearAlgebra { private static boolean isEigenvalueDecompositionViaSVD = Boolean.parseBoolean(System.getProperty("net.finmath.functions.LinearAlgebra.isEigenvalueDecompositionViaSVD","false")); private static boolean isSolverUseApacheCommonsMath; private static boolean isJBlasAvailable; static { // Default value is true, in which case we will NOT use jblas boolean isSolverUseApacheCommonsMath = Boolean.parseBoolean(System.getProperty("net.finmath.functions.LinearAlgebra.isUseApacheCommonsMath","true")); /* * Check if jblas is available */ if(!isSolverUseApacheCommonsMath) { try { double[] x = org.jblas.Solve.solve(new org.jblas.DoubleMatrix(2, 2, 1.0, 1.0, 0.0, 1.0), new org.jblas.DoubleMatrix(2, 1, 1.0, 1.0)).data; // The following should not happen. if(x[0] != 1.0 || x[1] != 0.0) { isJBlasAvailable = false; } else { isJBlasAvailable = true; } } catch(java.lang.UnsatisfiedLinkError e) { isJBlasAvailable = false; } } if(!isJBlasAvailable) isSolverUseApacheCommonsMath = true; LinearAlgebra.isSolverUseApacheCommonsMath = isSolverUseApacheCommonsMath; } /** * Find a solution of the linear equation A x = b where * <ul> * <li>A is an n x m - matrix given as double[n][m]</li> * <li>b is an m - vector given as double[m],</li> * <li>x is an n - vector given as double[n],</li> * </ul> * * @param matrixA The matrix A (left hand side of the linear equation). * @param b The vector (right hand of the linear equation). * @return A solution x to A x = b. */ public static double[] solveLinearEquation(double[][] matrixA, double[] b) { if(isSolverUseApacheCommonsMath) { Array2DRowRealMatrix matrix = new Array2DRowRealMatrix(matrixA); DecompositionSolver solver; if(matrix.getColumnDimension() == matrix.getRowDimension()) { solver = new LUDecomposition(matrix).getSolver(); } else { solver = new QRDecomposition(new Array2DRowRealMatrix(matrixA)).getSolver(); } // Using SVD - very slow // solver = new SingularValueDecomposition(new Array2DRowRealMatrix(A)).getSolver(); return solver.solve(new Array2DRowRealMatrix(b)).getColumn(0); } else { return org.jblas.Solve.solve(new org.jblas.DoubleMatrix(matrixA), new org.jblas.DoubleMatrix(b)).data; // For use of colt: // cern.colt.matrix.linalg.Algebra linearAlgebra = new cern.colt.matrix.linalg.Algebra(); // return linearAlgebra.solve(new DenseDoubleMatrix2D(A), linearAlgebra.transpose(new DenseDoubleMatrix2D(new double[][] { b }))).viewColumn(0).toArray(); // For use of parallel colt: // return new cern.colt.matrix.tdouble.algo.decomposition.DenseDoubleLUDecomposition(new cern.colt.matrix.tdouble.impl.DenseDoubleMatrix2D(A)).solve(new cern.colt.matrix.tdouble.impl.DenseDoubleMatrix1D(b)).toArray(); } } /** * Returns the inverse of a given matrix. * * @param matrix A matrix given as double[n][n]. * @return The inverse of the given matrix. */ public static double[][] invert(double[][] matrix) { if(isSolverUseApacheCommonsMath) { // Use LU from common math LUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix)); double[][] matrixInverse = lu.getSolver().getInverse().getData(); return matrixInverse; } else { return org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2(); } } /** * Find a solution of the linear equation A x = b where * <ul> * <li>A is an symmetric n x n - matrix given as double[n][n]</li> * <li>b is an n - vector given as double[n],</li> * <li>x is an n - vector given as double[n],</li> * </ul> * * @param matrix The matrix A (left hand side of the linear equation). * @param vector The vector b (right hand of the linear equation). * @return A solution x to A x = b. */ public static double[] solveLinearEquationSymmetric(double[][] matrix, double[] vector) { if(isSolverUseApacheCommonsMath) { DecompositionSolver solver = new LUDecomposition(new Array2DRowRealMatrix(matrix)).getSolver(); return solver.solve(new Array2DRowRealMatrix(vector)).getColumn(0); } else { return org.jblas.Solve.solveSymmetric(new org.jblas.DoubleMatrix(matrix), new org.jblas.DoubleMatrix(vector)).data; /* To use the linear algebra package colt from cern. cern.colt.matrix.linalg.Algebra linearAlgebra = new cern.colt.matrix.linalg.Algebra(); double[] x = linearAlgebra.solve(new DenseDoubleMatrix2D(A), linearAlgebra.transpose(new DenseDoubleMatrix2D(new double[][] { b }))).viewColumn(0).toArray(); return x; */ } } /** * Find a solution of the linear equation A x = b in the least square sense where * <ul> * <li>A is an n x m - matrix given as double[n][m]</li> * <li>b is an m - vector given as double[m],</li> * <li>x is an n - vector given as double[n],</li> * </ul> * * @param matrix The matrix A (left hand side of the linear equation). * @param vector The vector b (right hand of the linear equation). * @return A solution x to A x = b. */ public static double[] solveLinearEquationLeastSquare(double[][] matrix, double[] vector) { // We use the linear algebra package apache commons math DecompositionSolver solver = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix, false)).getSolver(); return solver.solve(new ArrayRealVector(vector)).toArray(); } /** * Find a solution of the linear equation A X = B in the least square sense where * <ul> * <li>A is an n x m - matrix given as double[n][m]</li> * <li>B is an m x k - matrix given as double[m][k],</li> * <li>X is an n x k - matrix given as double[n][k],</li> * </ul> * * @param matrix The matrix A (left hand side of the linear equation). * @param rhs The matrix B (right hand of the linear equation). * @return A solution X to A X = B. */ public static double[][] solveLinearEquationLeastSquare(double[][] matrix, double[][] rhs) { // We use the linear algebra package apache commons math DecompositionSolver solver = new SingularValueDecomposition(new Array2DRowRealMatrix(matrix, false)).getSolver(); return solver.solve(new Array2DRowRealMatrix(rhs)).getData(); } /** * Returns the matrix of the n Eigenvectors corresponding to the first n largest Eigenvalues of a correlation matrix. * These Eigenvectors can also be interpreted as "principal components" (i.e., the method implements the PCA). * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (eigenvectors). * @return Matrix of n Eigenvectors (columns) (matrix is given as double[n][numberOfFactors], where n is the number of rows of the correlationMatrix. */ public static double[][] getFactorMatrix(double[][] correlationMatrix, int numberOfFactors) { return getFactorMatrixUsingCommonsMath(correlationMatrix, numberOfFactors); } /** * Returns a correlation matrix which has rank &lt; n and for which the first n factors agree with the factors of correlationMatrix. * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (Eigenvectors). * @return Factor reduced correlation matrix. */ public static double[][] factorReduction(double[][] correlationMatrix, int numberOfFactors) { return factorReductionUsingCommonsMath(correlationMatrix, numberOfFactors); } /** * Returns the matrix of the n Eigenvectors corresponding to the first n largest Eigenvalues of a correlation matrix. * These eigenvectors can also be interpreted as "principal components" (i.e., the method implements the PCA). * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (Eigenvectors). * @return Matrix of n Eigenvectors (columns) (matrix is given as double[n][numberOfFactors], where n is the number of rows of the correlationMatrix. */ private static double[][] getFactorMatrixUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { /* * Factor reduction */ // Create an eigen vector decomposition of the correlation matrix double[] eigenValues; double[][] eigenVectorMatrix; if(isEigenvalueDecompositionViaSVD) { SingularValueDecomposition svd = new SingularValueDecomposition(new Array2DRowRealMatrix(correlationMatrix)); eigenValues = svd.getSingularValues(); eigenVectorMatrix = svd.getV().getData(); } else { EigenDecomposition eigenDecomp = new EigenDecomposition(new Array2DRowRealMatrix(correlationMatrix, false)); eigenValues = eigenDecomp.getRealEigenvalues(); eigenVectorMatrix = eigenDecomp.getV().getData(); } class EigenValueIndex implements Comparable<EigenValueIndex> { private int index; private Double value; EigenValueIndex(int index, double value) { this.index = index; this.value = value; } @Override public int compareTo(EigenValueIndex o) { return o.value.compareTo(value); } } List<EigenValueIndex> eigenValueIndices = new ArrayList<>(); for(int i=0; i<eigenValues.length; i++) { eigenValueIndices.add(i,new EigenValueIndex(i,eigenValues[i])); } Collections.sort(eigenValueIndices); // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = new double[eigenValues.length][numberOfFactors]; for (int factor = 0; factor < numberOfFactors; factor++) { int eigenVectorIndex = eigenValueIndices.get(factor).index; double eigenValue = eigenValues[eigenVectorIndex]; double signChange = eigenVectorMatrix[0][eigenVectorIndex] > 0.0 ? 1.0 : -1.0; // Convention: Have first entry of eigenvector positive. This is to make results more consistent. double eigenVectorNormSquared = 0.0; for (int row = 0; row < eigenValues.length; row++) { eigenVectorNormSquared += eigenVectorMatrix[row][eigenVectorIndex] * eigenVectorMatrix[row][eigenVectorIndex]; } eigenValue = Math.max(eigenValue,0.0); for (int row = 0; row < eigenValues.length; row++) { factorMatrix[row][factor] = signChange * Math.sqrt(eigenValue/eigenVectorNormSquared) * eigenVectorMatrix[row][eigenVectorIndex]; } } return factorMatrix; } /** * Returns a correlation matrix which has rank &lt; n and for which the first n factors agree with the factors of correlationMatrix. * * @param correlationMatrix The given correlation matrix. * @param numberOfFactors The requested number of factors (Eigenvectors). * @return Factor reduced correlation matrix. */ public static double[][] factorReductionUsingCommonsMath(double[][] correlationMatrix, int numberOfFactors) { // Extract factors corresponding to the largest eigenvalues double[][] factorMatrix = getFactorMatrix(correlationMatrix, numberOfFactors); // Renormalize rows for (int row = 0; row < correlationMatrix.length; row++) { double sumSquared = 0; for (int factor = 0; factor < numberOfFactors; factor++) { sumSquared += factorMatrix[row][factor] * factorMatrix[row][factor]; } if(sumSquared != 0) { for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = factorMatrix[row][factor] / Math.sqrt(sumSquared); } } else { // This is a rare case: The factor reduction of a completely decorrelated system to 1 factor for (int factor = 0; factor < numberOfFactors; factor++) { factorMatrix[row][factor] = 1.0; } } } // Orthogonalized again double[][] reducedCorrelationMatrix = (new Array2DRowRealMatrix(factorMatrix).multiply(new Array2DRowRealMatrix(factorMatrix).transpose())).getData(); return getFactorMatrix(reducedCorrelationMatrix, numberOfFactors); } /** * Calculate the "matrix exponential" (expm). * * Note: The function currently requires jblas. If jblas is not availabe on your system, an exception will be thrown. * A future version of this function may implement a fall back. * * @param matrix The given matrix. * @return The exp(matrix). */ public double[][] exp(double[][] matrix) { return org.jblas.MatrixFunctions.expm(new org.jblas.DoubleMatrix(matrix)).toArray2(); } /** * Calculate the "matrix exponential" (expm). * * Note: The function currently requires jblas. If jblas is not availabe on your system, an exception will be thrown. * A future version of this function may implement a fall back. * * @param matrix The given matrix. * @return The exp(matrix). */ public RealMatrix exp(RealMatrix matrix) { return new Array2DRowRealMatrix(exp(matrix.getData())); } /** * Transpose a matrix * * @param matrix The given matrix. * @return The transposed matrix. */ public static double[][] transpose(double[][] matrix){ //Get number of rows and columns of matrix int numberOfRows = matrix.length; int numberOfCols = matrix[0].length; //Instantiate a unitMatrix of dimension dim double[][] transpose = new double[numberOfCols][numberOfRows]; //Create unit matrix for(int rowIndex = 0; rowIndex < numberOfRows; rowIndex++) { for(int colIndex = 0; colIndex < numberOfCols; colIndex++) { transpose[colIndex][rowIndex] = matrix[rowIndex][colIndex]; } } return transpose; } /** * Pseudo-Inverse of a matrix calculated in the least square sense. * * @param matrix The given matrix A. * @return pseudoInverse The pseudo-inverse matrix P, such that A*P*A = A and P*A*P = P */ public static double[][] pseudoInverse(double[][] matrix){ return invert(matrix); } /** * Generates a diagonal matrix with the input vector on its diagonal * * @param vector The given matrix A. * @return diagonalMatrix The matrix with the vectors entries on its diagonal */ public static double[][] diag(double[] vector){ // Note: According to the Java Language spec, an array is initialized with the default value, here 0. double[][] diagonalMatrix = new double[vector.length][vector.length]; for(int index = 0; index < vector.length; index++) { diagonalMatrix[index][index] = vector[index]; } return diagonalMatrix; } /** * Multiplication of two matrices. * * @param left The matrix A. * @param right The matrix B * @return product The matrix product of A*B (if suitable) */ public static double[][] multMatrices(double[][] left, double[][] right){ if(isSolverUseApacheCommonsMath) { return new Array2DRowRealMatrix(left).multiply(new Array2DRowRealMatrix(right)).getData(); } else { return new org.jblas.DoubleMatrix(left).mmul(new org.jblas.DoubleMatrix(right)).toArray2(); } } }
Clean up.
src/main/java/net/finmath/functions/LinearAlgebra.java
Clean up.
<ide><path>rc/main/java/net/finmath/functions/LinearAlgebra.java <ide> private static boolean isEigenvalueDecompositionViaSVD = Boolean.parseBoolean(System.getProperty("net.finmath.functions.LinearAlgebra.isEigenvalueDecompositionViaSVD","false")); <ide> private static boolean isSolverUseApacheCommonsMath; <ide> private static boolean isJBlasAvailable; <del> <add> <ide> static { <ide> // Default value is true, in which case we will NOT use jblas <ide> boolean isSolverUseApacheCommonsMath = Boolean.parseBoolean(System.getProperty("net.finmath.functions.LinearAlgebra.isUseApacheCommonsMath","true")); <ide> isJBlasAvailable = false; <ide> } <ide> } <del> <add> <ide> if(!isJBlasAvailable) isSolverUseApacheCommonsMath = true; <ide> LinearAlgebra.isSolverUseApacheCommonsMath = isSolverUseApacheCommonsMath; <ide> }
Java
apache-2.0
33ccc2a92f3662eaa1d4d591c785b3e0967decbe
0
apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj,apache/uima-uimaj
/* * 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.uima.cas; import java.io.InputStream; import java.util.Iterator; import java.util.ListIterator; import org.apache.uima.cas.admin.CASAdminException; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.LowLevelCAS; import org.apache.uima.cas.impl.SelectFSs_impl; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.impl.JCasImpl; import org.apache.uima.jcas.tcas.Annotation; /** * Object-oriented CAS (Common Analysis System) API. * * <p> * A <code>CAS</code> object provides the starting point for working with the CAS. It provides * access to the type system, to indexes, iterators and filters (constraints). It also lets you * create new annotations and other data structures. You can create a <code>CAS</code> object * using static methods on the class {@link org.apache.uima.util.CasCreationUtils}. * <p> * The <code>CAS</code> object is also the container that manages multiple Subjects of Analysis or * Sofas. A Sofa represents some form of an unstructured artifact that is processed in a UIMA * pipeline. The Java string called the "DocumentText" used in a UIMA text processing pipeline is an * example of a Sofa. A Sofa can be analyzed independently using the standard UIMA programming model * or analyzed together with other Sofas utilizing the Sofa programming model extensions. * <p> * A Sofa is implemented as a built-in CAS type uima.cas.Sofa. Use * {@link org.apache.uima.cas.CAS#createSofa CAS.createSofa()} to instantiate a Sofa feature * structure. The {@link SofaFS SofaFS} class provides methods to set and get the features of a * SofaFS. Although Sofas are implemented as standard feature structures, generic CAS APIs must * never be used to create Sofas or set their features. * <p> * Use {@link org.apache.uima.cas.CAS#getView(String)} or * {@link org.apache.uima.cas.CAS#getView(SofaFS)} to obtain a view of a particular Sofa in the CAS. * This view will provide access to the Sofa data (for example the document text) as well as the * index repository, which contains metadata (annotations and other feature structures) about that * Sofa. * <p> * Use {@link #getTypeSystem getTypeSystem()} to access the type system. With a * {@link TypeSystem TypeSystem} object, you can access the {@link Type Type} and * {@link Feature Feature} objects for the CAS built-in types. Note that this interface also * provides constants for the names of the built-in types and features. * * * */ public interface CAS extends AbstractCas { // ////////////////////////////////////////////////// // Type names /** * UIMA CAS name space. */ static final String NAME_SPACE_UIMA_CAS = "uima" + TypeSystem.NAMESPACE_SEPARATOR + "cas"; /** * UIMA CAS name space prefix to prepend to type names (adds an extra period to the name space * proper. */ static final String UIMA_CAS_PREFIX = NAME_SPACE_UIMA_CAS + TypeSystem.NAMESPACE_SEPARATOR; /** * Top type. */ static final String TYPE_NAME_TOP = UIMA_CAS_PREFIX + "TOP"; /** * Integer type. */ static final String TYPE_NAME_INTEGER = UIMA_CAS_PREFIX + "Integer"; /** * Float type. */ static final String TYPE_NAME_FLOAT = UIMA_CAS_PREFIX + "Float"; /** * String type. */ static final String TYPE_NAME_STRING = UIMA_CAS_PREFIX + "String"; /** * Boolean type. */ static final String TYPE_NAME_BOOLEAN = UIMA_CAS_PREFIX + "Boolean"; /** * Byte type. */ static final String TYPE_NAME_BYTE = UIMA_CAS_PREFIX + "Byte"; /** * Short type. */ static final String TYPE_NAME_SHORT = UIMA_CAS_PREFIX + "Short"; /** * Long type. */ static final String TYPE_NAME_LONG = UIMA_CAS_PREFIX + "Long"; /** * Double type. */ static final String TYPE_NAME_DOUBLE = UIMA_CAS_PREFIX + "Double"; // /** // * Java Object type // */ // static final String TYPE_NAME_JAVA_OBJECT = UIMA_CAS_PREFIX + "JavaObject"; // // /** // * FS Array List // */ // static final String TYPE_NAME_FS_ARRAY_LIST = UIMA_CAS_PREFIX + "FSArrayList"; // // /** // * int Array List // */ // static final String TYPE_NAME_INT_ARRAY_LIST = UIMA_CAS_PREFIX + "IntegerArrayList"; /** * ArrayBase type. */ static final String TYPE_NAME_ARRAY_BASE = UIMA_CAS_PREFIX + "ArrayBase"; /** * Feature structure array type. */ static final String TYPE_NAME_FS_ARRAY = UIMA_CAS_PREFIX + "FSArray"; /** * Integer array type. */ static final String TYPE_NAME_INTEGER_ARRAY = UIMA_CAS_PREFIX + "IntegerArray"; /** * Float array type. */ static final String TYPE_NAME_FLOAT_ARRAY = UIMA_CAS_PREFIX + "FloatArray"; /** * String array type. */ static final String TYPE_NAME_STRING_ARRAY = UIMA_CAS_PREFIX + "StringArray"; /** * Boolean array type. */ static final String TYPE_NAME_BOOLEAN_ARRAY = UIMA_CAS_PREFIX + "BooleanArray"; /** * Byte array type. */ static final String TYPE_NAME_BYTE_ARRAY = UIMA_CAS_PREFIX + "ByteArray"; /** * Short array type. */ static final String TYPE_NAME_SHORT_ARRAY = UIMA_CAS_PREFIX + "ShortArray"; /** * Long array type. */ static final String TYPE_NAME_LONG_ARRAY = UIMA_CAS_PREFIX + "LongArray"; /** * Double array type. */ static final String TYPE_NAME_DOUBLE_ARRAY = UIMA_CAS_PREFIX + "DoubleArray"; // /** // * FSHashSet type // */ // static final String TYPE_NAME_FS_HASH_SET = UIMA_CAS_PREFIX + "FSHashSet"; /** * Sofa type. */ static final String TYPE_NAME_SOFA = UIMA_CAS_PREFIX + "Sofa"; /** * Name of annotation base type. */ static final String TYPE_NAME_ANNOTATION_BASE = UIMA_CAS_PREFIX + "AnnotationBase"; // ///////////////////////////////////////////////////////////////////////// // Sofa features. /** * Base name of Sofa Number feature. */ static final String FEATURE_BASE_NAME_SOFANUM = "sofaNum"; /** * Base name of Sofa ID feature. */ static final String FEATURE_BASE_NAME_SOFAID = "sofaID"; /** * Base name of Sofa mime type feature. */ static final String FEATURE_BASE_NAME_SOFAMIME = "mimeType"; /** * Base name of Sofa URI feature. */ static final String FEATURE_BASE_NAME_SOFAURI = "sofaURI"; /** * Base name of Sofa string data feature. */ static final String FEATURE_BASE_NAME_SOFASTRING = "sofaString"; /** * Base name of Sofa array fs data feature. */ static final String FEATURE_BASE_NAME_SOFAARRAY = "sofaArray"; /** * Base name of FSArrayList fsArray feature. * Base name of FSHashSet fsArray feature. */ static final String FEATURE_BASE_NAME_FS_ARRAY = "fsArray"; /** * Base name of FSArrayList fsArray feature. */ static final String FEATURE_BASE_NAME_INT_ARRAY = "intArray"; /** * Qualified name of Sofa number feature. */ static final String FEATURE_FULL_NAME_SOFANUM = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFANUM; /** * Qualified name of Sofa id feature. */ static final String FEATURE_FULL_NAME_SOFAID = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFAID; /** * Qualified name of Sofa mime type feature. */ static final String FEATURE_FULL_NAME_SOFAMIME = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFAMIME; /** * Qualified name of Sofa URI feature. */ static final String FEATURE_FULL_NAME_SOFAURI = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFAURI; /** * Qualified name of Sofa string data feature. */ static final String FEATURE_FULL_NAME_SOFASTRING = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFASTRING; /** * Qualified name of Sofa array fs data feature. */ static final String FEATURE_FULL_NAME_SOFAARRAY = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFAARRAY; // //////////////////////////////////////////////////////////////////////// // Other Sofa names /** * Sofa Index name. */ static final String SOFA_INDEX_NAME = "SofaIndex"; /** * Sofa name for the default text sofa. * * @deprecated As of v2.0, this is replaced by {@link #NAME_DEFAULT_SOFA}, and the value has * changed. In general, user code should not need to refer to this name. */ @Deprecated static final String NAME_DEFAULT_TEXT_SOFA = "_InitialView"; /** * Sofa name for the initial view's sofa. */ static final String NAME_DEFAULT_SOFA = "_InitialView"; /** * Abstract list base type. */ static final String TYPE_NAME_LIST_BASE = UIMA_CAS_PREFIX + "ListBase"; /** * Feature structure list type. */ static final String TYPE_NAME_FS_LIST = UIMA_CAS_PREFIX + "FSList"; /** * Non-empty feature structure list type. */ static final String TYPE_NAME_NON_EMPTY_FS_LIST = UIMA_CAS_PREFIX + "NonEmptyFSList"; /** * Empty feature structure list type. */ static final String TYPE_NAME_EMPTY_FS_LIST = UIMA_CAS_PREFIX + "EmptyFSList"; /** * Integer list type. */ static final String TYPE_NAME_INTEGER_LIST = UIMA_CAS_PREFIX + "IntegerList"; /** * Non-empty integer list type. */ static final String TYPE_NAME_NON_EMPTY_INTEGER_LIST = UIMA_CAS_PREFIX + "NonEmptyIntegerList"; /** * Empty integer list type. */ static final String TYPE_NAME_EMPTY_INTEGER_LIST = UIMA_CAS_PREFIX + "EmptyIntegerList"; /** * Float list type. */ static final String TYPE_NAME_FLOAT_LIST = UIMA_CAS_PREFIX + "FloatList"; /** * Non-empty float list type. */ static final String TYPE_NAME_NON_EMPTY_FLOAT_LIST = UIMA_CAS_PREFIX + "NonEmptyFloatList"; /** * Empty float type. */ static final String TYPE_NAME_EMPTY_FLOAT_LIST = UIMA_CAS_PREFIX + "EmptyFloatList"; /** * String list type. */ static final String TYPE_NAME_STRING_LIST = UIMA_CAS_PREFIX + "StringList"; /** * Non-empty string list type. */ static final String TYPE_NAME_NON_EMPTY_STRING_LIST = UIMA_CAS_PREFIX + "NonEmptyStringList"; /** * Empty string list type. */ static final String TYPE_NAME_EMPTY_STRING_LIST = UIMA_CAS_PREFIX + "EmptyStringList"; /** * Base name of list head feature. */ static final String FEATURE_BASE_NAME_HEAD = "head"; /** * Base name of list tail feature. */ static final String FEATURE_BASE_NAME_TAIL = "tail"; /** * Qualified name of fs list head feature. */ static final String FEATURE_FULL_NAME_FS_LIST_HEAD = TYPE_NAME_NON_EMPTY_FS_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_HEAD; /** * Qualified name of integer list head feature. */ static final String FEATURE_FULL_NAME_INTEGER_LIST_HEAD = TYPE_NAME_NON_EMPTY_INTEGER_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_HEAD; /** * Qualified name of float list head feature. */ static final String FEATURE_FULL_NAME_FLOAT_LIST_HEAD = TYPE_NAME_NON_EMPTY_FLOAT_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_HEAD; /** * Qualified name of string list head feature. */ static final String FEATURE_FULL_NAME_STRING_LIST_HEAD = TYPE_NAME_NON_EMPTY_STRING_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_HEAD; /** * Qualified name of fs list tail feature. */ static final String FEATURE_FULL_NAME_FS_LIST_TAIL = TYPE_NAME_NON_EMPTY_FS_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_TAIL; /** * Qualified name of integer list tail feature. */ static final String FEATURE_FULL_NAME_INTEGER_LIST_TAIL = TYPE_NAME_NON_EMPTY_INTEGER_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_TAIL; /** * Qualified name of float list tail feature. */ static final String FEATURE_FULL_NAME_FLOAT_LIST_TAIL = TYPE_NAME_NON_EMPTY_FLOAT_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_TAIL; /** * Qualified name of string list tail feature. */ static final String FEATURE_FULL_NAME_STRING_LIST_TAIL = TYPE_NAME_NON_EMPTY_STRING_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_TAIL; /** * Name of Text CAS name space. */ static final String NAME_SPACE_UIMA_TCAS = "uima" + TypeSystem.NAMESPACE_SEPARATOR + "tcas"; /** * UIMA TCAS name space prefix to prepend to type names (adds an extra period to the name space * proper. */ static final String UIMA_TCAS_PREFIX = NAME_SPACE_UIMA_TCAS + TypeSystem.NAMESPACE_SEPARATOR; /** * Name of annotation type. */ static final String TYPE_NAME_ANNOTATION = UIMA_TCAS_PREFIX + "Annotation"; /** * Name of document annotation type. */ static final String TYPE_NAME_DOCUMENT_ANNOTATION = UIMA_TCAS_PREFIX + "DocumentAnnotation"; /** * Sofa ID feature that is the handle to a text Sofa. */ static final String FEATURE_BASE_NAME_SOFA = "sofa"; /** * Base name of annotation begin feature. */ static final String FEATURE_BASE_NAME_BEGIN = "begin"; /** * Base name of annotation end feature. */ static final String FEATURE_BASE_NAME_END = "end"; /** * Base name of document language feature. */ static final String FEATURE_BASE_NAME_LANGUAGE = "language"; /** * Fully qualified name of annotation begin feature. */ static final String FEATURE_FULL_NAME_BEGIN = TYPE_NAME_ANNOTATION + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_BEGIN; /** * Fully qualified name of annotation sofa feature. */ static final String FEATURE_FULL_NAME_SOFA = TYPE_NAME_ANNOTATION_BASE + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFA; /** * Fully qualified name of annotation end feature. */ static final String FEATURE_FULL_NAME_END = TYPE_NAME_ANNOTATION + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_END; /** * Fully qualified name of document language feature. */ static final String FEATURE_FULL_NAME_LANGUAGE = TYPE_NAME_DOCUMENT_ANNOTATION + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_LANGUAGE; /** * Name of the built-in index on annotations. */ static final String STD_ANNOTATION_INDEX = "AnnotationIndex"; static final String DEFAULT_LANGUAGE_NAME = "x-unspecified"; /** * Create a new FeatureStructure. * * @param type * The type of the FS. * @param <T> the Java cover class for the FS being created * @return The new FS. */ <T extends FeatureStructure> T createFS(Type type) throws CASRuntimeException; /** * Create a new feature structure array. * * @param length * The length of the array. * @return The new array. */ ArrayFS createArrayFS(int length) throws CASRuntimeException; /** * Create a new int array. * * @param length * The length of the array. * @return The new array. */ IntArrayFS createIntArrayFS(int length) throws CASRuntimeException; /** * Create a new int array. * * @param length * The length of the array. * @return The new array. */ FloatArrayFS createFloatArrayFS(int length) throws CASRuntimeException; /** * Create a new String array. * * @param length * The length of the array. * @return The new array. */ StringArrayFS createStringArrayFS(int length) throws CASRuntimeException; /** * Create a new Byte array. * * @param length * The length of the array. * @return The new array. */ ByteArrayFS createByteArrayFS(int length) throws CASRuntimeException; /** * Create a new Boolean array. * * @param length * The length of the array. * @return The new array. */ BooleanArrayFS createBooleanArrayFS(int length) throws CASRuntimeException; /** * Create a new Short array. * * @param length * The length of the array. * @return The new array. */ ShortArrayFS createShortArrayFS(int length) throws CASRuntimeException; /** * Create a new Long array. * * @param length * The length of the array. * @return The new array. */ LongArrayFS createLongArrayFS(int length) throws CASRuntimeException; /** * Create a new Double array. * * @param length * The length of the array. * @return The new array. */ DoubleArrayFS createDoubleArrayFS(int length) throws CASRuntimeException; /** * Get the JCas for this CAS. * * @return The JCas for this CAS. * @throws CASException - */ JCas getJCas() throws CASException; /** * Get the JCasImpl for this CAS * @return the JCasImpl for this CAS */ default JCasImpl getJCasImpl() { return ((CASImpl) this).getJCasImpl(); } /** * Get the Cas view that the current component should use. This * should only be used by single-view components. * * @return the Cas view specified for the current component by Sofa mapping. Defaults to _InitialView if there is no Sofa mapping. * */ CAS getCurrentView(); /** * Get sofaFS for given Subject of Analysis ID. * * @param sofaID - * @return The sofaFS. * * @deprecated As of v2.0, use {#getView(String)}. From the view you can access the Sofa data, or * call {@link #getSofa()} if you truly need to access the SofaFS object. */ @Deprecated SofaFS getSofa(SofaID sofaID); /** * Get the Sofa feature structure associated with this CAS view. * * @return The SofaFS associated with this CAS view. */ SofaFS getSofa(); /** * Create a view and its underlying Sofa (subject of analysis). The view provides access to the * Sofa data and the index repository that contains metadata (annotations and other feature * structures) pertaining to that Sofa. * <p> * This method creates the underlying Sofa feature structure, but does not set the Sofa data. * Setting ths Sofa data must be done by calling {@link #setSofaDataArray(FeatureStructure, String)}, * {@link #setSofaDataString(String, String)} or {@link #setSofaDataURI(String, String)} on the * CAS view returned by this method. * * @param localViewName * the local name, before any sofa name mapping is done, for this view (note: this is the * same as the associated Sofa name). * * @return The view corresponding to this local name. * @throws CASRuntimeException * if a View with this name already exists in this CAS */ CAS createView(String localViewName); /** * Create a JCas view for a Sofa. Note: as of UIMA v2.0, can be replaced with * getView(sofaFS).getJCas(). * * @param aSofa * a Sofa feature structure in this CAS. * * @return The JCas view for the given Sofa. * @throws CASException - */ JCas getJCas(SofaFS aSofa) throws CASException; /** * Create a JCas view for a Sofa. Note: this is provided for convenience. It is equivalent to * <code>getView(aSofaID).getJCas()</code>. * * @param aSofaID * the ID of a Sofa defined in this CAS * * @return The view for the Sofa with ID <code>aSofaID</code>. * @throws CASException * if no Sofa with the given ID exists in this CAS * * @deprecated As of v2.0, use {@link #getView(String)} followed by {@link #getJCas()}. */ @Deprecated JCas getJCas(SofaID aSofaID) throws CASException; /** * Get the view for a Sofa (subject of analysis). The view provides access to the Sofa data and * the index repository that contains metadata (annotations and other feature structures) * pertaining to that Sofa. * * @param localViewName * the local name, before any sofa name mapping is done, for this view (note: this is the * same as the associated Sofa name). * * @return The view corresponding to this local name. * @throws CASRuntimeException * if no View with this name exists in this CAS */ CAS getView(String localViewName); /** * Get the view for a Sofa (subject of analysis). The view provides access to the Sofa data and * the index repository that contains metadata (annotations and other feature structures) * pertaining to that Sofa. * * @param aSofa * a Sofa feature structure in the CAS * * @return The view for the given Sofa */ CAS getView(SofaFS aSofa); /** * Get an instance of the low-level CAS. Low-level and regular CAS can be used in parallel, all * data is always contained in both. * * <p> * <b>Note</b>: This is for internal use. * * @return A low-level CAS. * @see LowLevelCAS */ LowLevelCAS getLowLevelCAS(); /** * Get the type object for the annotation type. * * @return The annotation type. */ Type getAnnotationType(); /** * Get the feature object for the annotation begin feature. * * @return The annotation begin feature. */ Feature getBeginFeature(); /** * Get the feature object for the annotation end feature. * * @return The annotation end feature. */ Feature getEndFeature(); /** * Get the standard annotation index. * * @param <T> either Annotation (if JCas is in use) or AnnotationImpl * * @return The standard annotation index. */ <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(); /** * Get the standard annotation index restricted to a specific annotation type. * * @param type * The annotation type the index is restricted to. * @param <T> the topmost Java class corresponding to the type * @return The standard annotation index, restricted to <code>type</code>. * @exception CASRuntimeException When <code>type</code> is not an annotation type. */ <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(Type type) throws CASRuntimeException; /** * Get the standard annotation index restricted to a specific annotation type. * * @param clazz * The annotation type the index is restricted to, specified as a JCas class * @param <T> the topmost Java class corresponding to the type * @return The standard annotation index, restricted to <code>type</code>. * @exception CASRuntimeException When <code>type</code> is not an annotation type. */ default <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(Class<T> clazz) throws CASRuntimeException { return getAnnotationIndex(this.getJCasImpl().getCasType(clazz)); } /** * Create a new annotation. Note that you still need to insert the annotation into the index * repository yourself. * * @param type * The type of the annotation. * @param begin * The start of the annotation. * @param end * The end of the annotation. * @param <T> the Java class corresponding to the type * @return A new annotation object. */ <T extends AnnotationFS> AnnotationFS createAnnotation(Type type, int begin, int end); /** * Get the document annotation. The document has a string-valued feature called "language" where * the document language is specified. * * @param <T> the Java class for the document annotation. Could be the JCas cover class or FeatureStructure * @return The document annotation. If it doesn't exist, one is created. The return value is the * JCas cover class or the plain Java cover class for FeatureStructures if * there is no JCas cover class for this type. */ <T extends AnnotationFS> T getDocumentAnnotation(); /** * Informs the CAS of relevant information about the component that is currently processing it. * This is called by the framework automatically; users do not need to call it. * * @param info * information about the component that is currently processing this CAS. */ void setCurrentComponentInfo(ComponentInfo info); /** * This part of the CAS interface is shared among CAS and JCAS interfaces If you change it in one * of the interfaces, consider changing it in the other */ // ///////////////////////////////////////////////////////////////////////// // // Standard CAS Methods // // ///////////////////////////////////////////////////////////////////////// /** * Return the type system of this CAS instance. * * @return The type system, or <code>null</code> if none is available. * @exception CASRuntimeException * If the type system has not been committed. */ TypeSystem getTypeSystem() throws CASRuntimeException; /** * Create a Subject of Analysis. The new sofaFS is automatically added to the SofaIndex. * * @param sofaID - * @param mimeType - * @return The sofaFS. * * @deprecated As of v2.0, use {@link #createView(String)} instead. */ @Deprecated SofaFS createSofa(SofaID sofaID, String mimeType); /** * Get iterator for all SofaFS in the CAS. * @param <T> generic type of sofa iterator * @return an iterator over SofaFS. */ <T extends SofaFS> FSIterator<T> getSofaIterator(); /** * Create an iterator over structures satisfying a given constraint. Constraints are described in * the javadocs for {@link ConstraintFactory} and related classes. * * @param it * The input iterator. * @param cons * The constraint specifying what structures should be returned. * @param <T> - the type of the Feature Structure * @return An iterator over FSs. */ <T extends FeatureStructure> FSIterator<T> createFilteredIterator(FSIterator<T> it, FSMatchConstraint cons); /** * Get a constraint factory. A constraint factory is a simple way of creating * {@link org.apache.uima.cas.FSMatchConstraint FSMatchConstraints}. * * @return A constraint factory to create new FS constraints. */ ConstraintFactory getConstraintFactory(); /** * Create a feature path. This is mainly useful for creating * {@link org.apache.uima.cas.FSMatchConstraint FSMatchConstraints}. * * @return A new, empty feature path. */ FeaturePath createFeaturePath(); /** * Get the index repository. * * @return The index repository, or <code>null</code> if none is available. */ FSIndexRepository getIndexRepository(); /** * Wrap a standard Java {@link java.util.ListIterator ListIterator} around an FSListIterator. Use * if you feel more comfortable with java style iterators. * * @param it * The <code>FSListIterator</code> to be wrapped. * @param <T> The type of FeatureStructure * @return An equivalent <code>ListIterator</code>. */ <T extends FeatureStructure> ListIterator<T> fs2listIterator(FSIterator<T> it); /** * Reset the CAS, emptying it of all content. Feature structures and iterators will no longer be * valid. Note: this method may only be called from an application. Calling it from an annotator * will trigger a runtime exception. * * @throws CASRuntimeException * When called out of sequence. * @see org.apache.uima.cas.admin.CASMgr */ void reset() throws CASAdminException; /** * Get the view name. The view name is the same as the name of the view's Sofa, retrieved by * getSofa().getSofaID(), except for the initial View before its Sofa has been created. * * @return The name of the view */ String getViewName(); /** * Estimate the memory consumption of this CAS instance (in bytes). * * @return The estimated memory used by this CAS instance. */ int size(); /** * Create a feature-value path from a string. * * @param featureValuePath * String representation of the feature-value path. * @return Feature-value path object. * @throws CASRuntimeException * If the input string is not well-formed. */ FeatureValuePath createFeatureValuePath(String featureValuePath) throws CASRuntimeException; /** * Set the document text. Once set, Sofa data is immutable, and cannot be set again until the CAS * has been reset. * * @param text * The text to be analyzed. * @exception CASRuntimeException * If the Sofa data has already been set. */ void setDocumentText(String text) throws CASRuntimeException; /** * Set the document text. Once set, Sofa data is immutable, and cannot be set again until the CAS * has been reset. * * @param text * The text to be analyzed. * @param mimetype * The mime type of the data * @exception CASRuntimeException * If the Sofa data has already been set. */ void setSofaDataString(String text, String mimetype) throws CASRuntimeException; /** * Get the document text. * * @return The text being analyzed, or <code>null</code> if not set. */ String getDocumentText(); /** * Get the Sofa Data String (a.k.a. the document text). * * @return The Sofa data string, or <code>null</code> if not set. */ String getSofaDataString(); /** * Sets the language for this document. This value sets the language feature of the special * instance of DocumentAnnotation associated with this CAS. * * @param languageCode - * @throws CASRuntimeException passthru */ void setDocumentLanguage(String languageCode) throws CASRuntimeException; /** * Gets the language code for this document from the language feature of the special instance of * the DocumentationAnnotation associated with this CAS. * * @return language identifier */ String getDocumentLanguage(); /** * Set the Sofa data as an ArrayFS. Once set, Sofa data is immutable, and cannot be set again * until the CAS has been reset. * * @param array * The ArrayFS to be analyzed. * @param mime * The mime type of the data * @exception CASRuntimeException * If the Sofa data has already been set. */ void setSofaDataArray(FeatureStructure array, String mime) throws CASRuntimeException; /** * Get the Sofa data array. * * @return The Sofa Data being analyzed, or <code>null</code> if not set. */ FeatureStructure getSofaDataArray(); /** * Set the Sofa data as a URI. Once set, Sofa data is immutable, and cannot be set again until the * CAS has been reset. * * @param uri * The URI of the data to be analyzed. * @param mime * The mime type of the data * @exception CASRuntimeException * If the Sofa data has already been set. */ void setSofaDataURI(String uri, String mime) throws CASRuntimeException; /** * Get the Sofa data array. * * @return The Sofa URI being analyzed, or <code>null</code> if not set. */ String getSofaDataURI(); /** * Get the Sofa data as a byte stream. * * @return A stream handle to the Sofa Data, or <code>null</code> if not set. */ InputStream getSofaDataStream(); /** * Get the mime type of the Sofa data being analyzed. * * @return the mime type of the Sofa */ String getSofaMimeType(); /** * Add a feature structure to all appropriate indexes in the repository associated with this CAS * View. If no indexes exist for the type of FS that you are adding, then a bag (unsorted) index * will be automatically created. * * <p> * <b>Important</b>: after you have called <code>addFsToIndexes(...)</code> on a FS, do not * change the values of any features used for indexing. If you do, the index will become corrupted * and may be unusable. If you need to change an index feature value, first call * {@link #removeFsFromIndexes(FeatureStructure) removeFsFromIndexes(...)} on the FS, change the * feature values, then call <code>addFsToIndexes(...)</code> again. * * @param fs * The Feature Structure to be added. * @exception NullPointerException * If the <code>fs</code> parameter is <code>null</code>. */ void addFsToIndexes(FeatureStructure fs); /** * Remove a feature structure from all indexes in the repository associated with this CAS View. * The remove operation removes the exact fs from the indexes, unlike operations such as * moveTo which use the fs argument as a template. * * It is not an error if the FS is not present in the indexes. * * @param fs * The Feature Structure to be removed. * @exception NullPointerException * If the <code>fs</code> parameter is <code>null</code>. */ void removeFsFromIndexes(FeatureStructure fs); /** * Get iterator over all views in this CAS. Each view provides access to Sofa data * and the index repository that contains metadata (annotations and other feature * structures) pertaining to that Sofa. * * @param <T> generic type of returned view * @return an iterator which returns all views. Each object returned by * the iterator is of type CAS or a subtype. */ <T extends CAS> Iterator<T> getViewIterator(); /** * Get iterator over all views with the given name prefix. Each view provides access to Sofa data * and the index repository that contains metadata (annotations and other feature * structures) pertaining to that Sofa. * <p> * When passed the prefix <i>namePrefix</i>, the iterator will return all views who * name is either exactly equal to <i>namePrefix</i> or is of the form * <i>namePrefix</i><code>.</code><i>suffix</i>, where <i>suffix</i> can be any String. * * @param localViewNamePrefix the local name prefix, before any sofa name mapping * is done, for this view (note: this is the same as the associated Sofa name prefix). * * @return an iterator which returns all views with the given name prefix. * Each object returned by the iterator is of type CAS. */ Iterator<CAS> getViewIterator(String localViewNamePrefix); /** * Sets a mark and returns the marker object set with the current mark which can be used to query when certain FSs * were created. This can then be used to identify FSs as added before or after the mark was set and * to identify FSs modified after the mark is set. * * Note: this method may only be called from an application. Calling it from an annotator * will trigger a runtime exception. * * * @return a marker object. */ Marker createMarker(); /** * Call this method to set up a region, * ended by a {@link java.lang.AutoCloseable#close()} call on the returned object, * You can use this or the {@link #protectIndexes(Runnable)} method to protected * the indexes. * <p> * This approach allows arbitrary code between the protectIndexes and the associated close method. * <p> * The close method is best done in a finally block, or using the try-with-resources statement in * Java 8. * * @return an object used to record things that need adding back */ AutoCloseable protectIndexes(); /** * Runs the code in the runnable inside a protection block, where any modifications to features * done while in this block will be done in a way to protect any indexes which otherwise * might become corrupted by the update action; the protection is achieved by temporarily * removing the FS (if it is in the indexes), before the update happens. * At the end of the block, affected indexes have any removed-under-the-covers FSs added back. * @param runnable code to execute while protecting the indexes. */ void protectIndexes(Runnable runnable); default <T extends FeatureStructure> SelectFSs<T> select() { return new SelectFSs_impl<>(this); } default <T extends FeatureStructure> SelectFSs<T> select(Type type) { return new SelectFSs_impl<>(this).type(type); } default <T extends FeatureStructure> SelectFSs<T> select(Class<T> clazz) { return new SelectFSs_impl<>(this).type(clazz); } default <T extends FeatureStructure> SelectFSs<T> select(int jcasType) { return new SelectFSs_impl<>(this).type(jcasType); } default <T extends FeatureStructure> SelectFSs<T> select(String fullyQualifiedTypeName) { return new SelectFSs_impl<>(this).type(fullyQualifiedTypeName); } }
uimaj-core/src/main/java/org/apache/uima/cas/CAS.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.uima.cas; import java.io.InputStream; import java.util.Iterator; import java.util.ListIterator; import org.apache.uima.cas.admin.CASAdminException; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.LowLevelCAS; import org.apache.uima.cas.impl.SelectFSs_impl; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.impl.JCasImpl; import org.apache.uima.jcas.tcas.Annotation; /** * Object-oriented CAS (Common Analysis System) API. * * <p> * A <code>CAS</code> object provides the starting point for working with the CAS. It provides * access to the type system, to indexes, iterators and filters (constraints). It also lets you * create new annotations and other data structures. You can create a <code>CAS</code> object * using static methods on the class {@link org.apache.uima.util.CasCreationUtils}. * <p> * The <code>CAS</code> object is also the container that manages multiple Subjects of Analysis or * Sofas. A Sofa represents some form of an unstructured artifact that is processed in a UIMA * pipeline. The Java string called the "DocumentText" used in a UIMA text processing pipeline is an * example of a Sofa. A Sofa can be analyzed independently using the standard UIMA programming model * or analyzed together with other Sofas utilizing the Sofa programming model extensions. * <p> * A Sofa is implemented as a built-in CAS type uima.cas.Sofa. Use * {@link org.apache.uima.cas.CAS#createSofa CAS.createSofa()} to instantiate a Sofa feature * structure. The {@link SofaFS SofaFS} class provides methods to set and get the features of a * SofaFS. Although Sofas are implemented as standard feature structures, generic CAS APIs must * never be used to create Sofas or set their features. * <p> * Use {@link org.apache.uima.cas.CAS#getView(String)} or * {@link org.apache.uima.cas.CAS#getView(SofaFS)} to obtain a view of a particular Sofa in the CAS. * This view will provide access to the Sofa data (for example the document text) as well as the * index repository, which contains metadata (annotations and other feature structures) about that * Sofa. * <p> * Use {@link #getTypeSystem getTypeSystem()} to access the type system. With a * {@link TypeSystem TypeSystem} object, you can access the {@link Type Type} and * {@link Feature Feature} objects for the CAS built-in types. Note that this interface also * provides constants for the names of the built-in types and features. * * * */ public interface CAS extends AbstractCas { // ////////////////////////////////////////////////// // Type names /** * UIMA CAS name space. */ static final String NAME_SPACE_UIMA_CAS = "uima" + TypeSystem.NAMESPACE_SEPARATOR + "cas"; /** * UIMA CAS name space prefix to prepend to type names (adds an extra period to the name space * proper. */ static final String UIMA_CAS_PREFIX = NAME_SPACE_UIMA_CAS + TypeSystem.NAMESPACE_SEPARATOR; /** * Top type. */ static final String TYPE_NAME_TOP = UIMA_CAS_PREFIX + "TOP"; /** * Integer type. */ static final String TYPE_NAME_INTEGER = UIMA_CAS_PREFIX + "Integer"; /** * Float type. */ static final String TYPE_NAME_FLOAT = UIMA_CAS_PREFIX + "Float"; /** * String type. */ static final String TYPE_NAME_STRING = UIMA_CAS_PREFIX + "String"; /** * Boolean type. */ static final String TYPE_NAME_BOOLEAN = UIMA_CAS_PREFIX + "Boolean"; /** * Byte type. */ static final String TYPE_NAME_BYTE = UIMA_CAS_PREFIX + "Byte"; /** * Short type. */ static final String TYPE_NAME_SHORT = UIMA_CAS_PREFIX + "Short"; /** * Long type. */ static final String TYPE_NAME_LONG = UIMA_CAS_PREFIX + "Long"; /** * Double type. */ static final String TYPE_NAME_DOUBLE = UIMA_CAS_PREFIX + "Double"; // /** // * Java Object type // */ // static final String TYPE_NAME_JAVA_OBJECT = UIMA_CAS_PREFIX + "JavaObject"; // // /** // * FS Array List // */ // static final String TYPE_NAME_FS_ARRAY_LIST = UIMA_CAS_PREFIX + "FSArrayList"; // // /** // * int Array List // */ // static final String TYPE_NAME_INT_ARRAY_LIST = UIMA_CAS_PREFIX + "IntegerArrayList"; /** * ArrayBase type. */ static final String TYPE_NAME_ARRAY_BASE = UIMA_CAS_PREFIX + "ArrayBase"; /** * Feature structure array type. */ static final String TYPE_NAME_FS_ARRAY = UIMA_CAS_PREFIX + "FSArray"; /** * Integer array type. */ static final String TYPE_NAME_INTEGER_ARRAY = UIMA_CAS_PREFIX + "IntegerArray"; /** * Float array type. */ static final String TYPE_NAME_FLOAT_ARRAY = UIMA_CAS_PREFIX + "FloatArray"; /** * String array type. */ static final String TYPE_NAME_STRING_ARRAY = UIMA_CAS_PREFIX + "StringArray"; /** * Boolean array type. */ static final String TYPE_NAME_BOOLEAN_ARRAY = UIMA_CAS_PREFIX + "BooleanArray"; /** * Byte array type. */ static final String TYPE_NAME_BYTE_ARRAY = UIMA_CAS_PREFIX + "ByteArray"; /** * Short array type. */ static final String TYPE_NAME_SHORT_ARRAY = UIMA_CAS_PREFIX + "ShortArray"; /** * Long array type. */ static final String TYPE_NAME_LONG_ARRAY = UIMA_CAS_PREFIX + "LongArray"; /** * Double array type. */ static final String TYPE_NAME_DOUBLE_ARRAY = UIMA_CAS_PREFIX + "DoubleArray"; // /** // * FSHashSet type // */ // static final String TYPE_NAME_FS_HASH_SET = UIMA_CAS_PREFIX + "FSHashSet"; /** * Sofa type. */ static final String TYPE_NAME_SOFA = UIMA_CAS_PREFIX + "Sofa"; /** * Name of annotation base type. */ static final String TYPE_NAME_ANNOTATION_BASE = UIMA_CAS_PREFIX + "AnnotationBase"; // ///////////////////////////////////////////////////////////////////////// // Sofa features. /** * Base name of Sofa Number feature. */ static final String FEATURE_BASE_NAME_SOFANUM = "sofaNum"; /** * Base name of Sofa ID feature. */ static final String FEATURE_BASE_NAME_SOFAID = "sofaID"; /** * Base name of Sofa mime type feature. */ static final String FEATURE_BASE_NAME_SOFAMIME = "mimeType"; /** * Base name of Sofa URI feature. */ static final String FEATURE_BASE_NAME_SOFAURI = "sofaURI"; /** * Base name of Sofa string data feature. */ static final String FEATURE_BASE_NAME_SOFASTRING = "sofaString"; /** * Base name of Sofa array fs data feature. */ static final String FEATURE_BASE_NAME_SOFAARRAY = "sofaArray"; /** * Base name of FSArrayList fsArray feature. * Base name of FSHashSet fsArray feature. */ static final String FEATURE_BASE_NAME_FS_ARRAY = "fsArray"; /** * Base name of FSArrayList fsArray feature. */ static final String FEATURE_BASE_NAME_INT_ARRAY = "intArray"; /** * Qualified name of Sofa number feature. */ static final String FEATURE_FULL_NAME_SOFANUM = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFANUM; /** * Qualified name of Sofa id feature. */ static final String FEATURE_FULL_NAME_SOFAID = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFAID; /** * Qualified name of Sofa mime type feature. */ static final String FEATURE_FULL_NAME_SOFAMIME = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFAMIME; /** * Qualified name of Sofa URI feature. */ static final String FEATURE_FULL_NAME_SOFAURI = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFAURI; /** * Qualified name of Sofa string data feature. */ static final String FEATURE_FULL_NAME_SOFASTRING = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFASTRING; /** * Qualified name of Sofa array fs data feature. */ static final String FEATURE_FULL_NAME_SOFAARRAY = TYPE_NAME_SOFA + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFAARRAY; // //////////////////////////////////////////////////////////////////////// // Other Sofa names /** * Sofa Index name. */ static final String SOFA_INDEX_NAME = "SofaIndex"; /** * Sofa name for the default text sofa. * * @deprecated As of v2.0, this is replaced by {@link #NAME_DEFAULT_SOFA}, and the value has * changed. In general, user code should not need to refer to this name. */ @Deprecated static final String NAME_DEFAULT_TEXT_SOFA = "_InitialView"; /** * Sofa name for the initial view's sofa. */ static final String NAME_DEFAULT_SOFA = "_InitialView"; /** * Abstract list base type. */ static final String TYPE_NAME_LIST_BASE = UIMA_CAS_PREFIX + "ListBase"; /** * Feature structure list type. */ static final String TYPE_NAME_FS_LIST = UIMA_CAS_PREFIX + "FSList"; /** * Non-empty feature structure list type. */ static final String TYPE_NAME_NON_EMPTY_FS_LIST = UIMA_CAS_PREFIX + "NonEmptyFSList"; /** * Empty feature structure list type. */ static final String TYPE_NAME_EMPTY_FS_LIST = UIMA_CAS_PREFIX + "EmptyFSList"; /** * Integer list type. */ static final String TYPE_NAME_INTEGER_LIST = UIMA_CAS_PREFIX + "IntegerList"; /** * Non-empty integer list type. */ static final String TYPE_NAME_NON_EMPTY_INTEGER_LIST = UIMA_CAS_PREFIX + "NonEmptyIntegerList"; /** * Empty integer list type. */ static final String TYPE_NAME_EMPTY_INTEGER_LIST = UIMA_CAS_PREFIX + "EmptyIntegerList"; /** * Float list type. */ static final String TYPE_NAME_FLOAT_LIST = UIMA_CAS_PREFIX + "FloatList"; /** * Non-empty float list type. */ static final String TYPE_NAME_NON_EMPTY_FLOAT_LIST = UIMA_CAS_PREFIX + "NonEmptyFloatList"; /** * Empty float type. */ static final String TYPE_NAME_EMPTY_FLOAT_LIST = UIMA_CAS_PREFIX + "EmptyFloatList"; /** * String list type. */ static final String TYPE_NAME_STRING_LIST = UIMA_CAS_PREFIX + "StringList"; /** * Non-empty string list type. */ static final String TYPE_NAME_NON_EMPTY_STRING_LIST = UIMA_CAS_PREFIX + "NonEmptyStringList"; /** * Empty string list type. */ static final String TYPE_NAME_EMPTY_STRING_LIST = UIMA_CAS_PREFIX + "EmptyStringList"; /** * Base name of list head feature. */ static final String FEATURE_BASE_NAME_HEAD = "head"; /** * Base name of list tail feature. */ static final String FEATURE_BASE_NAME_TAIL = "tail"; /** * Qualified name of fs list head feature. */ static final String FEATURE_FULL_NAME_FS_LIST_HEAD = TYPE_NAME_NON_EMPTY_FS_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_HEAD; /** * Qualified name of integer list head feature. */ static final String FEATURE_FULL_NAME_INTEGER_LIST_HEAD = TYPE_NAME_NON_EMPTY_INTEGER_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_HEAD; /** * Qualified name of float list head feature. */ static final String FEATURE_FULL_NAME_FLOAT_LIST_HEAD = TYPE_NAME_NON_EMPTY_FLOAT_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_HEAD; /** * Qualified name of string list head feature. */ static final String FEATURE_FULL_NAME_STRING_LIST_HEAD = TYPE_NAME_NON_EMPTY_STRING_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_HEAD; /** * Qualified name of fs list tail feature. */ static final String FEATURE_FULL_NAME_FS_LIST_TAIL = TYPE_NAME_NON_EMPTY_FS_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_TAIL; /** * Qualified name of integer list tail feature. */ static final String FEATURE_FULL_NAME_INTEGER_LIST_TAIL = TYPE_NAME_NON_EMPTY_INTEGER_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_TAIL; /** * Qualified name of float list tail feature. */ static final String FEATURE_FULL_NAME_FLOAT_LIST_TAIL = TYPE_NAME_NON_EMPTY_FLOAT_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_TAIL; /** * Qualified name of string list tail feature. */ static final String FEATURE_FULL_NAME_STRING_LIST_TAIL = TYPE_NAME_NON_EMPTY_STRING_LIST + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_TAIL; /** * Name of Text CAS name space. */ static final String NAME_SPACE_UIMA_TCAS = "uima" + TypeSystem.NAMESPACE_SEPARATOR + "tcas"; /** * UIMA TCAS name space prefix to prepend to type names (adds an extra period to the name space * proper. */ static final String UIMA_TCAS_PREFIX = NAME_SPACE_UIMA_TCAS + TypeSystem.NAMESPACE_SEPARATOR; /** * Name of annotation type. */ static final String TYPE_NAME_ANNOTATION = UIMA_TCAS_PREFIX + "Annotation"; /** * Name of document annotation type. */ static final String TYPE_NAME_DOCUMENT_ANNOTATION = UIMA_TCAS_PREFIX + "DocumentAnnotation"; /** * Sofa ID feature that is the handle to a text Sofa. */ static final String FEATURE_BASE_NAME_SOFA = "sofa"; /** * Base name of annotation begin feature. */ static final String FEATURE_BASE_NAME_BEGIN = "begin"; /** * Base name of annotation end feature. */ static final String FEATURE_BASE_NAME_END = "end"; /** * Base name of document language feature. */ static final String FEATURE_BASE_NAME_LANGUAGE = "language"; /** * Fully qualified name of annotation begin feature. */ static final String FEATURE_FULL_NAME_BEGIN = TYPE_NAME_ANNOTATION + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_BEGIN; /** * Fully qualified name of annotation sofa feature. */ static final String FEATURE_FULL_NAME_SOFA = TYPE_NAME_ANNOTATION_BASE + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_SOFA; /** * Fully qualified name of annotation end feature. */ static final String FEATURE_FULL_NAME_END = TYPE_NAME_ANNOTATION + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_END; /** * Fully qualified name of document language feature. */ static final String FEATURE_FULL_NAME_LANGUAGE = TYPE_NAME_DOCUMENT_ANNOTATION + TypeSystem.FEATURE_SEPARATOR + FEATURE_BASE_NAME_LANGUAGE; /** * Name of the built-in index on annotations. */ static final String STD_ANNOTATION_INDEX = "AnnotationIndex"; static final String DEFAULT_LANGUAGE_NAME = "x-unspecified"; /** * Create a new FeatureStructure. * * @param type * The type of the FS. * @param <T> the Java cover class for the FS being created * @return The new FS. */ <T extends FeatureStructure> T createFS(Type type) throws CASRuntimeException; /** * Create a new feature structure array. * * @param length * The length of the array. * @return The new array. */ ArrayFS createArrayFS(int length) throws CASRuntimeException; /** * Create a new int array. * * @param length * The length of the array. * @return The new array. */ IntArrayFS createIntArrayFS(int length) throws CASRuntimeException; /** * Create a new int array. * * @param length * The length of the array. * @return The new array. */ FloatArrayFS createFloatArrayFS(int length) throws CASRuntimeException; /** * Create a new String array. * * @param length * The length of the array. * @return The new array. */ StringArrayFS createStringArrayFS(int length) throws CASRuntimeException; /** * Create a new Byte array. * * @param length * The length of the array. * @return The new array. */ ByteArrayFS createByteArrayFS(int length) throws CASRuntimeException; /** * Create a new Boolean array. * * @param length * The length of the array. * @return The new array. */ BooleanArrayFS createBooleanArrayFS(int length) throws CASRuntimeException; /** * Create a new Short array. * * @param length * The length of the array. * @return The new array. */ ShortArrayFS createShortArrayFS(int length) throws CASRuntimeException; /** * Create a new Long array. * * @param length * The length of the array. * @return The new array. */ LongArrayFS createLongArrayFS(int length) throws CASRuntimeException; /** * Create a new Double array. * * @param length * The length of the array. * @return The new array. */ DoubleArrayFS createDoubleArrayFS(int length) throws CASRuntimeException; /** * Get the JCas for this CAS. * * @return The JCas for this CAS. * @throws CASException - */ JCas getJCas() throws CASException; /** * Get the JCasImpl for this CAS * @return the JCasImpl for this CAS */ default JCasImpl getJCasImpl() { return ((CASImpl) this).getJCasImpl(); } /** * Get the Cas view that the current component should use. This * should only be used by single-view components. * * @return the Cas view specified for the current component by Sofa mapping. Defaults to _InitialView if there is no Sofa mapping. * */ CAS getCurrentView(); /** * Get sofaFS for given Subject of Analysis ID. * * @param sofaID - * @return The sofaFS. * * @deprecated As of v2.0, use {#getView(String)}. From the view you can access the Sofa data, or * call {@link #getSofa()} if you truly need to access the SofaFS object. */ @Deprecated SofaFS getSofa(SofaID sofaID); /** * Get the Sofa feature structure associated with this CAS view. * * @return The SofaFS associated with this CAS view. */ SofaFS getSofa(); /** * Create a view and its underlying Sofa (subject of analysis). The view provides access to the * Sofa data and the index repository that contains metadata (annotations and other feature * structures) pertaining to that Sofa. * <p> * This method creates the underlying Sofa feature structure, but does not set the Sofa data. * Setting ths Sofa data must be done by calling {@link #setSofaDataArray(FeatureStructure, String)}, * {@link #setSofaDataString(String, String)} or {@link #setSofaDataURI(String, String)} on the * CAS view returned by this method. * * @param localViewName * the local name, before any sofa name mapping is done, for this view (note: this is the * same as the associated Sofa name). * * @return The view corresponding to this local name. * @throws CASRuntimeException * if a View with this name already exists in this CAS */ CAS createView(String localViewName); /** * Create a JCas view for a Sofa. Note: as of UIMA v2.0, can be replaced with * getView(sofaFS).getJCas(). * * @param aSofa * a Sofa feature structure in this CAS. * * @return The JCas view for the given Sofa. * @throws CASException - */ JCas getJCas(SofaFS aSofa) throws CASException; /** * Create a JCas view for a Sofa. Note: this is provided for convenience. It is equivalent to * <code>getView(aSofaID).getJCas()</code>. * * @param aSofaID * the ID of a Sofa defined in this CAS * * @return The view for the Sofa with ID <code>aSofaID</code>. * @throws CASException * if no Sofa with the given ID exists in this CAS * * @deprecated As of v2.0, use {@link #getView(String)} followed by {@link #getJCas()}. */ @Deprecated JCas getJCas(SofaID aSofaID) throws CASException; /** * Get the view for a Sofa (subject of analysis). The view provides access to the Sofa data and * the index repository that contains metadata (annotations and other feature structures) * pertaining to that Sofa. * * @param localViewName * the local name, before any sofa name mapping is done, for this view (note: this is the * same as the associated Sofa name). * * @return The view corresponding to this local name. * @throws CASRuntimeException * if no View with this name exists in this CAS */ CAS getView(String localViewName); /** * Get the view for a Sofa (subject of analysis). The view provides access to the Sofa data and * the index repository that contains metadata (annotations and other feature structures) * pertaining to that Sofa. * * @param aSofa * a Sofa feature structure in the CAS * * @return The view for the given Sofa */ CAS getView(SofaFS aSofa); /** * Get an instance of the low-level CAS. Low-level and regular CAS can be used in parallel, all * data is always contained in both. * * <p> * <b>Note</b>: This is for internal use. * * @return A low-level CAS. * @see LowLevelCAS */ LowLevelCAS getLowLevelCAS(); /** * Get the type object for the annotation type. * * @return The annotation type. */ Type getAnnotationType(); /** * Get the feature object for the annotation begin feature. * * @return The annotation begin feature. */ Feature getBeginFeature(); /** * Get the feature object for the annotation end feature. * * @return The annotation end feature. */ Feature getEndFeature(); /** * Get the standard annotation index. * * @param <T> either Annotation (if JCas is in use) or AnnotationImpl * * @return The standard annotation index. */ <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(); /** * Get the standard annotation index restricted to a specific annotation type. * * @param type * The annotation type the index is restricted to. * @param <T> the topmost Java class corresponding to the type * @return The standard annotation index, restricted to <code>type</code>. * @exception CASRuntimeException When <code>type</code> is not an annotation type. */ <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(Type type) throws CASRuntimeException; /** * Get the standard annotation index restricted to a specific annotation type. * * @param type * The annotation type the index is restricted to, specified as a JCas class * @param <T> the topmost Java class corresponding to the type * @return The standard annotation index, restricted to <code>type</code>. * @exception CASRuntimeException When <code>type</code> is not an annotation type. */ default <T extends AnnotationFS> AnnotationIndex<T> getAnnotationIndex(Class<T> clazz) throws CASRuntimeException { return getAnnotationIndex(this.getJCasImpl().getCasType(clazz)); } /** * Create a new annotation. Note that you still need to insert the annotation into the index * repository yourself. * * @param type * The type of the annotation. * @param begin * The start of the annotation. * @param end * The end of the annotation. * @param <T> the Java class corresponding to the type * @return A new annotation object. */ <T extends AnnotationFS> AnnotationFS createAnnotation(Type type, int begin, int end); /** * Get the document annotation. The document has a string-valued feature called "language" where * the document language is specified. * * @param <T> the Java class for the document annotation. Could be the JCas cover class or FeatureStructure * @return The document annotation. If it doesn't exist, one is created. The return value is the * JCas cover class or the plain Java cover class for FeatureStructures if * there is no JCas cover class for this type. */ <T extends AnnotationFS> T getDocumentAnnotation(); /** * Informs the CAS of relevant information about the component that is currently processing it. * This is called by the framework automatically; users do not need to call it. * * @param info * information about the component that is currently processing this CAS. */ void setCurrentComponentInfo(ComponentInfo info); /** * This part of the CAS interface is shared among CAS and JCAS interfaces If you change it in one * of the interfaces, consider changing it in the other */ // ///////////////////////////////////////////////////////////////////////// // // Standard CAS Methods // // ///////////////////////////////////////////////////////////////////////// /** * Return the type system of this CAS instance. * * @return The type system, or <code>null</code> if none is available. * @exception CASRuntimeException * If the type system has not been committed. */ TypeSystem getTypeSystem() throws CASRuntimeException; /** * Create a Subject of Analysis. The new sofaFS is automatically added to the SofaIndex. * * @param sofaID - * @param mimeType - * @return The sofaFS. * * @deprecated As of v2.0, use {@link #createView(String)} instead. */ @Deprecated SofaFS createSofa(SofaID sofaID, String mimeType); /** * Get iterator for all SofaFS in the CAS. * @param <T> generic type of sofa iterator * @return an iterator over SofaFS. */ <T extends SofaFS> FSIterator<T> getSofaIterator(); /** * Create an iterator over structures satisfying a given constraint. Constraints are described in * the javadocs for {@link ConstraintFactory} and related classes. * * @param it * The input iterator. * @param cons * The constraint specifying what structures should be returned. * @param <T> - the type of the Feature Structure * @return An iterator over FSs. */ <T extends FeatureStructure> FSIterator<T> createFilteredIterator(FSIterator<T> it, FSMatchConstraint cons); /** * Get a constraint factory. A constraint factory is a simple way of creating * {@link org.apache.uima.cas.FSMatchConstraint FSMatchConstraints}. * * @return A constraint factory to create new FS constraints. */ ConstraintFactory getConstraintFactory(); /** * Create a feature path. This is mainly useful for creating * {@link org.apache.uima.cas.FSMatchConstraint FSMatchConstraints}. * * @return A new, empty feature path. */ FeaturePath createFeaturePath(); /** * Get the index repository. * * @return The index repository, or <code>null</code> if none is available. */ FSIndexRepository getIndexRepository(); /** * Wrap a standard Java {@link java.util.ListIterator ListIterator} around an FSListIterator. Use * if you feel more comfortable with java style iterators. * * @param it * The <code>FSListIterator</code> to be wrapped. * @param <T> The type of FeatureStructure * @return An equivalent <code>ListIterator</code>. */ <T extends FeatureStructure> ListIterator<T> fs2listIterator(FSIterator<T> it); /** * Reset the CAS, emptying it of all content. Feature structures and iterators will no longer be * valid. Note: this method may only be called from an application. Calling it from an annotator * will trigger a runtime exception. * * @throws CASRuntimeException * When called out of sequence. * @see org.apache.uima.cas.admin.CASMgr */ void reset() throws CASAdminException; /** * Get the view name. The view name is the same as the name of the view's Sofa, retrieved by * getSofa().getSofaID(), except for the initial View before its Sofa has been created. * * @return The name of the view */ String getViewName(); /** * Estimate the memory consumption of this CAS instance (in bytes). * * @return The estimated memory used by this CAS instance. */ int size(); /** * Create a feature-value path from a string. * * @param featureValuePath * String representation of the feature-value path. * @return Feature-value path object. * @throws CASRuntimeException * If the input string is not well-formed. */ FeatureValuePath createFeatureValuePath(String featureValuePath) throws CASRuntimeException; /** * Set the document text. Once set, Sofa data is immutable, and cannot be set again until the CAS * has been reset. * * @param text * The text to be analyzed. * @exception CASRuntimeException * If the Sofa data has already been set. */ void setDocumentText(String text) throws CASRuntimeException; /** * Set the document text. Once set, Sofa data is immutable, and cannot be set again until the CAS * has been reset. * * @param text * The text to be analyzed. * @param mimetype * The mime type of the data * @exception CASRuntimeException * If the Sofa data has already been set. */ void setSofaDataString(String text, String mimetype) throws CASRuntimeException; /** * Get the document text. * * @return The text being analyzed, or <code>null</code> if not set. */ String getDocumentText(); /** * Get the Sofa Data String (a.k.a. the document text). * * @return The Sofa data string, or <code>null</code> if not set. */ String getSofaDataString(); /** * Sets the language for this document. This value sets the language feature of the special * instance of DocumentAnnotation associated with this CAS. * * @param languageCode - * @throws CASRuntimeException passthru */ void setDocumentLanguage(String languageCode) throws CASRuntimeException; /** * Gets the language code for this document from the language feature of the special instance of * the DocumentationAnnotation associated with this CAS. * * @return language identifier */ String getDocumentLanguage(); /** * Set the Sofa data as an ArrayFS. Once set, Sofa data is immutable, and cannot be set again * until the CAS has been reset. * * @param array * The ArrayFS to be analyzed. * @param mime * The mime type of the data * @exception CASRuntimeException * If the Sofa data has already been set. */ void setSofaDataArray(FeatureStructure array, String mime) throws CASRuntimeException; /** * Get the Sofa data array. * * @return The Sofa Data being analyzed, or <code>null</code> if not set. */ FeatureStructure getSofaDataArray(); /** * Set the Sofa data as a URI. Once set, Sofa data is immutable, and cannot be set again until the * CAS has been reset. * * @param uri * The URI of the data to be analyzed. * @param mime * The mime type of the data * @exception CASRuntimeException * If the Sofa data has already been set. */ void setSofaDataURI(String uri, String mime) throws CASRuntimeException; /** * Get the Sofa data array. * * @return The Sofa URI being analyzed, or <code>null</code> if not set. */ String getSofaDataURI(); /** * Get the Sofa data as a byte stream. * * @return A stream handle to the Sofa Data, or <code>null</code> if not set. */ InputStream getSofaDataStream(); /** * Get the mime type of the Sofa data being analyzed. * * @return the mime type of the Sofa */ String getSofaMimeType(); /** * Add a feature structure to all appropriate indexes in the repository associated with this CAS * View. If no indexes exist for the type of FS that you are adding, then a bag (unsorted) index * will be automatically created. * * <p> * <b>Important</b>: after you have called <code>addFsToIndexes(...)</code> on a FS, do not * change the values of any features used for indexing. If you do, the index will become corrupted * and may be unusable. If you need to change an index feature value, first call * {@link #removeFsFromIndexes(FeatureStructure) removeFsFromIndexes(...)} on the FS, change the * feature values, then call <code>addFsToIndexes(...)</code> again. * * @param fs * The Feature Structure to be added. * @exception NullPointerException * If the <code>fs</code> parameter is <code>null</code>. */ void addFsToIndexes(FeatureStructure fs); /** * Remove a feature structure from all indexes in the repository associated with this CAS View. * The remove operation removes the exact fs from the indexes, unlike operations such as * moveTo which use the fs argument as a template. * * It is not an error if the FS is not present in the indexes. * * @param fs * The Feature Structure to be removed. * @exception NullPointerException * If the <code>fs</code> parameter is <code>null</code>. */ void removeFsFromIndexes(FeatureStructure fs); /** * Get iterator over all views in this CAS. Each view provides access to Sofa data * and the index repository that contains metadata (annotations and other feature * structures) pertaining to that Sofa. * * @param <T> generic type of returned view * @return an iterator which returns all views. Each object returned by * the iterator is of type CAS or a subtype. */ <T extends CAS> Iterator<T> getViewIterator(); /** * Get iterator over all views with the given name prefix. Each view provides access to Sofa data * and the index repository that contains metadata (annotations and other feature * structures) pertaining to that Sofa. * <p> * When passed the prefix <i>namePrefix</i>, the iterator will return all views who * name is either exactly equal to <i>namePrefix</i> or is of the form * <i>namePrefix</i><code>.</code><i>suffix</i>, where <i>suffix</i> can be any String. * * @param localViewNamePrefix the local name prefix, before any sofa name mapping * is done, for this view (note: this is the same as the associated Sofa name prefix). * * @return an iterator which returns all views with the given name prefix. * Each object returned by the iterator is of type CAS. */ Iterator<CAS> getViewIterator(String localViewNamePrefix); /** * Sets a mark and returns the marker object set with the current mark which can be used to query when certain FSs * were created. This can then be used to identify FSs as added before or after the mark was set and * to identify FSs modified after the mark is set. * * Note: this method may only be called from an application. Calling it from an annotator * will trigger a runtime exception. * * * @return a marker object. */ Marker createMarker(); /** * Call this method to set up a region, * ended by a {@link java.lang.AutoCloseable#close()} call on the returned object, * You can use this or the {@link #protectIndexes(Runnable)} method to protected * the indexes. * <p> * This approach allows arbitrary code between the protectIndexes and the associated close method. * <p> * The close method is best done in a finally block, or using the try-with-resources statement in * Java 8. * * @return an object used to record things that need adding back */ AutoCloseable protectIndexes(); /** * Runs the code in the runnable inside a protection block, where any modifications to features * done while in this block will be done in a way to protect any indexes which otherwise * might become corrupted by the update action; the protection is achieved by temporarily * removing the FS (if it is in the indexes), before the update happens. * At the end of the block, affected indexes have any removed-under-the-covers FSs added back. * @param runnable code to execute while protecting the indexes. */ void protectIndexes(Runnable runnable); default <T extends FeatureStructure> SelectFSs<T> select() { return new SelectFSs_impl<>(this); } default <T extends FeatureStructure> SelectFSs<T> select(Type type) { return new SelectFSs_impl<>(this).type(type); } default <T extends FeatureStructure> SelectFSs<T> select(Class<T> clazz) { return new SelectFSs_impl<>(this).type(clazz); } default <T extends FeatureStructure> SelectFSs<T> select(int jcasType) { return new SelectFSs_impl<>(this).type(jcasType); } default <T extends FeatureStructure> SelectFSs<T> select(String fullyQualifiedTypeName) { return new SelectFSs_impl<>(this).type(fullyQualifiedTypeName); } }
no jira fix javadoc pblm git-svn-id: d56ff9e7d7ea0b208561738885f328c1a8397aa6@1802508 13f79535-47bb-0310-9956-ffa450edef68
uimaj-core/src/main/java/org/apache/uima/cas/CAS.java
no jira fix javadoc pblm
<ide><path>imaj-core/src/main/java/org/apache/uima/cas/CAS.java <ide> /** <ide> * Get the standard annotation index restricted to a specific annotation type. <ide> * <del> * @param type <add> * @param clazz <ide> * The annotation type the index is restricted to, specified as a JCas class <ide> * @param <T> the topmost Java class corresponding to the type <ide> * @return The standard annotation index, restricted to <code>type</code>.
Java
apache-2.0
dcf5daa07ee2a64451a663d52915d1123fdc3ee0
0
pferraro/JGroups,slaskawi/JGroups,danberindei/JGroups,dimbleby/JGroups,ligzy/JGroups,danberindei/JGroups,rpelisse/JGroups,tristantarrant/JGroups,dimbleby/JGroups,danberindei/JGroups,rpelisse/JGroups,vjuranek/JGroups,pferraro/JGroups,rhusar/JGroups,TarantulaTechnology/JGroups,rvansa/JGroups,ibrahimshbat/JGroups,dimbleby/JGroups,ibrahimshbat/JGroups,tristantarrant/JGroups,belaban/JGroups,vjuranek/JGroups,rhusar/JGroups,rvansa/JGroups,rpelisse/JGroups,ibrahimshbat/JGroups,belaban/JGroups,deepnarsay/JGroups,TarantulaTechnology/JGroups,slaskawi/JGroups,kedzie/JGroups,kedzie/JGroups,deepnarsay/JGroups,vjuranek/JGroups,belaban/JGroups,Sanne/JGroups,deepnarsay/JGroups,pruivo/JGroups,ibrahimshbat/JGroups,pferraro/JGroups,Sanne/JGroups,slaskawi/JGroups,TarantulaTechnology/JGroups,Sanne/JGroups,ligzy/JGroups,pruivo/JGroups,kedzie/JGroups,ligzy/JGroups,rhusar/JGroups,pruivo/JGroups
package org.jgroups.mux; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.*; import org.jgroups.TimeoutException; import org.jgroups.protocols.pbcast.FLUSH; import org.jgroups.stack.StateTransferInfo; import org.jgroups.util.FIFOMessageQueue; import org.jgroups.util.Promise; import org.jgroups.util.Util; import java.util.*; import java.util.concurrent.*; /** * Used for dispatching incoming messages. The Multiplexer implements UpHandler and registers with the associated * JChannel (there can only be 1 Multiplexer per JChannel). When up() is called with a message, the header of the * message is removed and the MuxChannel corresponding to the header's service ID is retrieved from the map, * and MuxChannel.up() is called with the message. * @author Bela Ban * @version $Id: Multiplexer.java,v 1.51 2007/03/05 13:33:42 belaban Exp $ */ public class Multiplexer implements UpHandler { /** Map<String,MuxChannel>. Maintains the mapping between service IDs and their associated MuxChannels */ private final Map<String,MuxChannel> services=new HashMap<String,MuxChannel>(); private final JChannel channel; static final Log log=LogFactory.getLog(Multiplexer.class); static final String SEPARATOR="::"; static final short SEPARATOR_LEN=(short)SEPARATOR.length(); static final String NAME="MUX"; private MergeView temp_merge_view=null; private boolean flush_present=true; private boolean blocked=false; /** Thread pool to concurrently process messages sent to different services */ private static Executor thread_pool=null; /** To make sure messages sent to different services are processed concurrently (using the thread pool above), but * messages to the same service are processed FIFO */ private FIFOMessageQueue<String,Runnable> fifo_queue=new FIFOMessageQueue<String,Runnable>(); /** Cluster view */ View view=null; Address local_addr=null; /** Map<String,Boolean>. Map of service IDs and booleans that determine whether getState() has already been called */ private final Map<String,Boolean> state_transfer_listeners=new HashMap<String,Boolean>(); /** Map<String,List<Address>>. A map of services as keys and lists of hosts as values */ private final Map<String,List<Address>> service_state=new HashMap<String,List<Address>>(); /** Used to wait on service state information */ private final Promise service_state_promise=new Promise(); /** Map<Address, Set<String>>. Keys are senders, values are a set of services hosted by that sender. * Used to collect responses to LIST_SERVICES_REQ */ private final Map<Address, Set<String>> service_responses=new HashMap<Address, Set<String>>(); private long SERVICES_RSP_TIMEOUT=10000; static { int min_threads=1, max_threads=4; long keep_alive=30000; boolean mux_enabled=true; // default is to use the thread pool String tmp; try { tmp=System.getProperty(Global.MUX_ENABLED); if(tmp != null) mux_enabled=Boolean.parseBoolean(tmp); } catch(Throwable t) {} if(mux_enabled) { ThreadFactory factory=new ThreadFactory() { int num=1; ThreadGroup mux_threads=new ThreadGroup(Util.getGlobalThreadGroup(), "MultiplexerThreads"); public Thread newThread(Runnable command) { Thread ret=new Thread(mux_threads, command, "Multiplexer-" + num++); ret.setDaemon(true); return ret; } }; try { tmp=System.getProperty(Global.MUX_MIN_THREADS); if(tmp != null) min_threads=Integer.parseInt(tmp); } catch(Throwable t) {} try { tmp=System.getProperty(Global.MUX_MAX_THREADS); if(tmp != null) max_threads=Integer.parseInt(tmp); } catch(Throwable t) {} try { tmp=System.getProperty(Global.MUX_KEEPALIVE); if(tmp != null) keep_alive=Long.parseLong(tmp); } catch(Throwable t) {} thread_pool=new ThreadPoolExecutor(min_threads, max_threads, keep_alive, TimeUnit.MILLISECONDS, new SynchronousQueue(), factory, new ThreadPoolExecutor.CallerRunsPolicy()); } } public Multiplexer() { this.channel=null; flush_present=isFlushPresent(); } public Multiplexer(JChannel channel) { this.channel=channel; this.channel.setUpHandler(this); this.channel.setOpt(Channel.BLOCK, Boolean.TRUE); // we want to handle BLOCK events ourselves flush_present=isFlushPresent(); } /** * @deprecated Use ${link #getServiceIds()} instead * @return The set of service IDs */ public Set getApplicationIds() { return services != null? services.keySet() : null; } public Set<String> getServiceIds() { return services != null? services.keySet() : null; } public long getServicesResponseTimeout() { return SERVICES_RSP_TIMEOUT; } public void setServicesResponseTimeout(long services_rsp_timeout) { this.SERVICES_RSP_TIMEOUT=services_rsp_timeout; } /** Returns a copy of the current view <em>minus</em> the nodes on which service service_id is <em>not</em> running * * @param service_id * @return The service view */ public View getServiceView(String service_id) { List hosts=service_state.get(service_id); if(hosts == null) return null; return generateServiceView(hosts); } public boolean stateTransferListenersPresent() { return state_transfer_listeners != null && !state_transfer_listeners.isEmpty(); } public synchronized void registerForStateTransfer(String appl_id, String substate_id) { String key=appl_id; if(substate_id != null && substate_id.length() > 0) key+=SEPARATOR + substate_id; state_transfer_listeners.put(key, Boolean.FALSE); } public synchronized boolean getState(Address target, String id, long timeout) throws ChannelNotConnectedException, ChannelClosedException { if(state_transfer_listeners == null) return false; Map.Entry entry; String key; for(Iterator it=state_transfer_listeners.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); key=(String)entry.getKey(); int index=key.indexOf(SEPARATOR); boolean match; if(index > -1) { String tmp=key.substring(0, index); match=id.equals(tmp); } else { match=id.equals(key); } if(match) { entry.setValue(Boolean.TRUE); break; } } Collection values=state_transfer_listeners.values(); boolean all_true=Util.all(values, Boolean.TRUE); if(!all_true) return true; // pseudo boolean rc=false; Set keys=new HashSet(state_transfer_listeners.keySet()); rc=fetchServiceStates(target, keys, timeout); state_transfer_listeners.clear(); return rc; } /** Fetches the app states for all service IDs in keys. * The keys are a duplicate list, so it cannot be modified by the caller of this method * @param keys */ private boolean fetchServiceStates(Address target, Set keys, long timeout) throws ChannelClosedException, ChannelNotConnectedException { boolean rc, all_rcs=true; String appl_id; for(Iterator it=keys.iterator(); it.hasNext();) { appl_id=(String)it.next(); rc=channel.getState(target, appl_id, timeout); if(rc == false) all_rcs=false; } return all_rcs; } /** * Fetches the map of services and hosts from the coordinator (Multiplexer). No-op if we are the coordinator */ public void fetchServiceInformation() throws Exception { while(true) { Address coord=getCoordinator(), local_address=channel != null? channel.getLocalAddress() : null; boolean is_coord=coord != null && local_address != null && local_address.equals(coord); if(is_coord) { if(log.isTraceEnabled()) log.trace("I'm coordinator, will not fetch service state information"); break; } ServiceInfo si=new ServiceInfo(ServiceInfo.STATE_REQ, null, null, null); MuxHeader hdr=new MuxHeader(si); Message state_req=new Message(coord, null, null); state_req.putHeader(NAME, hdr); service_state_promise.reset(); channel.send(state_req); try { byte[] state=(byte[])service_state_promise.getResultWithTimeout(2000); if(state != null) { Map new_state=(Map)Util.objectFromByteBuffer(state); synchronized(service_state) { service_state.clear(); service_state.putAll(new_state); } if(log.isTraceEnabled()) log.trace("service state was set successfully (" + service_state.size() + " entries)"); } else { if(log.isWarnEnabled()) log.warn("received service state was null"); } break; } catch(TimeoutException e) { if(log.isTraceEnabled()) log.trace("timed out waiting for service state from " + coord + ", retrying"); } } } public void sendServiceUpMessage(String service, Address host,boolean bypassFlush) throws Exception { sendServiceMessage(ServiceInfo.SERVICE_UP, service, host,bypassFlush); if(local_addr != null && host != null && local_addr.equals(host)) handleServiceUp(service, host, false); } public void sendServiceDownMessage(String service, Address host,boolean bypassFlush) throws Exception { sendServiceMessage(ServiceInfo.SERVICE_DOWN, service, host,bypassFlush); if(local_addr != null && host != null && local_addr.equals(host)) handleServiceDown(service, host, false); } /** * Remove mux header and dispatch to correct MuxChannel * @param evt * @return */ public Object up(final Event evt) { switch(evt.getType()) { case Event.MSG: final Message msg=(Message)evt.getArg(); final MuxHeader hdr=(MuxHeader)msg.getHeader(NAME); if(hdr == null) { log.error("MuxHeader not present - discarding message " + msg); return null; } Address sender=msg.getSrc(); if(hdr.info != null) { // it is a service state request - not a default multiplex request try { handleServiceStateRequest(hdr.info, sender); } catch(Exception e) { if(log.isErrorEnabled()) log.error("failure in handling service state request", e); } break; } MuxChannel mux_ch=services.get(hdr.id); if(mux_ch == null) { log.warn("service " + hdr.id + " not currently running, discarding message " + msg); return null; } return passToMuxChannel(mux_ch, evt, fifo_queue, sender, hdr.id, false); // don't block ! case Event.VIEW_CHANGE: Vector old_members=view != null? view.getMembers() : null; view=(View)evt.getArg(); Vector new_members=view != null? view.getMembers() : null; Vector left_members=Util.determineLeftMembers(old_members, new_members); if(view instanceof MergeView) { temp_merge_view=(MergeView)view.clone(); if(log.isTraceEnabled()) log.trace("received a MergeView: " + temp_merge_view + ", adjusting the service view"); if(!flush_present && temp_merge_view != null) { try { if(log.isTraceEnabled()) log.trace("calling handleMergeView() from VIEW_CHANGE (flush_present=" + flush_present + ")"); Thread merge_handler=new Thread() { public void run() { try { handleMergeView(temp_merge_view); } catch(Exception e) { if(log.isErrorEnabled()) log.error("problems handling merge view", e); } } }; merge_handler.setName("merge handler view_change"); merge_handler.setDaemon(false); merge_handler.start(); } catch(Exception e) { if(log.isErrorEnabled()) log.error("failed handling merge view", e); } } else { ; // don't do anything because we are blocked sending messages anyway } } else { // regular view synchronized(service_responses) { service_responses.clear(); } } if(!left_members.isEmpty()) adjustServiceViews(left_members); break; case Event.SUSPECT: Address suspected_mbr=(Address)evt.getArg(); synchronized(service_responses) { service_responses.put(suspected_mbr, null); service_responses.notifyAll(); } passToAllMuxChannels(evt); break; case Event.GET_APPLSTATE: case Event.STATE_TRANSFER_OUTPUTSTREAM: return handleStateRequest(evt); case Event.GET_STATE_OK: case Event.STATE_TRANSFER_INPUTSTREAM: handleStateResponse(evt); break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); passToAllMuxChannels(evt); break; case Event.BLOCK: blocked=true; if(!services.isEmpty()) { passToAllMuxChannels(evt); } return null; case Event.UNBLOCK: // process queued-up MergeViews if(!blocked) { passToAllMuxChannels(evt); return null; } else blocked=false; if(temp_merge_view != null) { if(log.isTraceEnabled()) log.trace("calling handleMergeView() from UNBLOCK (flush_present=" + flush_present + ")"); try { Thread merge_handler=new Thread() { public void run() { try { handleMergeView(temp_merge_view); } catch(Exception e) { if(log.isErrorEnabled()) log.error("problems handling merge view", e); } } }; merge_handler.setName("merge handler (unblock)"); merge_handler.setDaemon(false); merge_handler.start(); } catch(Exception e) { if(log.isErrorEnabled()) log.error("failed handling merge view", e); } } passToAllMuxChannels(evt); break; default: passToAllMuxChannels(evt); break; } return null; } public Channel createMuxChannel(JChannelFactory f, String id, String stack_name) throws Exception { MuxChannel ch; synchronized(services) { if(services.containsKey(id)) throw new Exception("service ID \"" + id + "\" is already registered, cannot register duplicate ID"); ch=new MuxChannel(f, channel, id, stack_name, this); services.put(id, ch); } return ch; } private void passToAllMuxChannels(Event evt) { String service_name; MuxChannel ch; for(Map.Entry<String,MuxChannel> entry: services.entrySet()) { service_name=entry.getKey(); ch=entry.getValue(); // these events are directly delivered, don't get added to any queue passToMuxChannel(ch, evt, fifo_queue, null, service_name, false); } } public MuxChannel remove(String id) { synchronized(services) { return services.remove(id); } } /** Closes the underlying JChannel if all MuxChannels have been disconnected */ public void disconnect() { boolean all_disconnected=true; synchronized(services) { for(MuxChannel mux_ch: services.values()) { if(mux_ch.isConnected()) { all_disconnected=false; break; } } if(all_disconnected) { if(log.isTraceEnabled()) { log.trace("disconnecting underlying JChannel as all MuxChannels are disconnected"); } channel.disconnect(); } } } public void unregister(String appl_id) { synchronized(services) { services.remove(appl_id); } } public boolean close() { boolean all_closed=true; synchronized(services) { for(MuxChannel mux_ch: services.values()) { if(mux_ch.isOpen()) { all_closed=false; break; } } if(all_closed) { if(log.isTraceEnabled()) { log.trace("closing underlying JChannel as all MuxChannels are closed"); } channel.close(); services.clear(); } return all_closed; } } public void closeAll() { synchronized(services) { for(MuxChannel mux_ch: services.values()) { mux_ch.setConnected(false); mux_ch.setClosed(true); mux_ch.closeMessageQueue(true); } } } public boolean shutdown() { boolean all_closed=true; synchronized(services) { for(MuxChannel mux_ch: services.values()) { if(mux_ch.isOpen()) { all_closed=false; break; } } if(all_closed) { if(log.isTraceEnabled()) { log.trace("shutting down underlying JChannel as all MuxChannels are closed"); } channel.shutdown(); services.clear(); } return all_closed; } } private boolean isFlushPresent() { return channel.getProtocolStack().findProtocol("FLUSH") != null; } private void sendServiceState() throws Exception { Object[] my_services=services.keySet().toArray(); byte[] data=Util.objectToByteBuffer(my_services); ServiceInfo sinfo=new ServiceInfo(ServiceInfo.LIST_SERVICES_RSP, null, channel.getLocalAddress(), data); Message rsp=new Message(); // send to everyone MuxHeader hdr=new MuxHeader(sinfo); rsp.putHeader(NAME, hdr); channel.send(rsp); } private Address getLocalAddress() { if(local_addr != null) return local_addr; if(channel != null) local_addr=channel.getLocalAddress(); return local_addr; } private Address getCoordinator() { if(channel != null) { View v=channel.getView(); if(v != null) { Vector members=v.getMembers(); if(members != null && !members.isEmpty()) { return (Address)members.firstElement(); } } } return null; } /** * Returns an Address of a state provider for a given service_id. * If preferredTarget is a member of a service view for a given service_id * then preferredTarget is returned. Otherwise, service view coordinator is * returned if such node exists. If service view is empty for a given service_id * null is returned. * * @param preferredTarget * @param service_id * @return */ public Address getStateProvider(Address preferredTarget, String service_id) { Address result = null; List hosts=service_state.get(service_id); if(hosts != null && !hosts.isEmpty()){ if(hosts.contains(preferredTarget)){ result = preferredTarget; } else{ result = (Address)hosts.get(0); } } return result; } private void sendServiceMessage(byte type, String service, Address host,boolean bypassFlush) throws Exception { if(host == null) host=getLocalAddress(); if(host == null) { if(log.isWarnEnabled()) { log.warn("local_addr is null, cannot send ServiceInfo." + ServiceInfo.typeToString(type) + " message"); } return; } ServiceInfo si=new ServiceInfo(type, service, host, null); MuxHeader hdr=new MuxHeader(si); Message service_msg=new Message(); service_msg.putHeader(NAME, hdr); if(bypassFlush) service_msg.putHeader(FLUSH.NAME, new FLUSH.FlushHeader(FLUSH.FlushHeader.FLUSH_BYPASS)); channel.send(service_msg); } private Object handleStateRequest(Event evt) { StateTransferInfo info=(StateTransferInfo)evt.getArg(); String id=info.state_id; String original_id=id; Address requester=info.target; // the sender of the state request try { int index=id.indexOf(SEPARATOR); if(index > -1) { info.state_id=id.substring(index + SEPARATOR_LEN); id=id.substring(0, index); // similar reuse as above... } else { info.state_id=null; } MuxChannel mux_ch=services.get(id); if(mux_ch == null) throw new IllegalArgumentException("didn't find service with ID=" + id + " to fetch state from"); // state_id will be null, get regular state from the service named state_id StateTransferInfo ret=(StateTransferInfo)passToMuxChannel(mux_ch, evt, fifo_queue, requester, id, true); ret.state_id=original_id; return ret; } catch(Throwable ex) { if(log.isErrorEnabled()) log.error("failed returning the application state, will return null", ex); return new StateTransferInfo(null, original_id, 0L, null); } } private void handleStateResponse(Event evt) { StateTransferInfo info=(StateTransferInfo)evt.getArg(); MuxChannel mux_ch; Address state_sender=info.target; String appl_id, substate_id, tmp; tmp=info.state_id; if(tmp == null) { if(log.isTraceEnabled()) log.trace("state is null, not passing up: " + info); return; } int index=tmp.indexOf(SEPARATOR); if(index > -1) { appl_id=tmp.substring(0, index); substate_id=tmp.substring(index+SEPARATOR_LEN); } else { appl_id=tmp; substate_id=null; } mux_ch=services.get(appl_id); if(mux_ch == null) { log.error("didn't find service with ID=" + appl_id + " to fetch state from"); } else { StateTransferInfo tmp_info=info.copy(); tmp_info.state_id=substate_id; Event tmpEvt=new Event(evt.getType(), tmp_info); passToMuxChannel(mux_ch, tmpEvt, fifo_queue, state_sender, appl_id, false); } } private void handleServiceStateRequest(ServiceInfo info, Address sender) throws Exception { switch(info.type) { case ServiceInfo.STATE_REQ: byte[] state; synchronized(service_state) { state=Util.objectToByteBuffer(service_state); } ServiceInfo si=new ServiceInfo(ServiceInfo.STATE_RSP, null, null, state); MuxHeader hdr=new MuxHeader(si); Message state_rsp=new Message(sender); state_rsp.putHeader(NAME, hdr); channel.send(state_rsp); break; case ServiceInfo.STATE_RSP: service_state_promise.setResult(info.state); break; case ServiceInfo.SERVICE_UP: handleServiceUp(info.service, info.host, true); break; case ServiceInfo.SERVICE_DOWN: handleServiceDown(info.service, info.host, true); break; case ServiceInfo.LIST_SERVICES_RSP: handleServicesRsp(sender, info.state); break; default: if(log.isErrorEnabled()) log.error("service request type " + info.type + " not known"); break; } } private void handleServicesRsp(Address sender, byte[] state) throws Exception { Object[] keys=(Object[])Util.objectFromByteBuffer(state); Set s=new HashSet(); for(int i=0; i < keys.length; i++) s.add(keys[i]); synchronized(service_responses) { Set tmp=service_responses.get(sender); if(tmp == null) tmp=new HashSet(); tmp.addAll(s); service_responses.put(sender, tmp); if(log.isTraceEnabled()) log.trace("received service response: " + sender + "(" + s.toString() + ")"); service_responses.notifyAll(); } } private void handleServiceDown(String service, Address host, boolean received) { List hosts, hosts_copy; boolean removed=false; // discard if we sent this message if(received && host != null && local_addr != null && local_addr.equals(host)) { return; } synchronized(service_state) { hosts=service_state.get(service); if(hosts == null) return; removed=hosts.remove(host); hosts_copy=new ArrayList(hosts); // make a copy so we don't modify hosts in generateServiceView() } if(removed) { View service_view=generateServiceView(hosts_copy); if(service_view != null) { MuxChannel ch=services.get(service); if(ch != null) { Event view_evt=new Event(Event.VIEW_CHANGE, service_view); // ch.up(view_evt); passToMuxChannel(ch, view_evt, fifo_queue, null, service, false); } else { if(log.isTraceEnabled()) log.trace("service " + service + " not found, cannot dispatch service view " + service_view); } } } Address local_address=getLocalAddress(); if(local_address != null && host != null && host.equals(local_address)) unregister(service); } private void handleServiceUp(String service, Address host, boolean received) { List hosts, hosts_copy; boolean added=false; // discard if we sent this message if(received && host != null && local_addr != null && local_addr.equals(host)) { return; } synchronized(service_state) { hosts=service_state.get(service); if(hosts == null) { hosts=new ArrayList(); service_state.put(service, hosts); } if(!hosts.contains(host)) { hosts.add(host); added=true; } hosts_copy=new ArrayList(hosts); // make a copy so we don't modify hosts in generateServiceView() } if(added) { View service_view=generateServiceView(hosts_copy); if(service_view != null) { MuxChannel ch=services.get(service); if(ch != null) { Event view_evt=new Event(Event.VIEW_CHANGE, service_view); // ch.up(view_evt); passToMuxChannel(ch, view_evt, fifo_queue, null, service, false); } else { if(log.isTraceEnabled()) log.trace("service " + service + " not found, cannot dispatch service view " + service_view); } } } } /** * Fetches the service states from everyone else in the cluster. Once all states have been received and inserted into * service_state, compute a service view (a copy of MergeView) for each service and pass it up * @param view */ private void handleMergeView(MergeView view) throws Exception { long time_to_wait=SERVICES_RSP_TIMEOUT, start; int num_members=view.size(); // include myself Map copy=null; sendServiceState(); synchronized(service_responses) { start=System.currentTimeMillis(); try { while(time_to_wait > 0 && numResponses(service_responses) < num_members) { service_responses.wait(time_to_wait); time_to_wait-=System.currentTimeMillis() - start; } copy=new HashMap(service_responses); } catch(Exception ex) { if(log.isErrorEnabled()) log.error("failed fetching a list of services from other members in the cluster, cannot handle merge view " + view, ex); } } if(log.isTraceEnabled()) log.trace("merging service state, my service_state: " + service_state + ", received responses: " + copy); // merges service_responses with service_state and emits MergeViews for the services affected (MuxChannel) mergeServiceState(view, copy); service_responses.clear(); temp_merge_view=null; } private int numResponses(Map m) { int num=0; Collection values=m.values(); for(Iterator it=values.iterator(); it.hasNext();) { if(it.next() != null) num++; } return num; } private void mergeServiceState(MergeView view, Map copy) { Set modified_services=new HashSet(); Map.Entry entry; Address host; // address of the sender Set service_list; // Set<String> of services List my_services; String service; synchronized(service_state) { for(Iterator it=copy.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); host=(Address)entry.getKey(); service_list=(Set)entry.getValue(); if(service_list == null) continue; for(Iterator it2=service_list.iterator(); it2.hasNext();) { service=(String)it2.next(); my_services=service_state.get(service); if(my_services == null) { my_services=new ArrayList(); service_state.put(service, my_services); } boolean was_modified=my_services.add(host); if(was_modified) { modified_services.add(service); } } } } // now emit MergeViews for all services which were modified for(Iterator it=modified_services.iterator(); it.hasNext();) { service=(String)it.next(); MuxChannel ch=services.get(service); my_services=service_state.get(service); MergeView v=(MergeView)view.clone(); v.getMembers().retainAll(my_services); Event evt=new Event(Event.VIEW_CHANGE, v); // ch.up(evt); passToMuxChannel(ch, evt, fifo_queue, null, service, false); } } private void adjustServiceViews(Vector left_members) { if(left_members != null) for(int i=0; i < left_members.size(); i++) { try { adjustServiceView((Address)left_members.elementAt(i)); } catch(Throwable t) { if(log.isErrorEnabled()) log.error("failed adjusting service views", t); } } } private void adjustServiceView(Address host) { Map.Entry entry; List hosts, hosts_copy; String service; boolean removed=false; synchronized(service_state) { for(Iterator it=service_state.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); service=(String)entry.getKey(); hosts=(List)entry.getValue(); if(hosts == null) continue; removed=hosts.remove(host); hosts_copy=new ArrayList(hosts); // make a copy so we don't modify hosts in generateServiceView() if(removed) { View service_view=generateServiceView(hosts_copy); if(service_view != null) { MuxChannel ch=services.get(service); if(ch != null) { Event view_evt=new Event(Event.VIEW_CHANGE, service_view); // ch.up(view_evt); passToMuxChannel(ch, view_evt, fifo_queue, null, service, false); } else { if(log.isTraceEnabled()) log.trace("service " + service + " not found, cannot dispatch service view " + service_view); } } } Address local_address=getLocalAddress(); if(local_address != null && host != null && host.equals(local_address)) unregister(service); } } } /** * Create a copy of view which contains only members which are present in hosts. Call viewAccepted() on the MuxChannel * which corresponds with service. If no members are removed or added from/to view, this is a no-op. * @param hosts List<Address> * @return the servicd view (a modified copy of the real view), or null if the view was not modified */ private View generateServiceView(List hosts) { Vector members=new Vector(view.getMembers()); members.retainAll(hosts); return new View(view.getVid(), members); } /** Tell the underlying channel to start the flush protocol, this will be handled by FLUSH */ private void startFlush() { channel.down(new Event(Event.SUSPEND)); } /** Tell the underlying channel to stop the flush, and resume message sending. This will be handled by FLUSH */ private void stopFlush() { channel.down(new Event(Event.RESUME)); } private Object passToMuxChannel(MuxChannel ch, Event evt, final FIFOMessageQueue<String,Runnable> queue, final Address sender, final String dest, boolean block) { if(thread_pool == null) return ch.up(evt); Task task=new Task(ch, evt, queue, sender, dest, block); ExecuteTask execute_task=new ExecuteTask(fifo_queue); // takes Task from queue and executes it try { fifo_queue.put(sender, dest, task); thread_pool.execute(execute_task); if(block) { try { return task.exchanger.exchange(null); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); } return null; } public void addServiceIfNotPresent(String id, MuxChannel ch) { MuxChannel tmp; synchronized(services) { tmp=services.get(id); if(tmp == null) { services.put(id, ch); } } } private static class Task implements Runnable { Exchanger<Object> exchanger; MuxChannel channel; Event evt; FIFOMessageQueue<String,Runnable> queue; Address sender; String dest; Task(MuxChannel channel, Event evt, FIFOMessageQueue<String,Runnable> queue, Address sender, String dest, boolean result_expected) { this.channel=channel; this.evt=evt; this.queue=queue; this.sender=sender; this.dest=dest; if(result_expected) exchanger=new Exchanger<Object>(); } public void run() { Object retval; try { retval=channel.up(evt); if(exchanger != null) exchanger.exchange(retval); } catch(InterruptedException e) { Thread.currentThread().interrupt(); // let the thread pool handle the interrupt - we're done anyway } finally { queue.done(sender, dest); } } } private static class ExecuteTask implements Runnable { FIFOMessageQueue<String,Runnable> queue; public ExecuteTask(FIFOMessageQueue<String,Runnable> queue) { this.queue=queue; } public void run() { try { Runnable task=queue.take(); task.run(); } catch(InterruptedException e) { } } } }
src/org/jgroups/mux/Multiplexer.java
package org.jgroups.mux; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.*; import org.jgroups.TimeoutException; import org.jgroups.protocols.pbcast.FLUSH; import org.jgroups.stack.StateTransferInfo; import org.jgroups.util.FIFOMessageQueue; import org.jgroups.util.Promise; import org.jgroups.util.Util; import java.util.*; import java.util.concurrent.*; /** * Used for dispatching incoming messages. The Multiplexer implements UpHandler and registers with the associated * JChannel (there can only be 1 Multiplexer per JChannel). When up() is called with a message, the header of the * message is removed and the MuxChannel corresponding to the header's service ID is retrieved from the map, * and MuxChannel.up() is called with the message. * @author Bela Ban * @version $Id: Multiplexer.java,v 1.50 2007/03/05 09:34:46 belaban Exp $ */ public class Multiplexer implements UpHandler { /** Map<String,MuxChannel>. Maintains the mapping between service IDs and their associated MuxChannels */ private final Map<String,MuxChannel> services=new HashMap<String,MuxChannel>(); private final JChannel channel; static final Log log=LogFactory.getLog(Multiplexer.class); static final String SEPARATOR="::"; static final short SEPARATOR_LEN=(short)SEPARATOR.length(); static final String NAME="MUX"; private MergeView temp_merge_view=null; private boolean flush_present=true; private boolean blocked=false; /** Thread pool to concurrently process messages sent to different services */ private static Executor thread_pool=null; /** To make sure messages sent to different services are processed concurrently (using the thread pool above), but * messages to the same service are processed FIFO */ private FIFOMessageQueue<String,Runnable> fifo_queue=new FIFOMessageQueue<String,Runnable>(); /** Cluster view */ View view=null; Address local_addr=null; /** Map<String,Boolean>. Map of service IDs and booleans that determine whether getState() has already been called */ private final Map<String,Boolean> state_transfer_listeners=new HashMap<String,Boolean>(); /** Map<String,List<Address>>. A map of services as keys and lists of hosts as values */ private final Map<String,List<Address>> service_state=new HashMap<String,List<Address>>(); /** Used to wait on service state information */ private final Promise service_state_promise=new Promise(); /** Map<Address, Set<String>>. Keys are senders, values are a set of services hosted by that sender. * Used to collect responses to LIST_SERVICES_REQ */ private final Map<Address, Set<String>> service_responses=new HashMap<Address, Set<String>>(); private long SERVICES_RSP_TIMEOUT=10000; static { int min_threads=1, max_threads=4; long keep_alive=30000; boolean mux_enabled=true; // default is to use the thread pool String tmp; try { tmp=System.getProperty(Global.MUX_ENABLED); if(tmp != null) mux_enabled=Boolean.parseBoolean(tmp); } catch(Throwable t) {} if(mux_enabled) { ThreadFactory factory=new ThreadFactory() { int num=1; ThreadGroup mux_threads=new ThreadGroup(Util.getGlobalThreadGroup(), "MultiplexerThreads"); public Thread newThread(Runnable command) { return new Thread(mux_threads, command, "Multiplexer-" + num++); } }; try { tmp=System.getProperty(Global.MUX_MIN_THREADS); if(tmp != null) min_threads=Integer.parseInt(tmp); } catch(Throwable t) {} try { tmp=System.getProperty(Global.MUX_MAX_THREADS); if(tmp != null) max_threads=Integer.parseInt(tmp); } catch(Throwable t) {} try { tmp=System.getProperty(Global.MUX_KEEPALIVE); if(tmp != null) keep_alive=Long.parseLong(tmp); } catch(Throwable t) {} thread_pool=new ThreadPoolExecutor(min_threads, max_threads, keep_alive, TimeUnit.MILLISECONDS, new SynchronousQueue(), factory, new ThreadPoolExecutor.CallerRunsPolicy()); } } public Multiplexer() { this.channel=null; flush_present=isFlushPresent(); } public Multiplexer(JChannel channel) { this.channel=channel; this.channel.setUpHandler(this); this.channel.setOpt(Channel.BLOCK, Boolean.TRUE); // we want to handle BLOCK events ourselves flush_present=isFlushPresent(); } /** * @deprecated Use ${link #getServiceIds()} instead * @return The set of service IDs */ public Set getApplicationIds() { return services != null? services.keySet() : null; } public Set<String> getServiceIds() { return services != null? services.keySet() : null; } public long getServicesResponseTimeout() { return SERVICES_RSP_TIMEOUT; } public void setServicesResponseTimeout(long services_rsp_timeout) { this.SERVICES_RSP_TIMEOUT=services_rsp_timeout; } /** Returns a copy of the current view <em>minus</em> the nodes on which service service_id is <em>not</em> running * * @param service_id * @return The service view */ public View getServiceView(String service_id) { List hosts=service_state.get(service_id); if(hosts == null) return null; return generateServiceView(hosts); } public boolean stateTransferListenersPresent() { return state_transfer_listeners != null && !state_transfer_listeners.isEmpty(); } public synchronized void registerForStateTransfer(String appl_id, String substate_id) { String key=appl_id; if(substate_id != null && substate_id.length() > 0) key+=SEPARATOR + substate_id; state_transfer_listeners.put(key, Boolean.FALSE); } public synchronized boolean getState(Address target, String id, long timeout) throws ChannelNotConnectedException, ChannelClosedException { if(state_transfer_listeners == null) return false; Map.Entry entry; String key; for(Iterator it=state_transfer_listeners.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); key=(String)entry.getKey(); int index=key.indexOf(SEPARATOR); boolean match; if(index > -1) { String tmp=key.substring(0, index); match=id.equals(tmp); } else { match=id.equals(key); } if(match) { entry.setValue(Boolean.TRUE); break; } } Collection values=state_transfer_listeners.values(); boolean all_true=Util.all(values, Boolean.TRUE); if(!all_true) return true; // pseudo boolean rc=false; Set keys=new HashSet(state_transfer_listeners.keySet()); rc=fetchServiceStates(target, keys, timeout); state_transfer_listeners.clear(); return rc; } /** Fetches the app states for all service IDs in keys. * The keys are a duplicate list, so it cannot be modified by the caller of this method * @param keys */ private boolean fetchServiceStates(Address target, Set keys, long timeout) throws ChannelClosedException, ChannelNotConnectedException { boolean rc, all_rcs=true; String appl_id; for(Iterator it=keys.iterator(); it.hasNext();) { appl_id=(String)it.next(); rc=channel.getState(target, appl_id, timeout); if(rc == false) all_rcs=false; } return all_rcs; } /** * Fetches the map of services and hosts from the coordinator (Multiplexer). No-op if we are the coordinator */ public void fetchServiceInformation() throws Exception { while(true) { Address coord=getCoordinator(), local_address=channel != null? channel.getLocalAddress() : null; boolean is_coord=coord != null && local_address != null && local_address.equals(coord); if(is_coord) { if(log.isTraceEnabled()) log.trace("I'm coordinator, will not fetch service state information"); break; } ServiceInfo si=new ServiceInfo(ServiceInfo.STATE_REQ, null, null, null); MuxHeader hdr=new MuxHeader(si); Message state_req=new Message(coord, null, null); state_req.putHeader(NAME, hdr); service_state_promise.reset(); channel.send(state_req); try { byte[] state=(byte[])service_state_promise.getResultWithTimeout(2000); if(state != null) { Map new_state=(Map)Util.objectFromByteBuffer(state); synchronized(service_state) { service_state.clear(); service_state.putAll(new_state); } if(log.isTraceEnabled()) log.trace("service state was set successfully (" + service_state.size() + " entries)"); } else { if(log.isWarnEnabled()) log.warn("received service state was null"); } break; } catch(TimeoutException e) { if(log.isTraceEnabled()) log.trace("timed out waiting for service state from " + coord + ", retrying"); } } } public void sendServiceUpMessage(String service, Address host,boolean bypassFlush) throws Exception { sendServiceMessage(ServiceInfo.SERVICE_UP, service, host,bypassFlush); if(local_addr != null && host != null && local_addr.equals(host)) handleServiceUp(service, host, false); } public void sendServiceDownMessage(String service, Address host,boolean bypassFlush) throws Exception { sendServiceMessage(ServiceInfo.SERVICE_DOWN, service, host,bypassFlush); if(local_addr != null && host != null && local_addr.equals(host)) handleServiceDown(service, host, false); } /** * Remove mux header and dispatch to correct MuxChannel * @param evt * @return */ public Object up(final Event evt) { switch(evt.getType()) { case Event.MSG: final Message msg=(Message)evt.getArg(); final MuxHeader hdr=(MuxHeader)msg.getHeader(NAME); if(hdr == null) { log.error("MuxHeader not present - discarding message " + msg); return null; } Address sender=msg.getSrc(); if(hdr.info != null) { // it is a service state request - not a default multiplex request try { handleServiceStateRequest(hdr.info, sender); } catch(Exception e) { if(log.isErrorEnabled()) log.error("failure in handling service state request", e); } break; } MuxChannel mux_ch=services.get(hdr.id); if(mux_ch == null) { log.warn("service " + hdr.id + " not currently running, discarding message " + msg); return null; } return passToMuxChannel(mux_ch, evt, fifo_queue, sender, hdr.id, false); // don't block ! case Event.VIEW_CHANGE: Vector old_members=view != null? view.getMembers() : null; view=(View)evt.getArg(); Vector new_members=view != null? view.getMembers() : null; Vector left_members=Util.determineLeftMembers(old_members, new_members); if(view instanceof MergeView) { temp_merge_view=(MergeView)view.clone(); if(log.isTraceEnabled()) log.trace("received a MergeView: " + temp_merge_view + ", adjusting the service view"); if(!flush_present && temp_merge_view != null) { try { if(log.isTraceEnabled()) log.trace("calling handleMergeView() from VIEW_CHANGE (flush_present=" + flush_present + ")"); Thread merge_handler=new Thread() { public void run() { try { handleMergeView(temp_merge_view); } catch(Exception e) { if(log.isErrorEnabled()) log.error("problems handling merge view", e); } } }; merge_handler.setName("merge handler view_change"); merge_handler.setDaemon(false); merge_handler.start(); } catch(Exception e) { if(log.isErrorEnabled()) log.error("failed handling merge view", e); } } else { ; // don't do anything because we are blocked sending messages anyway } } else { // regular view synchronized(service_responses) { service_responses.clear(); } } if(!left_members.isEmpty()) adjustServiceViews(left_members); break; case Event.SUSPECT: Address suspected_mbr=(Address)evt.getArg(); synchronized(service_responses) { service_responses.put(suspected_mbr, null); service_responses.notifyAll(); } passToAllMuxChannels(evt); break; case Event.GET_APPLSTATE: case Event.STATE_TRANSFER_OUTPUTSTREAM: return handleStateRequest(evt); case Event.GET_STATE_OK: case Event.STATE_TRANSFER_INPUTSTREAM: handleStateResponse(evt); break; case Event.SET_LOCAL_ADDRESS: local_addr=(Address)evt.getArg(); passToAllMuxChannels(evt); break; case Event.BLOCK: blocked=true; if(!services.isEmpty()) { passToAllMuxChannels(evt); } return null; case Event.UNBLOCK: // process queued-up MergeViews if(!blocked) { passToAllMuxChannels(evt); return null; } else blocked=false; if(temp_merge_view != null) { if(log.isTraceEnabled()) log.trace("calling handleMergeView() from UNBLOCK (flush_present=" + flush_present + ")"); try { Thread merge_handler=new Thread() { public void run() { try { handleMergeView(temp_merge_view); } catch(Exception e) { if(log.isErrorEnabled()) log.error("problems handling merge view", e); } } }; merge_handler.setName("merge handler (unblock)"); merge_handler.setDaemon(false); merge_handler.start(); } catch(Exception e) { if(log.isErrorEnabled()) log.error("failed handling merge view", e); } } passToAllMuxChannels(evt); break; default: passToAllMuxChannels(evt); break; } return null; } public Channel createMuxChannel(JChannelFactory f, String id, String stack_name) throws Exception { MuxChannel ch; synchronized(services) { if(services.containsKey(id)) throw new Exception("service ID \"" + id + "\" is already registered, cannot register duplicate ID"); ch=new MuxChannel(f, channel, id, stack_name, this); services.put(id, ch); } return ch; } private void passToAllMuxChannels(Event evt) { String service_name; MuxChannel ch; for(Map.Entry<String,MuxChannel> entry: services.entrySet()) { service_name=entry.getKey(); ch=entry.getValue(); // these events are directly delivered, don't get added to any queue passToMuxChannel(ch, evt, fifo_queue, null, service_name, false); } } public MuxChannel remove(String id) { synchronized(services) { return services.remove(id); } } /** Closes the underlying JChannel if all MuxChannels have been disconnected */ public void disconnect() { boolean all_disconnected=true; synchronized(services) { for(MuxChannel mux_ch: services.values()) { if(mux_ch.isConnected()) { all_disconnected=false; break; } } if(all_disconnected) { if(log.isTraceEnabled()) { log.trace("disconnecting underlying JChannel as all MuxChannels are disconnected"); } channel.disconnect(); } } } public void unregister(String appl_id) { synchronized(services) { services.remove(appl_id); } } public boolean close() { boolean all_closed=true; synchronized(services) { for(MuxChannel mux_ch: services.values()) { if(mux_ch.isOpen()) { all_closed=false; break; } } if(all_closed) { if(log.isTraceEnabled()) { log.trace("closing underlying JChannel as all MuxChannels are closed"); } channel.close(); services.clear(); } return all_closed; } } public void closeAll() { synchronized(services) { for(MuxChannel mux_ch: services.values()) { mux_ch.setConnected(false); mux_ch.setClosed(true); mux_ch.closeMessageQueue(true); } } } public boolean shutdown() { boolean all_closed=true; synchronized(services) { for(MuxChannel mux_ch: services.values()) { if(mux_ch.isOpen()) { all_closed=false; break; } } if(all_closed) { if(log.isTraceEnabled()) { log.trace("shutting down underlying JChannel as all MuxChannels are closed"); } channel.shutdown(); services.clear(); } return all_closed; } } private boolean isFlushPresent() { return channel.getProtocolStack().findProtocol("FLUSH") != null; } private void sendServiceState() throws Exception { Object[] my_services=services.keySet().toArray(); byte[] data=Util.objectToByteBuffer(my_services); ServiceInfo sinfo=new ServiceInfo(ServiceInfo.LIST_SERVICES_RSP, null, channel.getLocalAddress(), data); Message rsp=new Message(); // send to everyone MuxHeader hdr=new MuxHeader(sinfo); rsp.putHeader(NAME, hdr); channel.send(rsp); } private Address getLocalAddress() { if(local_addr != null) return local_addr; if(channel != null) local_addr=channel.getLocalAddress(); return local_addr; } private Address getCoordinator() { if(channel != null) { View v=channel.getView(); if(v != null) { Vector members=v.getMembers(); if(members != null && !members.isEmpty()) { return (Address)members.firstElement(); } } } return null; } /** * Returns an Address of a state provider for a given service_id. * If preferredTarget is a member of a service view for a given service_id * then preferredTarget is returned. Otherwise, service view coordinator is * returned if such node exists. If service view is empty for a given service_id * null is returned. * * @param preferredTarget * @param service_id * @return */ public Address getStateProvider(Address preferredTarget, String service_id) { Address result = null; List hosts=service_state.get(service_id); if(hosts != null && !hosts.isEmpty()){ if(hosts.contains(preferredTarget)){ result = preferredTarget; } else{ result = (Address)hosts.get(0); } } return result; } private void sendServiceMessage(byte type, String service, Address host,boolean bypassFlush) throws Exception { if(host == null) host=getLocalAddress(); if(host == null) { if(log.isWarnEnabled()) { log.warn("local_addr is null, cannot send ServiceInfo." + ServiceInfo.typeToString(type) + " message"); } return; } ServiceInfo si=new ServiceInfo(type, service, host, null); MuxHeader hdr=new MuxHeader(si); Message service_msg=new Message(); service_msg.putHeader(NAME, hdr); if(bypassFlush) service_msg.putHeader(FLUSH.NAME, new FLUSH.FlushHeader(FLUSH.FlushHeader.FLUSH_BYPASS)); channel.send(service_msg); } private Object handleStateRequest(Event evt) { StateTransferInfo info=(StateTransferInfo)evt.getArg(); String id=info.state_id; String original_id=id; Address requester=info.target; // the sender of the state request try { int index=id.indexOf(SEPARATOR); if(index > -1) { info.state_id=id.substring(index + SEPARATOR_LEN); id=id.substring(0, index); // similar reuse as above... } else { info.state_id=null; } MuxChannel mux_ch=services.get(id); if(mux_ch == null) throw new IllegalArgumentException("didn't find service with ID=" + id + " to fetch state from"); // return mux_ch.up(evt); // state_id will be null, get regular state from the service named state_id // state_id will be null, get regular state from the service named state_id StateTransferInfo ret=(StateTransferInfo)passToMuxChannel(mux_ch, evt, fifo_queue, requester, id, true); ret.state_id=original_id; return ret; } catch(Throwable ex) { if(log.isErrorEnabled()) log.error("failed returning the application state, will return null", ex); return new StateTransferInfo(null, original_id, 0L, null); } } private void handleStateResponse(Event evt) { StateTransferInfo info=(StateTransferInfo)evt.getArg(); MuxChannel mux_ch; Address state_sender=info.target; String appl_id, substate_id, tmp; tmp=info.state_id; if(tmp == null) { if(log.isTraceEnabled()) log.trace("state is null, not passing up: " + info); return; } int index=tmp.indexOf(SEPARATOR); if(index > -1) { appl_id=tmp.substring(0, index); substate_id=tmp.substring(index+SEPARATOR_LEN); } else { appl_id=tmp; substate_id=null; } mux_ch=services.get(appl_id); if(mux_ch == null) { log.error("didn't find service with ID=" + appl_id + " to fetch state from"); } else { StateTransferInfo tmp_info=info.copy(); tmp_info.state_id=substate_id; // evt.setArg(tmp_info); Event tmpEvt=new Event(evt.getType(), tmp_info); mux_ch.up(tmpEvt); // state_id will be null, get regular state from the service named state_id } } private void handleServiceStateRequest(ServiceInfo info, Address sender) throws Exception { switch(info.type) { case ServiceInfo.STATE_REQ: byte[] state; synchronized(service_state) { state=Util.objectToByteBuffer(service_state); } ServiceInfo si=new ServiceInfo(ServiceInfo.STATE_RSP, null, null, state); MuxHeader hdr=new MuxHeader(si); Message state_rsp=new Message(sender); state_rsp.putHeader(NAME, hdr); channel.send(state_rsp); break; case ServiceInfo.STATE_RSP: service_state_promise.setResult(info.state); break; case ServiceInfo.SERVICE_UP: handleServiceUp(info.service, info.host, true); break; case ServiceInfo.SERVICE_DOWN: handleServiceDown(info.service, info.host, true); break; case ServiceInfo.LIST_SERVICES_RSP: handleServicesRsp(sender, info.state); break; default: if(log.isErrorEnabled()) log.error("service request type " + info.type + " not known"); break; } } private void handleServicesRsp(Address sender, byte[] state) throws Exception { Object[] keys=(Object[])Util.objectFromByteBuffer(state); Set s=new HashSet(); for(int i=0; i < keys.length; i++) s.add(keys[i]); synchronized(service_responses) { Set tmp=service_responses.get(sender); if(tmp == null) tmp=new HashSet(); tmp.addAll(s); service_responses.put(sender, tmp); if(log.isTraceEnabled()) log.trace("received service response: " + sender + "(" + s.toString() + ")"); service_responses.notifyAll(); } } private void handleServiceDown(String service, Address host, boolean received) { List hosts, hosts_copy; boolean removed=false; // discard if we sent this message if(received && host != null && local_addr != null && local_addr.equals(host)) { return; } synchronized(service_state) { hosts=service_state.get(service); if(hosts == null) return; removed=hosts.remove(host); hosts_copy=new ArrayList(hosts); // make a copy so we don't modify hosts in generateServiceView() } if(removed) { View service_view=generateServiceView(hosts_copy); if(service_view != null) { MuxChannel ch=services.get(service); if(ch != null) { Event view_evt=new Event(Event.VIEW_CHANGE, service_view); ch.up(view_evt); } else { if(log.isTraceEnabled()) log.trace("service " + service + " not found, cannot dispatch service view " + service_view); } } } Address local_address=getLocalAddress(); if(local_address != null && host != null && host.equals(local_address)) unregister(service); } private void handleServiceUp(String service, Address host, boolean received) { List hosts, hosts_copy; boolean added=false; // discard if we sent this message if(received && host != null && local_addr != null && local_addr.equals(host)) { return; } synchronized(service_state) { hosts=service_state.get(service); if(hosts == null) { hosts=new ArrayList(); service_state.put(service, hosts); } if(!hosts.contains(host)) { hosts.add(host); added=true; } hosts_copy=new ArrayList(hosts); // make a copy so we don't modify hosts in generateServiceView() } if(added) { View service_view=generateServiceView(hosts_copy); if(service_view != null) { MuxChannel ch=services.get(service); if(ch != null) { Event view_evt=new Event(Event.VIEW_CHANGE, service_view); ch.up(view_evt); } else { if(log.isTraceEnabled()) log.trace("service " + service + " not found, cannot dispatch service view " + service_view); } } } } /** * Fetches the service states from everyone else in the cluster. Once all states have been received and inserted into * service_state, compute a service view (a copy of MergeView) for each service and pass it up * @param view */ private void handleMergeView(MergeView view) throws Exception { long time_to_wait=SERVICES_RSP_TIMEOUT, start; int num_members=view.size(); // include myself Map copy=null; sendServiceState(); synchronized(service_responses) { start=System.currentTimeMillis(); try { while(time_to_wait > 0 && numResponses(service_responses) < num_members) { service_responses.wait(time_to_wait); time_to_wait-=System.currentTimeMillis() - start; } copy=new HashMap(service_responses); } catch(Exception ex) { if(log.isErrorEnabled()) log.error("failed fetching a list of services from other members in the cluster, cannot handle merge view " + view, ex); } } if(log.isTraceEnabled()) log.trace("merging service state, my service_state: " + service_state + ", received responses: " + copy); // merges service_responses with service_state and emits MergeViews for the services affected (MuxChannel) mergeServiceState(view, copy); service_responses.clear(); temp_merge_view=null; } private int numResponses(Map m) { int num=0; Collection values=m.values(); for(Iterator it=values.iterator(); it.hasNext();) { if(it.next() != null) num++; } return num; } private void mergeServiceState(MergeView view, Map copy) { Set modified_services=new HashSet(); Map.Entry entry; Address host; // address of the sender Set service_list; // Set<String> of services List my_services; String service; synchronized(service_state) { for(Iterator it=copy.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); host=(Address)entry.getKey(); service_list=(Set)entry.getValue(); if(service_list == null) continue; for(Iterator it2=service_list.iterator(); it2.hasNext();) { service=(String)it2.next(); my_services=service_state.get(service); if(my_services == null) { my_services=new ArrayList(); service_state.put(service, my_services); } boolean was_modified=my_services.add(host); if(was_modified) { modified_services.add(service); } } } } // now emit MergeViews for all services which were modified for(Iterator it=modified_services.iterator(); it.hasNext();) { service=(String)it.next(); MuxChannel ch=services.get(service); my_services=service_state.get(service); MergeView v=(MergeView)view.clone(); v.getMembers().retainAll(my_services); Event evt=new Event(Event.VIEW_CHANGE, v); ch.up(evt); } } private void adjustServiceViews(Vector left_members) { if(left_members != null) for(int i=0; i < left_members.size(); i++) { try { adjustServiceView((Address)left_members.elementAt(i)); } catch(Throwable t) { if(log.isErrorEnabled()) log.error("failed adjusting service views", t); } } } private void adjustServiceView(Address host) { Map.Entry entry; List hosts, hosts_copy; String service; boolean removed=false; synchronized(service_state) { for(Iterator it=service_state.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); service=(String)entry.getKey(); hosts=(List)entry.getValue(); if(hosts == null) continue; removed=hosts.remove(host); hosts_copy=new ArrayList(hosts); // make a copy so we don't modify hosts in generateServiceView() if(removed) { View service_view=generateServiceView(hosts_copy); if(service_view != null) { MuxChannel ch=services.get(service); if(ch != null) { Event view_evt=new Event(Event.VIEW_CHANGE, service_view); ch.up(view_evt); } else { if(log.isTraceEnabled()) log.trace("service " + service + " not found, cannot dispatch service view " + service_view); } } } Address local_address=getLocalAddress(); if(local_address != null && host != null && host.equals(local_address)) unregister(service); } } } /** * Create a copy of view which contains only members which are present in hosts. Call viewAccepted() on the MuxChannel * which corresponds with service. If no members are removed or added from/to view, this is a no-op. * @param hosts List<Address> * @return the servicd view (a modified copy of the real view), or null if the view was not modified */ private View generateServiceView(List hosts) { Vector members=new Vector(view.getMembers()); members.retainAll(hosts); return new View(view.getVid(), members); } /** Tell the underlying channel to start the flush protocol, this will be handled by FLUSH */ private void startFlush() { channel.down(new Event(Event.SUSPEND)); } /** Tell the underlying channel to stop the flush, and resume message sending. This will be handled by FLUSH */ private void stopFlush() { channel.down(new Event(Event.RESUME)); } private Object passToMuxChannel(MuxChannel ch, Event evt, final FIFOMessageQueue<String,Runnable> queue, final Address sender, final String dest, boolean block) { if(thread_pool == null) return ch.up(evt); Task task=new Task(ch, evt, queue, sender, dest, block); ExecuteTask execute_task=new ExecuteTask(fifo_queue); // takes Task from queue and executes it try { fifo_queue.put(sender, dest, task); thread_pool.execute(execute_task); if(block) { try { return task.exchanger.exchange(null); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } // fifo_queue.done(sender, dest); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } return null; } public void addServiceIfNotPresent(String id, MuxChannel ch) { MuxChannel tmp; synchronized(services) { tmp=services.get(id); if(tmp == null) { services.put(id, ch); } } } private static class Task implements Runnable { Exchanger<Object> exchanger; MuxChannel channel; Event evt; FIFOMessageQueue<String,Runnable> queue; Address sender; String dest; Task(MuxChannel channel, Event evt, FIFOMessageQueue<String,Runnable> queue, Address sender, String dest, boolean result_expected) { this.channel=channel; this.evt=evt; this.queue=queue; this.sender=sender; this.dest=dest; if(result_expected) exchanger=new Exchanger<Object>(); } public void run() { Object retval; try { retval=channel.up(evt); if(exchanger != null) exchanger.exchange(retval); } catch(InterruptedException e) { Thread.currentThread().interrupt(); // let the thread pool handle the interrupt - we're done anyway } finally { queue.done(sender, dest); } } } private static class ExecuteTask implements Runnable { FIFOMessageQueue<String,Runnable> queue; public ExecuteTask(FIFOMessageQueue<String,Runnable> queue) { this.queue=queue; } public void run() { try { Runnable task=queue.take(); task.run(); } catch(InterruptedException e) { } } } }
all MuxChannel.up() calls are now handled by passToMuxChannel()
src/org/jgroups/mux/Multiplexer.java
all MuxChannel.up() calls are now handled by passToMuxChannel()
<ide><path>rc/org/jgroups/mux/Multiplexer.java <ide> * message is removed and the MuxChannel corresponding to the header's service ID is retrieved from the map, <ide> * and MuxChannel.up() is called with the message. <ide> * @author Bela Ban <del> * @version $Id: Multiplexer.java,v 1.50 2007/03/05 09:34:46 belaban Exp $ <add> * @version $Id: Multiplexer.java,v 1.51 2007/03/05 13:33:42 belaban Exp $ <ide> */ <ide> public class Multiplexer implements UpHandler { <ide> /** Map<String,MuxChannel>. Maintains the mapping between service IDs and their associated MuxChannels */ <ide> int num=1; <ide> ThreadGroup mux_threads=new ThreadGroup(Util.getGlobalThreadGroup(), "MultiplexerThreads"); <ide> public Thread newThread(Runnable command) { <del> return new Thread(mux_threads, command, "Multiplexer-" + num++); <add> Thread ret=new Thread(mux_threads, command, "Multiplexer-" + num++); <add> ret.setDaemon(true); <add> return ret; <ide> } <ide> }; <ide> <ide> MuxChannel mux_ch=services.get(id); <ide> if(mux_ch == null) <ide> throw new IllegalArgumentException("didn't find service with ID=" + id + " to fetch state from"); <del> // return mux_ch.up(evt); // state_id will be null, get regular state from the service named state_id <ide> <ide> // state_id will be null, get regular state from the service named state_id <ide> StateTransferInfo ret=(StateTransferInfo)passToMuxChannel(mux_ch, evt, fifo_queue, requester, id, true); <ide> else { <ide> StateTransferInfo tmp_info=info.copy(); <ide> tmp_info.state_id=substate_id; <del> // evt.setArg(tmp_info); <ide> Event tmpEvt=new Event(evt.getType(), tmp_info); <del> mux_ch.up(tmpEvt); // state_id will be null, get regular state from the service named state_id <add> passToMuxChannel(mux_ch, tmpEvt, fifo_queue, state_sender, appl_id, false); <ide> } <ide> } <ide> <ide> MuxChannel ch=services.get(service); <ide> if(ch != null) { <ide> Event view_evt=new Event(Event.VIEW_CHANGE, service_view); <del> ch.up(view_evt); <add> // ch.up(view_evt); <add> passToMuxChannel(ch, view_evt, fifo_queue, null, service, false); <ide> } <ide> else { <ide> if(log.isTraceEnabled()) <ide> MuxChannel ch=services.get(service); <ide> if(ch != null) { <ide> Event view_evt=new Event(Event.VIEW_CHANGE, service_view); <del> ch.up(view_evt); <add> // ch.up(view_evt); <add> passToMuxChannel(ch, view_evt, fifo_queue, null, service, false); <ide> } <ide> else { <ide> if(log.isTraceEnabled()) <ide> MergeView v=(MergeView)view.clone(); <ide> v.getMembers().retainAll(my_services); <ide> Event evt=new Event(Event.VIEW_CHANGE, v); <del> ch.up(evt); <add> // ch.up(evt); <add> passToMuxChannel(ch, evt, fifo_queue, null, service, false); <ide> } <ide> } <ide> <ide> MuxChannel ch=services.get(service); <ide> if(ch != null) { <ide> Event view_evt=new Event(Event.VIEW_CHANGE, service_view); <del> ch.up(view_evt); <add> // ch.up(view_evt); <add> passToMuxChannel(ch, view_evt, fifo_queue, null, service, false); <ide> } <ide> else { <ide> if(log.isTraceEnabled()) <ide> Thread.currentThread().interrupt(); <ide> } <ide> } <del> <del> // fifo_queue.done(sender, dest); <ide> } <ide> catch(InterruptedException e) { <ide> Thread.currentThread().interrupt();
Java
agpl-3.0
1a92216ab89275052dc9de910b269c2c6e2e53f3
0
bhutchinson/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,quikkian-ua-devops/will-financials,kuali/kfs,kuali/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,smith750/kfs,kuali/kfs,bhutchinson/kfs,ua-eas/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,kuali/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,quikkian-ua-devops/kfs,smith750/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kkronenb/kfs,smith750/kfs,quikkian-ua-devops/kfs,ua-eas/kfs,smith750/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials
/* * Copyright 2005 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.fp.document; import org.kuali.kfs.fp.businessobject.IndirectCostAdjustmentDocumentAccountingLineParser; import org.kuali.kfs.fp.document.validation.impl.IndirectCostAdjustmentDocumentRuleConstants; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.businessobject.AccountingLine; import org.kuali.kfs.sys.businessobject.AccountingLineParser; import org.kuali.kfs.sys.businessobject.GeneralLedgerPendingEntrySourceDetail; import org.kuali.kfs.sys.businessobject.SourceAccountingLine; import org.kuali.kfs.sys.businessobject.TargetAccountingLine; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.AccountingDocumentBase; import org.kuali.kfs.sys.document.AmountTotaling; import org.kuali.kfs.sys.document.Correctable; import org.kuali.kfs.sys.document.service.DebitDeterminerService; import org.kuali.rice.kns.document.Copyable; import org.kuali.rice.kns.exception.InfrastructureException; import org.kuali.rice.kns.service.ParameterService; public class IndirectCostAdjustmentDocument extends AccountingDocumentBase implements Copyable, Correctable, AmountTotaling { /** * Constructs a IndirectCostAdjustmentDocument.java. */ public IndirectCostAdjustmentDocument() { super(); } /** * @see org.kuali.kfs.sys.document.AccountingDocument#getSourceAccountingLinesSectionTitle() */ @Override public String getSourceAccountingLinesSectionTitle() { return KFSConstants.GRANT; } /** * @see org.kuali.kfs.sys.document.AccountingDocument#getTargetAccountingLinesSectionTitle() */ @Override public String getTargetAccountingLinesSectionTitle() { return KFSConstants.ICR; } /** * per ICA specs, adds a target(receipt) line when an source(grant) line is added using the following logic to populate the * target line. * <ol> * <li>receipt line's chart = chart from grant line * <li>receipt line's account = ICR account for the account entered on the grant line * <li>receipt line's object code = Financial System Parameter APC for the document global receipt line object code (see APC * setion below) * <li>receipt line's amount = amount from grant line * </ol> * * @see org.kuali.kfs.sys.document.AccountingDocumentBase#addSourceAccountingLine(SourceAccountingLine) */ @Override public void addSourceAccountingLine(SourceAccountingLine line) { // add source super.addSourceAccountingLine(line); // create and populate target line TargetAccountingLine targetAccountingLine = null; try { targetAccountingLine = (TargetAccountingLine) getTargetAccountingLineClass().newInstance(); } catch (Exception e) { throw new InfrastructureException("unable to create a target accounting line", e); } // get apc object code value String objectCode = SpringContext.getBean(ParameterService.class).getParameterValue(IndirectCostAdjustmentDocument.class, IndirectCostAdjustmentDocumentRuleConstants.RECEIPT_OBJECT_CODE); targetAccountingLine.setFinancialObjectCode(objectCode); targetAccountingLine.setAccountNumber(line.getAccount().getIndirectCostRecoveryAcctNbr()); targetAccountingLine.setChartOfAccountsCode(line.getAccount().getIndirectCostRcvyFinCoaCode()); targetAccountingLine.setDocumentNumber(line.getDocumentNumber()); targetAccountingLine.setPostingYear(line.getPostingYear()); targetAccountingLine.setAmount(line.getAmount()); // refresh reference objects targetAccountingLine.refresh(); // add target line addTargetAccountingLine(targetAccountingLine); } /** * Same logic as <code>IsDebitUtils#isDebitConsideringType(FinancialDocumentRuleBase, FinancialDocument, AccountingLine)</code> * but has the following accounting line restrictions: * * for grant lines(source): * <ol> * <li>only allow expense object type codes * </ol> * for receipt lines(target): * <ol> * <li>only allow income object type codes * </ol> * * @param transactionDocument The document associated with the accounting line being reviewed to determine if it's a debit. * @param accountingLine The accounting line being reviewed to determine if it's a debit line. * @return True if the accounting line is a debit. See IsDebitUtils.isDebitConsideringType(). * @throws IllegalStateException Thrown if the accounting line given is a source accounting line representing an expense * or is a target accounting line representing an income. * * @see IsDebitUtils#isDebitConsideringType(FinancialDocumentRuleBase, FinancialDocument, AccountingLine) * @see org.kuali.rice.kns.rule.AccountingLineRule#isDebit(org.kuali.rice.kns.document.FinancialDocument, * org.kuali.rice.kns.bo.AccountingLine) */ public boolean isDebit(GeneralLedgerPendingEntrySourceDetail postable) throws IllegalStateException { AccountingLine accountingLine = (AccountingLine)postable; DebitDeterminerService isDebitUtils = SpringContext.getBean(DebitDeterminerService.class); if (!(accountingLine.isSourceAccountingLine() && isDebitUtils.isExpense(accountingLine)) && !(accountingLine.isTargetAccountingLine() && isDebitUtils.isIncome(accountingLine))) { throw new IllegalStateException(isDebitUtils.getDebitCalculationIllegalStateExceptionMessage()); } return isDebitUtils.isDebitConsideringType(this, accountingLine); } }
work/src/org/kuali/kfs/fp/document/IndirectCostAdjustmentDocument.java
/* * Copyright 2005 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.fp.document; import org.kuali.kfs.fp.businessobject.IndirectCostAdjustmentDocumentAccountingLineParser; import org.kuali.kfs.fp.document.validation.impl.IndirectCostAdjustmentDocumentRuleConstants; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.businessobject.AccountingLine; import org.kuali.kfs.sys.businessobject.AccountingLineParser; import org.kuali.kfs.sys.businessobject.GeneralLedgerPendingEntrySourceDetail; import org.kuali.kfs.sys.businessobject.SourceAccountingLine; import org.kuali.kfs.sys.businessobject.TargetAccountingLine; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.kfs.sys.document.AccountingDocumentBase; import org.kuali.kfs.sys.document.AmountTotaling; import org.kuali.kfs.sys.document.Correctable; import org.kuali.kfs.sys.document.service.DebitDeterminerService; import org.kuali.rice.kns.document.Copyable; import org.kuali.rice.kns.exception.InfrastructureException; import org.kuali.rice.kns.service.ParameterService; public class IndirectCostAdjustmentDocument extends AccountingDocumentBase implements Copyable, Correctable, AmountTotaling { /** * Constructs a IndirectCostAdjustmentDocument.java. */ public IndirectCostAdjustmentDocument() { super(); } /** * @see org.kuali.kfs.sys.document.AccountingDocument#getSourceAccountingLinesSectionTitle() */ @Override public String getSourceAccountingLinesSectionTitle() { return KFSConstants.GRANT; } /** * @see org.kuali.kfs.sys.document.AccountingDocument#getTargetAccountingLinesSectionTitle() */ @Override public String getTargetAccountingLinesSectionTitle() { return KFSConstants.ICR; } /** * per ICA specs, adds a target(receipt) line when an source(grant) line is added using the following logic to populate the * target line. * <ol> * <li>receipt line's chart = chart from grant line * <li>receipt line's account = ICR account for the account entered on the grant line * <li>receipt line's object code = Financial System Parameter APC for the document global receipt line object code (see APC * setion below) * <li>receipt line's amount = amount from grant line * </ol> * * @see org.kuali.kfs.sys.document.AccountingDocumentBase#addSourceAccountingLine(SourceAccountingLine) */ @Override public void addSourceAccountingLine(SourceAccountingLine line) { // add source super.addSourceAccountingLine(line); // create and populate target line TargetAccountingLine targetAccountingLine = null; try { targetAccountingLine = (TargetAccountingLine) getTargetAccountingLineClass().newInstance(); } catch (Exception e) { throw new InfrastructureException("unable to create a target accounting line", e); } // get apc object code value String objectCode = SpringContext.getBean(ParameterService.class).getParameterValue(IndirectCostAdjustmentDocument.class, IndirectCostAdjustmentDocumentRuleConstants.RECEIPT_OBJECT_CODE); targetAccountingLine.setFinancialObjectCode(objectCode); targetAccountingLine.setAccountNumber(line.getAccount().getIndirectCostRecoveryAcctNbr()); targetAccountingLine.setChartOfAccountsCode(line.getChartOfAccountsCode()); targetAccountingLine.setDocumentNumber(line.getDocumentNumber()); targetAccountingLine.setPostingYear(line.getPostingYear()); targetAccountingLine.setAmount(line.getAmount()); // refresh reference objects targetAccountingLine.refresh(); // add target line addTargetAccountingLine(targetAccountingLine); } /** * Same logic as <code>IsDebitUtils#isDebitConsideringType(FinancialDocumentRuleBase, FinancialDocument, AccountingLine)</code> * but has the following accounting line restrictions: * * for grant lines(source): * <ol> * <li>only allow expense object type codes * </ol> * for receipt lines(target): * <ol> * <li>only allow income object type codes * </ol> * * @param transactionDocument The document associated with the accounting line being reviewed to determine if it's a debit. * @param accountingLine The accounting line being reviewed to determine if it's a debit line. * @return True if the accounting line is a debit. See IsDebitUtils.isDebitConsideringType(). * @throws IllegalStateException Thrown if the accounting line given is a source accounting line representing an expense * or is a target accounting line representing an income. * * @see IsDebitUtils#isDebitConsideringType(FinancialDocumentRuleBase, FinancialDocument, AccountingLine) * @see org.kuali.rice.kns.rule.AccountingLineRule#isDebit(org.kuali.rice.kns.document.FinancialDocument, * org.kuali.rice.kns.bo.AccountingLine) */ public boolean isDebit(GeneralLedgerPendingEntrySourceDetail postable) throws IllegalStateException { AccountingLine accountingLine = (AccountingLine)postable; DebitDeterminerService isDebitUtils = SpringContext.getBean(DebitDeterminerService.class); if (!(accountingLine.isSourceAccountingLine() && isDebitUtils.isExpense(accountingLine)) && !(accountingLine.isTargetAccountingLine() && isDebitUtils.isIncome(accountingLine))) { throw new IllegalStateException(isDebitUtils.getDebitCalculationIllegalStateExceptionMessage()); } return isDebitUtils.isDebitConsideringType(this, accountingLine); } }
KFSMI-4964: Indirect Cost Adjustment chart code on Receipt line is fixed to pull the indirect cost recovery chart code, not copy the chart code from Grant source accounting line.
work/src/org/kuali/kfs/fp/document/IndirectCostAdjustmentDocument.java
KFSMI-4964: Indirect Cost Adjustment chart code on Receipt line is fixed to pull the indirect cost recovery chart code, not copy the chart code from Grant source accounting line.
<ide><path>ork/src/org/kuali/kfs/fp/document/IndirectCostAdjustmentDocument.java <ide> String objectCode = SpringContext.getBean(ParameterService.class).getParameterValue(IndirectCostAdjustmentDocument.class, IndirectCostAdjustmentDocumentRuleConstants.RECEIPT_OBJECT_CODE); <ide> targetAccountingLine.setFinancialObjectCode(objectCode); <ide> targetAccountingLine.setAccountNumber(line.getAccount().getIndirectCostRecoveryAcctNbr()); <del> targetAccountingLine.setChartOfAccountsCode(line.getChartOfAccountsCode()); <add> targetAccountingLine.setChartOfAccountsCode(line.getAccount().getIndirectCostRcvyFinCoaCode()); <ide> targetAccountingLine.setDocumentNumber(line.getDocumentNumber()); <ide> targetAccountingLine.setPostingYear(line.getPostingYear()); <ide> targetAccountingLine.setAmount(line.getAmount());
Java
lgpl-2.1
475609de790102db54e3b17ffa14f127693bec0d
0
jessealama/exist,jessealama/exist,wolfgangmm/exist,RemiKoutcherawy/exist,patczar/exist,eXist-db/exist,opax/exist,ambs/exist,shabanovd/exist,adamretter/exist,jessealama/exist,windauer/exist,kohsah/exist,ambs/exist,adamretter/exist,eXist-db/exist,patczar/exist,zwobit/exist,RemiKoutcherawy/exist,MjAbuz/exist,dizzzz/exist,zwobit/exist,joewiz/exist,MjAbuz/exist,jensopetersen/exist,lcahlander/exist,joewiz/exist,wshager/exist,ambs/exist,eXist-db/exist,adamretter/exist,olvidalo/exist,patczar/exist,ambs/exist,opax/exist,zwobit/exist,MjAbuz/exist,olvidalo/exist,dizzzz/exist,lcahlander/exist,kohsah/exist,windauer/exist,kohsah/exist,kohsah/exist,jensopetersen/exist,wshager/exist,zwobit/exist,wshager/exist,RemiKoutcherawy/exist,ljo/exist,ambs/exist,MjAbuz/exist,ljo/exist,adamretter/exist,wshager/exist,windauer/exist,wshager/exist,wolfgangmm/exist,RemiKoutcherawy/exist,opax/exist,jensopetersen/exist,wolfgangmm/exist,joewiz/exist,opax/exist,olvidalo/exist,dizzzz/exist,shabanovd/exist,jessealama/exist,hungerburg/exist,adamretter/exist,eXist-db/exist,shabanovd/exist,MjAbuz/exist,windauer/exist,zwobit/exist,wolfgangmm/exist,RemiKoutcherawy/exist,kohsah/exist,olvidalo/exist,wshager/exist,windauer/exist,zwobit/exist,joewiz/exist,shabanovd/exist,lcahlander/exist,shabanovd/exist,patczar/exist,lcahlander/exist,ljo/exist,kohsah/exist,lcahlander/exist,ambs/exist,dizzzz/exist,adamretter/exist,jessealama/exist,hungerburg/exist,ljo/exist,hungerburg/exist,wolfgangmm/exist,MjAbuz/exist,jensopetersen/exist,olvidalo/exist,lcahlander/exist,wolfgangmm/exist,eXist-db/exist,shabanovd/exist,hungerburg/exist,ljo/exist,RemiKoutcherawy/exist,jensopetersen/exist,dizzzz/exist,patczar/exist,jessealama/exist,opax/exist,joewiz/exist,hungerburg/exist,joewiz/exist,ljo/exist,dizzzz/exist,jensopetersen/exist,eXist-db/exist,windauer/exist,patczar/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2001-06 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * $Id$ */ package org.exist.webstart; import java.io.File; import org.apache.log4j.Logger; import org.exist.util.Configuration; /** * Helper class for webstart. * * @author Dannes Wessels */ public class JnlpHelper { private static Logger logger = Logger.getLogger(JnlpHelper.class); private File existHome=Configuration.getExistHome(); private File coreJarsFolder=null; private File existJarFolder=null; private File webappFolder=null; /** Creates a new instance of JnlpHelper */ public JnlpHelper() { // Setup path based on installation (in jetty, container) if(isInWarFile()){ // all files mixed in existHome/lib/ logger.debug("eXist is running in container (.war)."); coreJarsFolder= new File(existHome, "lib/"); existJarFolder= new File(existHome, "lib/"); webappFolder= new File(existHome, ".."); } else { // all files located in existHome/lib/core/ logger.debug("eXist is running private jetty server."); coreJarsFolder= new File(existHome, "lib/core"); existJarFolder= existHome; webappFolder= new File(existHome, "webapp"); } logger.debug("CORE jars location="+coreJarsFolder.getAbsolutePath()); logger.debug("EXIST jars location="+existJarFolder.getAbsolutePath()); logger.debug("WEBAPP location="+webappFolder.getAbsolutePath()); } /** * Check wether exist runs in Servlet container (as war file). * @return TRUE if exist runs in servlet container. */ public boolean isInWarFile(){ boolean retVal =true; if( new File(existHome, "lib/core").isDirectory() ) { retVal=false; } return retVal; } public File getWebappFolder(){ return webappFolder; } public File getCoreJarsFolder(){ return coreJarsFolder; } public File getExistJarFolder(){ return existJarFolder; } }
src/org/exist/webstart/JnlpHelper.java
/* * eXist Open Source Native XML Database * Copyright (C) 2001-06 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * $Id$ */ package org.exist.webstart; import java.io.File; import org.apache.log4j.Logger; /** * Helper class for webstart. * * @author Dannes Wessels */ public class JnlpHelper { private static Logger logger = Logger.getLogger(JnlpHelper.class); private String existHome=System.getProperty("exist.home"); private File coreJarsFolder=null; private File existJarFolder=null; private File webappFolder=null; /** Creates a new instance of JnlpHelper */ public JnlpHelper() { // Setup path based on installation (in jetty, container) if(isInWarFile()){ // all files mixed in existHome/lib/ logger.debug("eXist is running in container (.war)."); coreJarsFolder= new File(existHome, "lib/"); existJarFolder= new File(existHome, "lib/"); webappFolder= new File(existHome, ".."); } else { // all files located in existHome/lib/core/ logger.debug("eXist is running private jetty server."); coreJarsFolder= new File(existHome, "lib/core"); existJarFolder= new File(existHome); webappFolder= new File(existHome, "webapp"); } logger.debug("CORE jars location="+coreJarsFolder.getAbsolutePath()); logger.debug("EXIST jars location="+existJarFolder.getAbsolutePath()); logger.debug("WEBAPP location="+webappFolder.getAbsolutePath()); } /** * Check wether exist runs in Servlet container (as war file). * @return TRUE if exist runs in servlet container. */ public boolean isInWarFile(){ boolean retVal =true; if( new File(existHome, "lib/core").isDirectory() ) { retVal=false; } return retVal; } public File getWebappFolder(){ return webappFolder; } public File getCoreJarsFolder(){ return coreJarsFolder; } public File getExistJarFolder(){ return existJarFolder; } }
Reducing exist.home dependencies....... just one step svn path=/trunk/eXist-1.0/; revision=3858
src/org/exist/webstart/JnlpHelper.java
Reducing exist.home dependencies....... just one step
<ide><path>rc/org/exist/webstart/JnlpHelper.java <ide> <ide> import java.io.File; <ide> import org.apache.log4j.Logger; <add>import org.exist.util.Configuration; <ide> <ide> /** <ide> * Helper class for webstart. <ide> public class JnlpHelper { <ide> <ide> private static Logger logger = Logger.getLogger(JnlpHelper.class); <del> private String existHome=System.getProperty("exist.home"); <add> private File existHome=Configuration.getExistHome(); <ide> <ide> private File coreJarsFolder=null; <ide> private File existJarFolder=null; <ide> // all files located in existHome/lib/core/ <ide> logger.debug("eXist is running private jetty server."); <ide> coreJarsFolder= new File(existHome, "lib/core"); <del> existJarFolder= new File(existHome); <add> existJarFolder= existHome; <ide> webappFolder= new File(existHome, "webapp"); <ide> } <ide> logger.debug("CORE jars location="+coreJarsFolder.getAbsolutePath());
Java
apache-2.0
34b7dd3ae377c89d5652b9df7f9d85bed5b0c679
0
werkt/bazel,twitter-forks/bazel,dslomov/bazel,davidzchen/bazel,cushon/bazel,werkt/bazel,ulfjack/bazel,ButterflyNetwork/bazel,ulfjack/bazel,katre/bazel,bazelbuild/bazel,ulfjack/bazel,cushon/bazel,davidzchen/bazel,dslomov/bazel,safarmer/bazel,ButterflyNetwork/bazel,ButterflyNetwork/bazel,dslomov/bazel-windows,bazelbuild/bazel,meteorcloudy/bazel,bazelbuild/bazel,ulfjack/bazel,werkt/bazel,akira-baruah/bazel,akira-baruah/bazel,dslomov/bazel-windows,akira-baruah/bazel,akira-baruah/bazel,safarmer/bazel,twitter-forks/bazel,davidzchen/bazel,perezd/bazel,meteorcloudy/bazel,werkt/bazel,davidzchen/bazel,dslomov/bazel-windows,aehlig/bazel,perezd/bazel,dslomov/bazel,twitter-forks/bazel,dslomov/bazel,bazelbuild/bazel,meteorcloudy/bazel,bazelbuild/bazel,katre/bazel,twitter-forks/bazel,katre/bazel,davidzchen/bazel,twitter-forks/bazel,katre/bazel,ButterflyNetwork/bazel,katre/bazel,ButterflyNetwork/bazel,perezd/bazel,safarmer/bazel,safarmer/bazel,cushon/bazel,aehlig/bazel,perezd/bazel,perezd/bazel,ulfjack/bazel,aehlig/bazel,dslomov/bazel,dslomov/bazel-windows,aehlig/bazel,meteorcloudy/bazel,werkt/bazel,aehlig/bazel,twitter-forks/bazel,dslomov/bazel-windows,perezd/bazel,meteorcloudy/bazel,cushon/bazel,ButterflyNetwork/bazel,dslomov/bazel,werkt/bazel,dslomov/bazel,twitter-forks/bazel,safarmer/bazel,aehlig/bazel,davidzchen/bazel,aehlig/bazel,akira-baruah/bazel,safarmer/bazel,meteorcloudy/bazel,bazelbuild/bazel,akira-baruah/bazel,ulfjack/bazel,cushon/bazel,dslomov/bazel-windows,ulfjack/bazel,katre/bazel,cushon/bazel,davidzchen/bazel,meteorcloudy/bazel,perezd/bazel
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.android.desugar; import static com.google.common.base.Preconditions.checkState; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.commons.ClassRemapper; import org.objectweb.asm.commons.MethodRemapper; import org.objectweb.asm.commons.Remapper; /** * A visitor that renames packages so configured using {@link CoreLibrarySupport}. */ class CorePackageRenamer extends ClassRemapper { private String internalName; public CorePackageRenamer(ClassVisitor cv, CoreLibrarySupport support) { super(cv, new CorePackageRemapper(support)); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { internalName = name; super.visit(version, access, name, signature, superName, interfaces); } @Override protected CoreMethodRemapper createMethodRemapper(MethodVisitor methodVisitor) { return new CoreMethodRemapper(methodVisitor, remapper); } private class CoreMethodRemapper extends MethodRemapper { public CoreMethodRemapper(MethodVisitor methodVisitor, Remapper remapper) { super(methodVisitor, remapper); } @Override public void visitMethodInsn(int opcode, String owner, String name, String descriptor, boolean isInterface) { CorePackageRemapper remapper = (CorePackageRemapper) this.remapper; remapper.didSomething = false; super.visitMethodInsn(opcode, owner, name, descriptor, isInterface); // TODO(b/79121791): Make this more precise: look for all unsupported core library members checkState(!remapper.didSomething || !owner.startsWith("android/") || owner.startsWith("android/support/"), "%s calls %s.%s%s which is not supported with core library desugaring. Please file " + "a feature request to support this method", internalName, owner, name, descriptor); } @Override public void visitFieldInsn(int opcode, String owner, String name, String descriptor) { CorePackageRemapper remapper = (CorePackageRemapper) this.remapper; remapper.didSomething = false; super.visitFieldInsn(opcode, owner, name, descriptor); // TODO(b/79121791): Make this more precise: look for all unsupported core library members checkState(!remapper.didSomething || !owner.startsWith("android/") || owner.startsWith("android/support/"), "%s accesses %s.%s: %s which is not supported with core library desugaring. Please file " + "a feature request to support this field", internalName, owner, name, descriptor); } } /** ASM {@link Remapper} based on {@link CoreLibrarySupport}. */ private static class CorePackageRemapper extends Remapper { private final CoreLibrarySupport support; boolean didSomething = false; CorePackageRemapper(CoreLibrarySupport support) { this.support = support; } @Override public String map(String typeName) { if (support.isRenamedCoreLibrary(typeName)) { didSomething = true; return support.renameCoreLibrary(typeName); } return typeName; } } }
src/tools/android/java/com/google/devtools/build/android/desugar/CorePackageRenamer.java
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.android.desugar; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.commons.ClassRemapper; /** * A visitor that renames packages so configured using {@link CoreLibrarySupport}.. */ class CorePackageRenamer extends ClassRemapper { public CorePackageRenamer(ClassVisitor cv, CoreLibrarySupport support) { super(cv, support.getRemapper()); } }
Simple build-time check for uses of desugared core library methods. PiperOrigin-RevId: 225110589
src/tools/android/java/com/google/devtools/build/android/desugar/CorePackageRenamer.java
Simple build-time check for uses of desugared core library methods.
<ide><path>rc/tools/android/java/com/google/devtools/build/android/desugar/CorePackageRenamer.java <ide> // limitations under the License. <ide> package com.google.devtools.build.android.desugar; <ide> <add>import static com.google.common.base.Preconditions.checkState; <add> <ide> import org.objectweb.asm.ClassVisitor; <add>import org.objectweb.asm.MethodVisitor; <ide> import org.objectweb.asm.commons.ClassRemapper; <add>import org.objectweb.asm.commons.MethodRemapper; <add>import org.objectweb.asm.commons.Remapper; <ide> <ide> /** <del> * A visitor that renames packages so configured using {@link CoreLibrarySupport}.. <add> * A visitor that renames packages so configured using {@link CoreLibrarySupport}. <ide> */ <ide> class CorePackageRenamer extends ClassRemapper { <ide> <add> private String internalName; <add> <ide> public CorePackageRenamer(ClassVisitor cv, CoreLibrarySupport support) { <del> super(cv, support.getRemapper()); <add> super(cv, new CorePackageRemapper(support)); <add> } <add> <add> @Override <add> public void visit(int version, int access, String name, String signature, String superName, <add> String[] interfaces) { <add> internalName = name; <add> super.visit(version, access, name, signature, superName, interfaces); <add> } <add> <add> @Override <add> protected CoreMethodRemapper createMethodRemapper(MethodVisitor methodVisitor) { <add> return new CoreMethodRemapper(methodVisitor, remapper); <add> } <add> <add> private class CoreMethodRemapper extends MethodRemapper { <add> <add> public CoreMethodRemapper(MethodVisitor methodVisitor, <add> Remapper remapper) { <add> super(methodVisitor, remapper); <add> } <add> <add> @Override <add> public void visitMethodInsn(int opcode, String owner, String name, String descriptor, <add> boolean isInterface) { <add> CorePackageRemapper remapper = (CorePackageRemapper) this.remapper; <add> remapper.didSomething = false; <add> super.visitMethodInsn(opcode, owner, name, descriptor, isInterface); <add> // TODO(b/79121791): Make this more precise: look for all unsupported core library members <add> checkState(!remapper.didSomething <add> || !owner.startsWith("android/") || owner.startsWith("android/support/"), <add> "%s calls %s.%s%s which is not supported with core library desugaring. Please file " <add> + "a feature request to support this method", internalName, owner, name, descriptor); <add> } <add> <add> @Override <add> public void visitFieldInsn(int opcode, String owner, String name, String descriptor) { <add> CorePackageRemapper remapper = (CorePackageRemapper) this.remapper; <add> remapper.didSomething = false; <add> super.visitFieldInsn(opcode, owner, name, descriptor); <add> // TODO(b/79121791): Make this more precise: look for all unsupported core library members <add> checkState(!remapper.didSomething <add> || !owner.startsWith("android/") || owner.startsWith("android/support/"), <add> "%s accesses %s.%s: %s which is not supported with core library desugaring. Please file " <add> + "a feature request to support this field", internalName, owner, name, descriptor); <add> } <add> } <add> <add> /** ASM {@link Remapper} based on {@link CoreLibrarySupport}. */ <add> private static class CorePackageRemapper extends Remapper { <add> <add> private final CoreLibrarySupport support; <add> boolean didSomething = false; <add> <add> CorePackageRemapper(CoreLibrarySupport support) { <add> this.support = support; <add> } <add> <add> @Override <add> public String map(String typeName) { <add> if (support.isRenamedCoreLibrary(typeName)) { <add> didSomething = true; <add> return support.renameCoreLibrary(typeName); <add> } <add> return typeName; <add> } <ide> } <ide> }
Java
bsd-3-clause
13412cc5e5360a2fde16e71113273866b0a8a0b4
0
aclissold/Proxima,aclissold/Proxima,aclissold/Proxima,aclissold/Proxima
package com.siteshot.siteshot.adapters; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseObject; import com.siteshot.siteshot.utils.PhotoUtils; /** * Adapts PhotoUtils' List of UserPhotos. */ public class ImageAdapter extends BaseAdapter { private final String TAG = getClass().getName(); private int mWidth, mHeight; private static final float SIZE_DP = 90.0f; private Context mContext; public ImageAdapter(Context c) { mContext = c; final float scale = c.getResources().getDisplayMetrics().density; // Adjust the width and height "constants" based on screen density. mWidth = (int) (SIZE_DP * scale + 0.5f); mHeight = mWidth; } public int getCount() { return PhotoUtils.getInstance().getUserPhotos().size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(mWidth, mHeight)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); } else { imageView = (ImageView) convertView; } // Retrieve the photo data from the UserPhoto instance. ParseObject object = PhotoUtils.getInstance().getUserPhotos().get(position); ParseFile file = object.getParseFile("photo"); byte[] data = new byte[0]; try { data = file.getData(); } catch (ParseException e) { Log.e(TAG, "could not get data from ParseFile:"); e.printStackTrace(); } Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, mWidth, mHeight, false)); imageView.setImageBitmap(bitmap); return imageView; } }
app/src/main/java/com/siteshot/siteshot/adapters/ImageAdapter.java
package com.siteshot.siteshot.adapters; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseObject; import com.siteshot.siteshot.utils.PhotoUtils; /** * Adapts PhotoUtils' List of UserPhotos. */ public class ImageAdapter extends BaseAdapter { private final String TAG = getClass().getName(); private final int width = 90, height = 90; private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return PhotoUtils.getInstance().getUserPhotos().size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(width, height)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); } else { imageView = (ImageView) convertView; } // Retrieve the photo data from the UserPhoto instance. ParseObject object = PhotoUtils.getInstance().getUserPhotos().get(position); ParseFile file = object.getParseFile("photo"); byte[] data = new byte[0]; try { data = file.getData(); } catch (ParseException e) { Log.e(TAG, "could not get data from ParseFile:"); e.printStackTrace(); } Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false)); imageView.setImageBitmap(bitmap); return imageView; } }
Use density-independent pixels on the profile grid
app/src/main/java/com/siteshot/siteshot/adapters/ImageAdapter.java
Use density-independent pixels on the profile grid
<ide><path>pp/src/main/java/com/siteshot/siteshot/adapters/ImageAdapter.java <ide> public class ImageAdapter extends BaseAdapter { <ide> <ide> private final String TAG = getClass().getName(); <del> private final int width = 90, height = 90; <del> <add> private int mWidth, mHeight; <add> private static final float SIZE_DP = 90.0f; <ide> private Context mContext; <ide> <ide> public ImageAdapter(Context c) { <ide> mContext = c; <add> final float scale = c.getResources().getDisplayMetrics().density; <add> <add> // Adjust the width and height "constants" based on screen density. <add> mWidth = (int) (SIZE_DP * scale + 0.5f); <add> mHeight = mWidth; <ide> } <ide> <ide> public int getCount() { <ide> ImageView imageView; <ide> if (convertView == null) { <ide> imageView = new ImageView(mContext); <del> imageView.setLayoutParams(new GridView.LayoutParams(width, height)); <add> imageView.setLayoutParams(new GridView.LayoutParams(mWidth, mHeight)); <ide> imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); <ide> } else { <ide> imageView = (ImageView) convertView; <ide> } <ide> Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); <ide> <del> imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false)); <add> imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, mWidth, mHeight, false)); <ide> <ide> imageView.setImageBitmap(bitmap); <ide>
Java
apache-2.0
e36a7ca831a5f33dc8929047c1972ff5fbcefa2d
0
magnetsystems/message-openfire,GregDThomas/Openfire,speedy01/Openfire,igniterealtime/Openfire,igniterealtime/Openfire,GregDThomas/Openfire,guusdk/Openfire,magnetsystems/message-openfire,magnetsystems/message-openfire,GregDThomas/Openfire,magnetsystems/message-openfire,guusdk/Openfire,akrherz/Openfire,Gugli/Openfire,Gugli/Openfire,akrherz/Openfire,igniterealtime/Openfire,speedy01/Openfire,speedy01/Openfire,igniterealtime/Openfire,akrherz/Openfire,GregDThomas/Openfire,akrherz/Openfire,guusdk/Openfire,speedy01/Openfire,igniterealtime/Openfire,magnetsystems/message-openfire,guusdk/Openfire,Gugli/Openfire,GregDThomas/Openfire,speedy01/Openfire,Gugli/Openfire,akrherz/Openfire,Gugli/Openfire,guusdk/Openfire
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright (C) 2008 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package org.jivesoftware.openfire.clearspace; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.*; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.XMPPPacketReader; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.XMPPServerInfo; import org.jivesoftware.openfire.auth.AuthFactory; import org.jivesoftware.openfire.auth.UnauthorizedException; import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET; import static org.jivesoftware.openfire.clearspace.WSUtils.getReturn; import org.jivesoftware.openfire.component.ExternalComponentConfiguration; import org.jivesoftware.openfire.component.ExternalComponentManager; import org.jivesoftware.openfire.component.ExternalComponentManagerListener; import org.jivesoftware.openfire.container.BasicModule; import org.jivesoftware.openfire.group.GroupNotFoundException; import org.jivesoftware.openfire.net.MXParser; import org.jivesoftware.openfire.user.UserNotFoundException; import org.jivesoftware.util.*; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmpp.packet.JID; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.*; import java.util.*; /** * Centralized administration of Clearspace connections. The {@link #getInstance()} method * should be used to get an instace. The following properties configure this manager: * * <ul> * <li>clearspace.uri</li> * <li>clearspace.sharedSecret</li> * </ul> * * @author Daniel Henninger */ public class ClearspaceManager extends BasicModule implements ExternalComponentManagerListener { private ConfigClearspaceTask configClearspaceTask; /** * Different kind of HTTP request types */ public enum HttpType { /** * Represents an HTTP Get request. And it's equivalent to a SQL SELECTE. */ GET, /** * Represents an HTTP Post request. And it's equivalent to a SQL UPDATE. */ POST, /** * Represents an HTTP Delete request. And it's equivalent to a SQL DELETE. */ DELETE, /** * Represents an HTTP Put requests.And it's equivalent to a SQL CREATE. */ PUT } /** * This is the username of the user that Openfires uses to connect * to Clearspace. It is fixed a well known by Openfire and Clearspace. */ private static final String OPENFIRE_USERNAME = "openfire_SHRJKZCNU53"; private static final String WEBSERVICES_PATH = "rpc/rest/"; protected static final String IM_URL_PREFIX = "imService/"; private static ThreadLocal<XMPPPacketReader> localParser = null; private static XmlPullParserFactory factory = null; static { try { factory = XmlPullParserFactory.newInstance(MXParser.class.getName(), null); factory.setNamespaceAware(true); } catch (XmlPullParserException e) { Log.error("Error creating a parser factory", e); } // Create xmpp parser to keep in each thread localParser = new ThreadLocal<XMPPPacketReader>() { protected XMPPPacketReader initialValue() { XMPPPacketReader parser = new XMPPPacketReader(); factory.setNamespaceAware(true); parser.setXPPFactory(factory); return parser; } }; } private static final Map<String, String> exceptionMap; static { exceptionMap = new HashMap<String, String>(); exceptionMap.put("com.jivesoftware.base.UserNotFoundException", "org.jivesoftware.openfire.user.UserNotFoundException"); exceptionMap.put("com.jivesoftware.base.UserAlreadyExistsException", "org.jivesoftware.openfire.user.UserAlreadyExistsException"); exceptionMap.put("com.jivesoftware.base.GroupNotFoundException", "org.jivesoftware.openfire.group.GroupNotFoundException"); exceptionMap.put("com.jivesoftware.base.GroupAlreadyExistsException", "org.jivesoftware.openfire.group.GroupAlreadyExistsException"); exceptionMap.put("org.acegisecurity.BadCredentialsException", "org.jivesoftware.openfire.auth.UnauthorizedException"); } private static ClearspaceManager instance = new ClearspaceManager(); private Map<String, String> properties; private String uri; private String host; private int port; private String sharedSecret; /** * Provides singleton access to an instance of the ClearspaceManager class. * * @return an ClearspaceManager instance. */ public static ClearspaceManager getInstance() { return instance; } /** * Constructs a new ClearspaceManager instance. Typically, {@link #getInstance()} should be * called instead of this method. ClearspaceManager instances should only be created directly * for testing purposes. * * @param properties the Map that contains properties used by the Clearspace manager, such as * Clearspace host and shared secret. */ public ClearspaceManager(Map<String, String> properties) { super("Clearspace integration module for testing only"); this.properties = properties; this.uri = properties.get("clearspace.uri"); if (!this.uri.endsWith("/")) { this.uri = this.uri + "/"; } sharedSecret = properties.get("clearspace.sharedSecret"); if (Log.isDebugEnabled()) { StringBuilder buf = new StringBuilder(); buf.append("Created new ClearspaceManager() instance, fields:\n"); buf.append("\t URI: ").append(uri).append("\n"); buf.append("\t sharedSecret: ").append(sharedSecret).append("\n"); Log.debug("ClearspaceManager: " + buf.toString()); } } /** * Constructs a new ClearspaceManager instance. Typically, {@link #getInstance()} should be * called instead of this method. ClearspaceManager instances should only be created directly * for testing purposes. * */ public ClearspaceManager() { super("Clearspace integration module"); // Create a special Map implementation to wrap XMLProperties. We only implement // the get, put, and remove operations, since those are the only ones used. Using a Map // makes it easier to perform LdapManager testing. this.properties = new Map<String, String>() { public String get(Object key) { return JiveGlobals.getXMLProperty((String)key); } public String put(String key, String value) { JiveGlobals.setXMLProperty(key, value); // Always return null since XMLProperties doesn't support the normal semantics. return null; } public String remove(Object key) { JiveGlobals.deleteXMLProperty((String)key); // Always return null since XMLProperties doesn't support the normal semantics. return null; } public int size() { return 0; } public boolean isEmpty() { return false; } public boolean containsKey(Object key) { return false; } public boolean containsValue(Object value) { return false; } public void putAll(Map<? extends String, ? extends String> t) { } public void clear() { } public Set<String> keySet() { return null; } public Collection<String> values() { return null; } public Set<Entry<String, String>> entrySet() { return null; } }; this.uri = JiveGlobals.getXMLProperty("clearspace.uri"); sharedSecret = JiveGlobals.getXMLProperty("clearspace.sharedSecret"); if (uri != null && !"".equals(uri.trim())) { try { URL url = new URL(uri); host = url.getHost(); port = url.getPort(); } catch (MalformedURLException e) { // this won't happen } } if (Log.isDebugEnabled()) { StringBuilder buf = new StringBuilder(); buf.append("Created new ClearspaceManager() instance, fields:\n"); buf.append("\t URI: ").append(uri).append("\n"); buf.append("\t sharedSecret: ").append(sharedSecret).append("\n"); Log.debug("ClearspaceManager: " + buf.toString()); } } /** * Check a username/password pair for valid authentication. * * @param username Username to authenticate against. * @param password Password to use for authentication. * @return True or false of the authentication succeeded. */ public Boolean checkAuthentication(String username, String password) { try { String path = ClearspaceAuthProvider.URL_PREFIX + "authenticate/" + username + "/" + password; executeRequest(GET, path); return true; } catch (Exception e) { // Nothing to do. } return false; } /** * Tests the web services connection with Clearspace given the manager's current configuration. * * @return True if connection test was successful. */ public Boolean testConnection() { // Test invoking a simple method try { String path = ClearspaceUserProvider.USER_URL_PREFIX + "users/count"; Element element = executeRequest(GET, path); getReturn(element); return true; } catch (Exception e) { // Nothing to do. } return false; } /** * Returns the Clearspace service URI; e.g. <tt>https://localhost:80/clearspace</tt>. * This value is stored as the Jive Property <tt>clearspace.uri</tt>. * * @return the Clearspace service URI. */ public String getConnectionURI() { return uri; } /** * Sets the URI of the Clearspace service; e.g., <tt>https://localhost:80/clearspace</tt>. * This value is stored as the Jive Property <tt>clearspace.uri</tt>. * * @param uri the Clearspace service URI. */ public void setConnectionURI(String uri) { if (!uri.endsWith("/")) { uri = uri + "/"; } this.uri = uri; properties.put("clearspace.uri", uri); if (isEnabled()) { startClearspaceConfig(); } } /** * Returns the password, configured in Clearspace, that Openfire will use to authenticate * with Clearspace to perform it's integration. * * @return the password Openfire will use to authenticate with Clearspace. */ public String getSharedSecret() { return sharedSecret; } /** * Sets the shared secret for the Clearspace service we're connecting to. * * @param sharedSecret the password configured in Clearspace to authenticate Openfire. */ public void setSharedSecret(String sharedSecret) { this.sharedSecret = sharedSecret; properties.put("clearspace.sharedSecret", sharedSecret); // Set new password for external component ExternalComponentConfiguration configuration = new ExternalComponentConfiguration("clearspace", ExternalComponentConfiguration.Permission.allowed, sharedSecret); try { ExternalComponentManager.allowAccess(configuration); } catch (ModificationNotAllowedException e) { Log.warn("Failed to configure password for Clearspace", e); } } /** * Returns true if Clearspace is being used as the backend of Openfire. When * integrated with Clearspace then users and groups will be pulled out from * Clearspace. User authentication will also rely on Clearspace. * * @return true if Clearspace is being used as the backend of Openfire. */ public boolean isEnabled() { return AuthFactory.getAuthProvider() instanceof ClearspaceAuthProvider; } public void start() throws IllegalStateException { super.start(); if (isEnabled()) { // Before starting up service make sure there is a default secret if (ExternalComponentManager.getDefaultSecret() == null || "".equals(ExternalComponentManager.getDefaultSecret())) { try { ExternalComponentManager.setDefaultSecret(StringUtils.randomString(10)); } catch (ModificationNotAllowedException e) { Log.warn("Failed to set a default secret to external component service", e); } } // Make sure that external component service is enabled if (!ExternalComponentManager.isServiceEnabled()) { try { ExternalComponentManager.setServiceEnabled(true); } catch (ModificationNotAllowedException e) { Log.warn("Failed to start external component service", e); } } // Listen for changes to external component settings ExternalComponentManager.addListener(this); // Starts the clearspace configuration task startClearspaceConfig(); } } /** * */ private void startClearspaceConfig() { // Start the task if it is not currently running if (configClearspaceTask == null) { configClearspaceTask = new ConfigClearspaceTask(); TaskEngine.getInstance().schedule(configClearspaceTask, 0, JiveConstants.MINUTE); }/* try { configClearspace(); } catch (UnauthorizedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } */ } private synchronized void configClearspace() throws UnauthorizedException { try { List<String> bindInterfaces = getServerInterfaces(); if (bindInterfaces.size() == 0) { // We aren't up and running enough to tell Clearspace what interfaces to bind to. return; } XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo(); // TODO: Eventually we would like to get POST support working properly. // String path = IM_URL_PREFIX + "configureComponent/"; // // // Creates the XML with the data // Document groupDoc = DocumentHelper.createDocument(); // Element rootE = groupDoc.addElement("configureComponent"); // Element domainE = rootE.addElement("domain"); // domainE.setText(serverInfo.getXMPPDomain()); // Element hostsE = rootE.addElement("hosts"); // hostsE.setText(WSUtils.marshallList(bindInterfaces)); // Element portE = rootE.addElement("port"); // portE.setText(String.valueOf(ExternalComponentManager.getServicePort())); // // executeRequest(POST, path, rootE.asXML()); String path = IM_URL_PREFIX + "configureComponent/" + serverInfo.getXMPPDomain() + "/" + WSUtils.marshallList(bindInterfaces) + "/" + String.valueOf(ExternalComponentManager.getServicePort()); executeRequest(GET, path); //Done, Clearspace was configured correctly, clear the task TaskEngine.getInstance().cancelScheduledTask(configClearspaceTask); configClearspaceTask = null; } catch (UnauthorizedException ue) { throw ue; } catch (Exception e) { // It is not supported exception, wrap it into an UnsupportedOperationException throw new UnsupportedOperationException("Unexpected error", e); } } private List<String> getServerInterfaces() { List<String> bindInterfaces = new ArrayList<String>(); String interfaceName = JiveGlobals.getXMLProperty("network.interface"); String bindInterface = null; if (interfaceName != null) { if (interfaceName.trim().length() > 0) { bindInterface = interfaceName; } } int adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090); int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091); if (bindInterface == null) { try { Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netInterface : Collections.list(nets)) { Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); for (InetAddress address : Collections.list(addresses)) { if ("127.0.0.1".equals(address.getHostAddress())) { continue; } if (address.getHostAddress().startsWith("0.")) { continue; } Socket socket = new Socket(); InetSocketAddress remoteAddress = new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort); try { socket.connect(remoteAddress); bindInterfaces.add(address.getHostAddress()); break; } catch (IOException e) { // Ignore this address. Let's hope there is more addresses to validate } } } } catch (SocketException e) { // We failed to discover a valid IP address where the admin console is running return null; } } return bindInterfaces; } private void updateClearspaceSharedSecret(String newSecret) { try { // Keeping this around for the moment just in case. String path = IM_URL_PREFIX + "updateSharedSecret/" + newSecret; executeRequest(GET, path); // TODO: We should switch to POST once we figure out why it's not behaving. // String path = IM_URL_PREFIX + "updateSharedSecret/"; // // // Creates the XML with the data // Document groupDoc = DocumentHelper.createDocument(); // Element rootE = groupDoc.addElement("updateSharedSecret"); // rootE.addElement("newSecret").setText(newSecret); // // executeRequest(POST, path, groupDoc.asXML()); } catch (UnauthorizedException ue) { // TODO: what should happen here? should continue? } catch (Exception e) { // TODO: what should happen here? should continue? } } public void serviceEnabled(boolean enabled) throws ModificationNotAllowedException { // Do not let admins shutdown the external component service if (!enabled) { throw new ModificationNotAllowedException("Service cannot be disabled when integrated with Clearspace."); } } public void portChanged(int newPort) throws ModificationNotAllowedException { startClearspaceConfig(); } public void defaultSecretChanged(String newSecret) throws ModificationNotAllowedException { // Do nothing } public void permissionPolicyChanged(ExternalComponentManager.PermissionPolicy newPolicy) throws ModificationNotAllowedException { // Do nothing } public void componentAllowed(String subdomain, ExternalComponentConfiguration configuration) throws ModificationNotAllowedException { if (subdomain.startsWith("clearspace")) { updateClearspaceSharedSecret(configuration.getSecret()); } } public void componentBlocked(String subdomain) throws ModificationNotAllowedException { if (subdomain.startsWith("clearspace")) { throw new ModificationNotAllowedException("Communication with Clearspace cannot be blocked."); } } public void componentSecretUpdated(String subdomain, String newSecret) throws ModificationNotAllowedException { if (subdomain.startsWith("clearspace")) { updateClearspaceSharedSecret(newSecret); } } public void componentConfigurationDeleted(String subdomain) throws ModificationNotAllowedException { // Do not let admins delete configuration of Clearspace component if (subdomain.startsWith("clearspace")) { throw new ModificationNotAllowedException("Use 'Profile Settings' to change password."); } } /** * Makes a rest request of either type GET or DELETE at the specified urlSuffix. * * urlSuffix should be of the form /userService/users * * @param type Must be GET or DELETE * @param urlSuffix The url suffix of the rest request * @return The response as a xml doc. * @throws Exception Thrown if there are issues parsing the request. */ public Element executeRequest(HttpType type, String urlSuffix) throws Exception { assert (type == HttpType.GET || type == HttpType.DELETE); return executeRequest(type, urlSuffix, null); } public Element executeRequest(HttpType type, String urlSuffix, String xmlParams) throws Exception { Log.debug("Outgoing REST call ["+type+"] to "+urlSuffix+": "+xmlParams); String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix; String secret = getSharedSecret(); HttpClient client = new HttpClient(); HttpMethod method; // Configures the authentication client.getParams().setAuthenticationPreemptive(true); Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret); AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM); client.getState().setCredentials(scope, credentials); // Creates the method switch (type) { case GET: method = new GetMethod(wsUrl); break; case POST: PostMethod pm = new PostMethod(wsUrl); StringRequestEntity requestEntity = new StringRequestEntity(xmlParams); pm.setRequestEntity(requestEntity); method = pm; break; case PUT: PutMethod pm1 = new PutMethod(wsUrl); StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams); pm1.setRequestEntity(requestEntity1); method = pm1; break; case DELETE: method = new DeleteMethod(wsUrl); break; default: throw new IllegalArgumentException(); } method.setRequestHeader("Accept", "text/xml"); method.setDoAuthentication(true); try { // Excecutes the resquest client.executeMethod(method); // Parses the result String body = method.getResponseBodyAsString(); Log.debug("Outgoing REST call results: "+body); Element response = localParser.get().parseDocument(body).getRootElement(); // Check for exceptions checkFault(response); // Since there is no exception, returns the response return response; } finally { method.releaseConnection(); } } private void checkFault(Element response) throws Exception { Node node = response.selectSingleNode("ns1:faultstring"); if (node != null) { String exceptionText = node.getText(); // Text accepted samples: // 'java.lang.Exception: Exception message' // 'java.lang.Exception' // Get the exception class and message if any int index = exceptionText.indexOf(":"); String className; String message; // If there is no massege, save the class only if (index == -1) { className = exceptionText; message = null; } else { // Else save both className = exceptionText.substring(0, index); message = exceptionText.substring(index + 2); } // Map the exception to a Openfire one, if possible if (exceptionMap.containsKey(className)) { className = exceptionMap.get(className); } //Tries to create an instance with the message Exception exception; try { Class exceptionClass = Class.forName(className); if (message == null) { exception = (Exception) exceptionClass.newInstance(); } else { Constructor constructor = exceptionClass.getConstructor(String.class); exception = (Exception) constructor.newInstance(message); } } catch (Exception e) { // failed to create an specific exception, creating a standar one. exception = new Exception(exceptionText); } throw exception; } } /** * Returns the Clearspace user id the user by username. * @param username Username to retrieve ID of. * @return The ID number of the user in Clearspace. * @throws org.jivesoftware.openfire.user.UserNotFoundException If the user was not found. */ protected long getUserID(String username) throws UserNotFoundException { // todo implement cache if(username.contains("@")) { if (!XMPPServer.getInstance().isLocal(new JID(username))) { throw new UserNotFoundException("Cannot load user of remote server: " + username); } username = username.substring(0,username.lastIndexOf("@")); } return getUserID(XMPPServer.getInstance().createJID(username, null)); } /** * Returns the Clearspace user id the user by JID. * @param user JID of user to retrieve ID of. * @return The ID number of the user in Clearspace. * @throws org.jivesoftware.openfire.user.UserNotFoundException If the user was not found. */ protected long getUserID(JID user) throws UserNotFoundException { // TODO: implement cache, after we are listening for user events from Clearspace. XMPPServer server = XMPPServer.getInstance(); String username = server.isLocal(user) ? JID.unescapeNode(user.getNode()) : user.toString(); try { String path = ClearspaceUserProvider.USER_URL_PREFIX + "users/" + username; Element element = executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path); return Long.valueOf(WSUtils.getElementText(element.selectSingleNode("return"), "ID")); } catch (UserNotFoundException unfe) { // It is a supported exception, throw it again throw unfe; } catch (Exception e) { // It is not asupperted exception, wrap it into a UserNotFoundException throw new UserNotFoundException("Unexpected error", e); } } /** * Returns the Clearspace group id of the group. * @param groupname Name of the group to retrieve ID of. * @return The ID number of the group in Clearspace. * @throws org.jivesoftware.openfire.group.GroupNotFoundException If the group was not found. */ protected long getGroupID(String groupname) throws GroupNotFoundException { // TODO: implement cache, after we are listening for group events from Clearspace. try { String path = ClearspaceGroupProvider.URL_PREFIX + "groups/" + groupname; Element element = executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path); return Long.valueOf(WSUtils.getElementText(element.selectSingleNode("return"), "ID")); } catch (GroupNotFoundException gnfe) { // It is a supported exception, throw it again throw gnfe; } catch (Exception e) { // It is not asupperted exception, wrap it into a GroupNotFoundException throw new GroupNotFoundException("Unexpected error", e); } } private class ConfigClearspaceTask extends TimerTask { public void run() { try { configClearspace(); } catch (UnauthorizedException e) { // TODO: mark that there is an authorization problem } } } }
src/java/org/jivesoftware/openfire/clearspace/ClearspaceManager.java
/** * $RCSfile$ * $Revision$ * $Date$ * * Copyright (C) 2008 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Public License (GPL), * a copy of which is included in this distribution. */ package org.jivesoftware.openfire.clearspace; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.*; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.XMPPPacketReader; import org.jivesoftware.openfire.XMPPServer; import org.jivesoftware.openfire.XMPPServerInfo; import org.jivesoftware.openfire.auth.AuthFactory; import org.jivesoftware.openfire.auth.UnauthorizedException; import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET; import static org.jivesoftware.openfire.clearspace.WSUtils.getReturn; import org.jivesoftware.openfire.component.ExternalComponentConfiguration; import org.jivesoftware.openfire.component.ExternalComponentManager; import org.jivesoftware.openfire.component.ExternalComponentManagerListener; import org.jivesoftware.openfire.container.BasicModule; import org.jivesoftware.openfire.group.GroupNotFoundException; import org.jivesoftware.openfire.net.MXParser; import org.jivesoftware.openfire.user.UserNotFoundException; import org.jivesoftware.util.*; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmpp.packet.JID; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.*; import java.util.*; /** * Centralized administration of Clearspace connections. The {@link #getInstance()} method * should be used to get an instace. The following properties configure this manager: * * <ul> * <li>clearspace.uri</li> * <li>clearspace.sharedSecret</li> * </ul> * * @author Daniel Henninger */ public class ClearspaceManager extends BasicModule implements ExternalComponentManagerListener { private ConfigClearspaceTask configClearspaceTask; /** * Different kind of HTTP request types */ public enum HttpType { /** * Represents an HTTP Get request. And it's equivalent to a SQL SELECTE. */ GET, /** * Represents an HTTP Post request. And it's equivalent to a SQL UPDATE. */ POST, /** * Represents an HTTP Delete request. And it's equivalent to a SQL DELETE. */ DELETE, /** * Represents an HTTP Put requests.And it's equivalent to a SQL CREATE. */ PUT } /** * This is the username of the user that Openfires uses to connect * to Clearspace. It is fixed a well known by Openfire and Clearspace. */ private static final String OPENFIRE_USERNAME = "openfire_SHRJKZCNU53"; private static final String WEBSERVICES_PATH = "rpc/rest/"; protected static final String IM_URL_PREFIX = "imService/"; private static ThreadLocal<XMPPPacketReader> localParser = null; private static XmlPullParserFactory factory = null; static { try { factory = XmlPullParserFactory.newInstance(MXParser.class.getName(), null); factory.setNamespaceAware(true); } catch (XmlPullParserException e) { Log.error("Error creating a parser factory", e); } // Create xmpp parser to keep in each thread localParser = new ThreadLocal<XMPPPacketReader>() { protected XMPPPacketReader initialValue() { XMPPPacketReader parser = new XMPPPacketReader(); factory.setNamespaceAware(true); parser.setXPPFactory(factory); return parser; } }; } private static final Map<String, String> exceptionMap; static { exceptionMap = new HashMap<String, String>(); exceptionMap.put("com.jivesoftware.base.UserNotFoundException", "org.jivesoftware.openfire.user.UserNotFoundException"); exceptionMap.put("com.jivesoftware.base.UserAlreadyExistsException", "org.jivesoftware.openfire.user.UserAlreadyExistsException"); exceptionMap.put("com.jivesoftware.base.GroupNotFoundException", "org.jivesoftware.openfire.group.GroupNotFoundException"); exceptionMap.put("com.jivesoftware.base.GroupAlreadyExistsException", "org.jivesoftware.openfire.group.GroupAlreadyExistsException"); exceptionMap.put("org.acegisecurity.BadCredentialsException", "org.jivesoftware.openfire.auth.UnauthorizedException"); } private static ClearspaceManager instance = new ClearspaceManager(); private Map<String, String> properties; private String uri; private String host; private int port; private String sharedSecret; /** * Provides singleton access to an instance of the ClearspaceManager class. * * @return an ClearspaceManager instance. */ public static ClearspaceManager getInstance() { return instance; } /** * Constructs a new ClearspaceManager instance. Typically, {@link #getInstance()} should be * called instead of this method. ClearspaceManager instances should only be created directly * for testing purposes. * * @param properties the Map that contains properties used by the Clearspace manager, such as * Clearspace host and shared secret. */ public ClearspaceManager(Map<String, String> properties) { super("Clearspace integration module for testing only"); this.properties = properties; this.uri = properties.get("clearspace.uri"); if (!this.uri.endsWith("/")) { this.uri = this.uri + "/"; } sharedSecret = properties.get("clearspace.sharedSecret"); if (Log.isDebugEnabled()) { StringBuilder buf = new StringBuilder(); buf.append("Created new ClearspaceManager() instance, fields:\n"); buf.append("\t URI: ").append(uri).append("\n"); buf.append("\t sharedSecret: ").append(sharedSecret).append("\n"); Log.debug("ClearspaceManager: " + buf.toString()); } } /** * Constructs a new ClearspaceManager instance. Typically, {@link #getInstance()} should be * called instead of this method. ClearspaceManager instances should only be created directly * for testing purposes. * */ public ClearspaceManager() { super("Clearspace integration module"); // Create a special Map implementation to wrap XMLProperties. We only implement // the get, put, and remove operations, since those are the only ones used. Using a Map // makes it easier to perform LdapManager testing. this.properties = new Map<String, String>() { public String get(Object key) { return JiveGlobals.getXMLProperty((String)key); } public String put(String key, String value) { JiveGlobals.setXMLProperty(key, value); // Always return null since XMLProperties doesn't support the normal semantics. return null; } public String remove(Object key) { JiveGlobals.deleteXMLProperty((String)key); // Always return null since XMLProperties doesn't support the normal semantics. return null; } public int size() { return 0; } public boolean isEmpty() { return false; } public boolean containsKey(Object key) { return false; } public boolean containsValue(Object value) { return false; } public void putAll(Map<? extends String, ? extends String> t) { } public void clear() { } public Set<String> keySet() { return null; } public Collection<String> values() { return null; } public Set<Entry<String, String>> entrySet() { return null; } }; this.uri = JiveGlobals.getXMLProperty("clearspace.uri"); sharedSecret = JiveGlobals.getXMLProperty("clearspace.sharedSecret"); if (uri != null && !"".equals(uri.trim())) { try { URL url = new URL(uri); host = url.getHost(); port = url.getPort(); } catch (MalformedURLException e) { // this won't happen } } if (Log.isDebugEnabled()) { StringBuilder buf = new StringBuilder(); buf.append("Created new ClearspaceManager() instance, fields:\n"); buf.append("\t URI: ").append(uri).append("\n"); buf.append("\t sharedSecret: ").append(sharedSecret).append("\n"); Log.debug("ClearspaceManager: " + buf.toString()); } } /** * Check a username/password pair for valid authentication. * * @param username Username to authenticate against. * @param password Password to use for authentication. * @return True or false of the authentication succeeded. */ public Boolean checkAuthentication(String username, String password) { try { String path = ClearspaceAuthProvider.URL_PREFIX + "authenticate/" + username + "/" + password; executeRequest(GET, path); return true; } catch (Exception e) {} return false; } /** * Tests the web services connection with Clearspace given the manager's current configuration. * * @return True if connection test was successful. */ public Boolean testConnection() { // Test invoking a simple method try { String path = ClearspaceUserProvider.USER_URL_PREFIX + "users/count"; Element element = executeRequest(GET, path); int count = Integer.valueOf(getReturn(element)); return true; } catch (Exception e) {} return false; } /** * Returns the Clearspace service URI; e.g. <tt>https://localhost:80/clearspace</tt>. * This value is stored as the Jive Property <tt>clearspace.uri</tt>. * * @return the Clearspace service URI. */ public String getConnectionURI() { return uri; } /** * Sets the URI of the Clearspace service; e.g., <tt>https://localhost:80/clearspace</tt>. * This value is stored as the Jive Property <tt>clearspace.uri</tt>. * * @param uri the Clearspace service URI. */ public void setConnectionURI(String uri) { if (!uri.endsWith("/")) { uri = uri + "/"; } this.uri = uri; properties.put("clearspace.uri", uri); if (isEnabled()) { startClearspaceConfig(); } } /** * Returns the password, configured in Clearspace, that Openfire will use to authenticate * with Clearspace to perform it's integration. * * @return the password Openfire will use to authenticate with Clearspace. */ public String getSharedSecret() { return sharedSecret; } /** * Sets the shared secret for the Clearspace service we're connecting to. * * @param sharedSecret the password configured in Clearspace to authenticate Openfire. */ public void setSharedSecret(String sharedSecret) { this.sharedSecret = sharedSecret; properties.put("clearspace.sharedSecret", sharedSecret); // Set new password for external component ExternalComponentConfiguration configuration = new ExternalComponentConfiguration("clearspace", ExternalComponentConfiguration.Permission.allowed, sharedSecret); try { ExternalComponentManager.allowAccess(configuration); } catch (ModificationNotAllowedException e) { Log.warn("Failed to configure password for Clearspace", e); } } /** * Returns true if Clearspace is being used as the backend of Openfire. When * integrated with Clearspace then users and groups will be pulled out from * Clearspace. User authentication will also rely on Clearspace. * * @return true if Clearspace is being used as the backend of Openfire. */ public boolean isEnabled() { return AuthFactory.getAuthProvider() instanceof ClearspaceAuthProvider; } public void start() throws IllegalStateException { super.start(); if (isEnabled()) { // Before starting up service make sure there is a default secret if (ExternalComponentManager.getDefaultSecret() == null || "".equals(ExternalComponentManager.getDefaultSecret())) { try { ExternalComponentManager.setDefaultSecret(StringUtils.randomString(10)); } catch (ModificationNotAllowedException e) { Log.warn("Failed to set a default secret to external component service", e); } } // Make sure that external component service is enabled if (!ExternalComponentManager.isServiceEnabled()) { try { ExternalComponentManager.setServiceEnabled(true); } catch (ModificationNotAllowedException e) { Log.warn("Failed to start external component service", e); } } // Listen for changes to external component settings ExternalComponentManager.addListener(this); // Starts the clearspace configuration task startClearspaceConfig(); } } /** * */ private void startClearspaceConfig() { // Start the task if it is not currently running if (configClearspaceTask == null) { configClearspaceTask = new ConfigClearspaceTask(); TaskEngine.getInstance().schedule(configClearspaceTask, 0, JiveConstants.MINUTE); }/* try { configClearspace(); } catch (UnauthorizedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } */ } private synchronized void configClearspace() throws UnauthorizedException { try { XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo(); // TODO use the post method // Creates the XML with the data /** Document groupDoc = DocumentHelper.createDocument(); Element rootE = groupDoc.addElement("connect"); Element domainE = rootE.addElement("domain"); domainE.setText(serverInfo.getXMPPDomain()); Element hostsE = rootE.addElement("hosts"); List<String> bindInterfaces = getServerInterfaces(); hostsE.setText("127.0.0.1"); Element portE = rootE.addElement("port"); portE.setText(String.valueOf(ExternalComponentManager.getServicePort())); executeRequest(POST, path, rootE.asXML()); */ List<String> bindInterfaces = getServerInterfaces(); String path = IM_URL_PREFIX + "configureComponent/" + serverInfo.getXMPPDomain() + "/" + WSUtils.marshallList(bindInterfaces) + "/" + String.valueOf(ExternalComponentManager.getServicePort()); executeRequest(GET, path); //Done, Clearspace was configured correctly, clear the task TaskEngine.getInstance().cancelScheduledTask(configClearspaceTask); configClearspaceTask = null; } catch (UnauthorizedException ue) { throw ue; } catch (Exception e) { // It is not supported exception, wrap it into an UnsupportedOperationException throw new UnsupportedOperationException("Unexpected error", e); } } private List<String> getServerInterfaces() { List<String> bindInterfaces = new ArrayList<String>(); String interfaceName = JiveGlobals.getXMLProperty("network.interface"); String bindInterface = null; if (interfaceName != null) { if (interfaceName.trim().length() > 0) { bindInterface = interfaceName; } } int adminPort = JiveGlobals.getXMLProperty("adminConsole.port", 9090); int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091); if (bindInterface == null) { Enumeration<NetworkInterface> nets = null; try { nets = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { // We failed to discover a valid IP address where the admin console is running return null; } for (NetworkInterface netInterface : Collections.list(nets)) { Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); for (InetAddress address : Collections.list(addresses)) { if ("127.0.0.1".equals(address.getHostAddress())) { continue; } Socket socket = new Socket(); InetSocketAddress remoteAddress = new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort); try { socket.connect(remoteAddress); bindInterfaces.add(address.getHostAddress()); break; } catch (IOException e) { // Ignore this address. Let's hope there is more addresses to validate } } } } return bindInterfaces; } private void updateClearspaceSharedSecret(String newSecret) { try { String path = IM_URL_PREFIX + "updateSharedSecret/" + newSecret; executeRequest(GET, path); //TODO use the post method /* // Creates the XML with the data Document groupDoc = DocumentHelper.createDocument(); Element rootE = groupDoc.addElement("updateSharedSecret"); rootE.addElement("newSecret").setText(newSecret ); executeRequest(POST, path, groupDoc.asXML()); */ } catch (UnauthorizedException ue) { // TODO what should happen here? should continue? } catch (Exception e) { // TODO what should happen here? should continue? } } public void serviceEnabled(boolean enabled) throws ModificationNotAllowedException { // Do not let admins shutdown the external component service if (!enabled) { throw new ModificationNotAllowedException("Service cannot be disabled when integrated with Clearspace."); } } public void portChanged(int newPort) throws ModificationNotAllowedException { startClearspaceConfig(); } public void defaultSecretChanged(String newSecret) throws ModificationNotAllowedException { // Do nothing } public void permissionPolicyChanged(ExternalComponentManager.PermissionPolicy newPolicy) throws ModificationNotAllowedException { // Do nothing } public void componentAllowed(String subdomain, ExternalComponentConfiguration configuration) throws ModificationNotAllowedException { if (subdomain.startsWith("clearspace")) { updateClearspaceSharedSecret(configuration.getSecret()); } } public void componentBlocked(String subdomain) throws ModificationNotAllowedException { if (subdomain.startsWith("clearspace")) { throw new ModificationNotAllowedException("Communication with Clearspace cannot be blocked."); } } public void componentSecretUpdated(String subdomain, String newSecret) throws ModificationNotAllowedException { if (subdomain.startsWith("clearspace")) { updateClearspaceSharedSecret(newSecret); } } public void componentConfigurationDeleted(String subdomain) throws ModificationNotAllowedException { // Do not let admins delete configuration of Clearspace component if (subdomain.startsWith("clearspace")) { throw new ModificationNotAllowedException("Use 'Profile Settings' to change password."); } } /** * Makes a rest request of either type GET or DELETE at the specified urlSuffix. * * urlSuffix should be of the form /userService/users * * @param type Must be GET or DELETE * @param urlSuffix The url suffix of the rest request * @return The response as a xml doc. * @throws Exception Thrown if there are issues parsing the request. */ public Element executeRequest(HttpType type, String urlSuffix) throws Exception { assert (type == HttpType.GET || type == HttpType.DELETE); return executeRequest(type, urlSuffix, null); } public Element executeRequest(HttpType type, String urlSuffix, String xmlParams) throws Exception { Log.debug("Outgoing REST call ["+type+"] to "+urlSuffix+": "+xmlParams); String wsUrl = getConnectionURI() + WEBSERVICES_PATH + urlSuffix; String secret = getSharedSecret(); HttpClient client = new HttpClient(); HttpMethod method; // Configures the authentication client.getParams().setAuthenticationPreemptive(true); Credentials credentials = new UsernamePasswordCredentials(OPENFIRE_USERNAME, secret); AuthScope scope = new AuthScope(host, port, AuthScope.ANY_REALM); client.getState().setCredentials(scope, credentials); // Creates the method switch (type) { case GET: method = new GetMethod(wsUrl); break; case POST: PostMethod pm = new PostMethod(wsUrl); StringRequestEntity requestEntity = new StringRequestEntity(xmlParams); pm.setRequestEntity(requestEntity); method = pm; break; case PUT: PutMethod pm1 = new PutMethod(wsUrl); StringRequestEntity requestEntity1 = new StringRequestEntity(xmlParams); pm1.setRequestEntity(requestEntity1); method = pm1; break; case DELETE: method = new DeleteMethod(wsUrl); break; default: throw new IllegalArgumentException(); } method.setRequestHeader("Accept", "text/xml"); method.setDoAuthentication(true); try { // Excecutes the resquest client.executeMethod(method); // Parses the result String body = method.getResponseBodyAsString(); Log.debug("Outgoing REST call results: "+body); Element response = localParser.get().parseDocument(body).getRootElement(); // Check for exceptions checkFault(response); // Since there is no exception, returns the response return response; } finally { method.releaseConnection(); } } private void checkFault(Element response) throws Exception { Node node = response.selectSingleNode("ns1:faultstring"); if (node != null) { String exceptionText = node.getText(); // Text accepted samples: // 'java.lang.Exception: Exception message' // 'java.lang.Exception' // Get the exception class and message if any int index = exceptionText.indexOf(":"); String className = null; String message = null; // If there is no massege, save the class only if (index == -1) { className = exceptionText; message = null; } else { // Else save both className = exceptionText.substring(0, index); message = exceptionText.substring(index + 2); } // Map the exception to a Openfire one, if possible if (exceptionMap.containsKey(className)) { className = exceptionMap.get(className); } //Tries to create an instance with the message Exception exception = null; try { Class exceptionClass = Class.forName(className); if (message == null) { exception = (Exception) exceptionClass.newInstance(); } else { Constructor constructor = exceptionClass.getConstructor(String.class); exception = (Exception) constructor.newInstance(message); } } catch (Exception e) { // failed to create an specific exception, creating a standar one. exception = new Exception(exceptionText); } throw exception; } } /** * Returns the Clearspace user id the user. * @param username * @return * @throws org.jivesoftware.openfire.user.UserNotFoundException */ protected long getUserID(String username) throws UserNotFoundException { // todo implement cache if(username.contains("@")) { if (!XMPPServer.getInstance().isLocal(new JID(username))) { throw new UserNotFoundException("Cannot load user of remote server: " + username); } username = username.substring(0,username.lastIndexOf("@")); } return getUserID(XMPPServer.getInstance().createJID(username, null)); } /** * Returns the Clearspace user id the user. * @param user * @return * @throws org.jivesoftware.openfire.user.UserNotFoundException */ protected long getUserID(JID user) throws UserNotFoundException { // todo implement cache //todo tema de si es local o no XMPPServer server = XMPPServer.getInstance(); String username = server.isLocal(user) ? JID.unescapeNode(user.getNode()) : user.toString(); try { String path = ClearspaceUserProvider.USER_URL_PREFIX + "users/" + username; Element element = executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path); return Long.valueOf(WSUtils.getElementText(element.selectSingleNode("return"), "ID")); } catch (UserNotFoundException unfe) { // It is a supported exception, throw it again throw unfe; } catch (Exception e) { // It is not asupperted exception, wrap it into a UserNotFoundException throw new UserNotFoundException("Unexpected error", e); } } /** * Returns the Clearspace group id of the group. * @param groupname * @return * @throws org.jivesoftware.openfire.group.GroupNotFoundException */ protected long getGroupID(String groupname) throws GroupNotFoundException { // todo implement cache try { String path = ClearspaceGroupProvider.URL_PREFIX + "groups/" + groupname; Element element = executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path); return Long.valueOf(WSUtils.getElementText(element.selectSingleNode("return"), "ID")); } catch (GroupNotFoundException gnfe) { // It is a supported exception, throw it again throw gnfe; } catch (Exception e) { // It is not asupperted exception, wrap it into a GroupNotFoundException throw new GroupNotFoundException("Unexpected error", e); } } private class ConfigClearspaceTask extends TimerTask { public void run() { try { configClearspace(); } catch (UnauthorizedException e) { //TODO mark that there is an authorization problem } } } }
Ported updates from 3.5.0 branch. git-svn-id: 2e83ce7f183c9abd424edb3952fab2cdab7acd7f@9974 b35dd754-fafc-0310-a699-88a17e54d16e
src/java/org/jivesoftware/openfire/clearspace/ClearspaceManager.java
Ported updates from 3.5.0 branch.
<ide><path>rc/java/org/jivesoftware/openfire/clearspace/ClearspaceManager.java <ide> String path = ClearspaceAuthProvider.URL_PREFIX + "authenticate/" + username + "/" + password; <ide> executeRequest(GET, path); <ide> return true; <del> } catch (Exception e) {} <add> } catch (Exception e) { <add> // Nothing to do. <add> } <ide> <ide> return false; <ide> } <ide> try { <ide> String path = ClearspaceUserProvider.USER_URL_PREFIX + "users/count"; <ide> Element element = executeRequest(GET, path); <del> int count = Integer.valueOf(getReturn(element)); <add> getReturn(element); <ide> return true; <del> } catch (Exception e) {} <add> } catch (Exception e) { <add> // Nothing to do. <add> } <ide> <ide> return false; <ide> } <ide> <ide> private synchronized void configClearspace() throws UnauthorizedException { <ide> try { <del> <add> List<String> bindInterfaces = getServerInterfaces(); <add> if (bindInterfaces.size() == 0) { <add> // We aren't up and running enough to tell Clearspace what interfaces to bind to. <add> return; <add> } <ide> <ide> XMPPServerInfo serverInfo = XMPPServer.getInstance().getServerInfo(); <ide> <del> // TODO use the post method <del> // Creates the XML with the data <del> /** <del> Document groupDoc = DocumentHelper.createDocument(); <del> Element rootE = groupDoc.addElement("connect"); <del> Element domainE = rootE.addElement("domain"); <del> domainE.setText(serverInfo.getXMPPDomain()); <del> Element hostsE = rootE.addElement("hosts"); <del> List<String> bindInterfaces = getServerInterfaces(); <del> hostsE.setText("127.0.0.1"); <del> Element portE = rootE.addElement("port"); <del> portE.setText(String.valueOf(ExternalComponentManager.getServicePort())); <del> <del> executeRequest(POST, path, rootE.asXML()); <del> */ <del> List<String> bindInterfaces = getServerInterfaces(); <add> // TODO: Eventually we would like to get POST support working properly. <add>// String path = IM_URL_PREFIX + "configureComponent/"; <add>// <add>// // Creates the XML with the data <add>// Document groupDoc = DocumentHelper.createDocument(); <add>// Element rootE = groupDoc.addElement("configureComponent"); <add>// Element domainE = rootE.addElement("domain"); <add>// domainE.setText(serverInfo.getXMPPDomain()); <add>// Element hostsE = rootE.addElement("hosts"); <add>// hostsE.setText(WSUtils.marshallList(bindInterfaces)); <add>// Element portE = rootE.addElement("port"); <add>// portE.setText(String.valueOf(ExternalComponentManager.getServicePort())); <add>// <add>// executeRequest(POST, path, rootE.asXML()); <ide> <ide> String path = IM_URL_PREFIX + "configureComponent/" + serverInfo.getXMPPDomain() + <ide> "/" + WSUtils.marshallList(bindInterfaces) + <ide> int adminSecurePort = JiveGlobals.getXMLProperty("adminConsole.securePort", 9091); <ide> <ide> if (bindInterface == null) { <del> Enumeration<NetworkInterface> nets = null; <ide> try { <del> nets = NetworkInterface.getNetworkInterfaces(); <add> Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); <add> for (NetworkInterface netInterface : Collections.list(nets)) { <add> Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); <add> for (InetAddress address : Collections.list(addresses)) { <add> if ("127.0.0.1".equals(address.getHostAddress())) { <add> continue; <add> } <add> if (address.getHostAddress().startsWith("0.")) { <add> continue; <add> } <add> Socket socket = new Socket(); <add> InetSocketAddress remoteAddress = new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort); <add> try { <add> socket.connect(remoteAddress); <add> bindInterfaces.add(address.getHostAddress()); <add> break; <add> } catch (IOException e) { <add> // Ignore this address. Let's hope there is more addresses to validate <add> } <add> } <add> } <ide> } catch (SocketException e) { <ide> // We failed to discover a valid IP address where the admin console is running <ide> return null; <ide> } <del> for (NetworkInterface netInterface : Collections.list(nets)) { <del> Enumeration<InetAddress> addresses = netInterface.getInetAddresses(); <del> for (InetAddress address : Collections.list(addresses)) { <del> if ("127.0.0.1".equals(address.getHostAddress())) { <del> continue; <del> } <del> Socket socket = new Socket(); <del> InetSocketAddress remoteAddress = new InetSocketAddress(address, adminPort > 0 ? adminPort : adminSecurePort); <del> try { <del> socket.connect(remoteAddress); <del> bindInterfaces.add(address.getHostAddress()); <del> break; <del> } catch (IOException e) { <del> // Ignore this address. Let's hope there is more addresses to validate <del> } <del> } <del> } <ide> } <ide> return bindInterfaces; <ide> } <ide> private void updateClearspaceSharedSecret(String newSecret) { <ide> <ide> try { <add> // Keeping this around for the moment just in case. <ide> String path = IM_URL_PREFIX + "updateSharedSecret/" + newSecret; <del> <ide> executeRequest(GET, path); <ide> <del> //TODO use the post method <del> /* <del> // Creates the XML with the data <del> Document groupDoc = DocumentHelper.createDocument(); <del> Element rootE = groupDoc.addElement("updateSharedSecret"); <del> rootE.addElement("newSecret").setText(newSecret <del> ); <del> <del> executeRequest(POST, path, groupDoc.asXML()); <del> */ <add> // TODO: We should switch to POST once we figure out why it's not behaving. <add>// String path = IM_URL_PREFIX + "updateSharedSecret/"; <add>// <add>// // Creates the XML with the data <add>// Document groupDoc = DocumentHelper.createDocument(); <add>// Element rootE = groupDoc.addElement("updateSharedSecret"); <add>// rootE.addElement("newSecret").setText(newSecret); <add>// <add>// executeRequest(POST, path, groupDoc.asXML()); <ide> } catch (UnauthorizedException ue) { <del> // TODO what should happen here? should continue? <add> // TODO: what should happen here? should continue? <ide> } catch (Exception e) { <del> // TODO what should happen here? should continue? <add> // TODO: what should happen here? should continue? <ide> } <ide> <ide> } <ide> <ide> // Get the exception class and message if any <ide> int index = exceptionText.indexOf(":"); <del> String className = null; <del> String message = null; <add> String className; <add> String message; <ide> // If there is no massege, save the class only <ide> if (index == -1) { <ide> className = exceptionText; <ide> } <ide> <ide> //Tries to create an instance with the message <del> Exception exception = null; <add> Exception exception; <ide> try { <ide> Class exceptionClass = Class.forName(className); <ide> if (message == null) { <ide> } <ide> <ide> /** <del> * Returns the Clearspace user id the user. <del> * @param username <del> * @return <del> * @throws org.jivesoftware.openfire.user.UserNotFoundException <add> * Returns the Clearspace user id the user by username. <add> * @param username Username to retrieve ID of. <add> * @return The ID number of the user in Clearspace. <add> * @throws org.jivesoftware.openfire.user.UserNotFoundException If the user was not found. <ide> */ <ide> protected long getUserID(String username) throws UserNotFoundException { <ide> // todo implement cache <ide> } <ide> <ide> /** <del> * Returns the Clearspace user id the user. <del> * @param user <del> * @return <del> * @throws org.jivesoftware.openfire.user.UserNotFoundException <add> * Returns the Clearspace user id the user by JID. <add> * @param user JID of user to retrieve ID of. <add> * @return The ID number of the user in Clearspace. <add> * @throws org.jivesoftware.openfire.user.UserNotFoundException If the user was not found. <ide> */ <ide> protected long getUserID(JID user) throws UserNotFoundException { <del> // todo implement cache <del> //todo tema de si es local o no <add> // TODO: implement cache, after we are listening for user events from Clearspace. <ide> XMPPServer server = XMPPServer.getInstance(); <ide> String username = server.isLocal(user) ? JID.unescapeNode(user.getNode()) : user.toString(); <ide> try { <ide> <ide> /** <ide> * Returns the Clearspace group id of the group. <del> * @param groupname <del> * @return <del> * @throws org.jivesoftware.openfire.group.GroupNotFoundException <add> * @param groupname Name of the group to retrieve ID of. <add> * @return The ID number of the group in Clearspace. <add> * @throws org.jivesoftware.openfire.group.GroupNotFoundException If the group was not found. <ide> */ <ide> protected long getGroupID(String groupname) throws GroupNotFoundException { <del> // todo implement cache <add> // TODO: implement cache, after we are listening for group events from Clearspace. <ide> try { <ide> String path = ClearspaceGroupProvider.URL_PREFIX + "groups/" + groupname; <ide> Element element = executeRequest(org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET, path); <ide> try { <ide> configClearspace(); <ide> } catch (UnauthorizedException e) { <del> //TODO mark that there is an authorization problem <add> // TODO: mark that there is an authorization problem <ide> } <ide> } <ide> }
Java
apache-2.0
8cec1ac1b0accd1d849aafacafd8011613c5af1b
0
oehf/ipf,oehf/ipf,oehf/ipf,oehf/ipf
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openehealth.ipf.commons.audit.marshal.dicom; import org.jdom2.Content; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.openehealth.ipf.commons.audit.marshal.SerializationStrategy; import org.openehealth.ipf.commons.audit.model.*; import org.openehealth.ipf.commons.audit.types.AuditSource; import org.openehealth.ipf.commons.audit.types.CodedValueType; import org.openehealth.ipf.commons.audit.types.EnumeratedValueSet; import java.io.IOException; import java.io.Writer; import java.nio.charset.StandardCharsets; /** * @author Christian Ohr * @since 3.5 */ public class DICOM2016a implements SerializationStrategy { // Omit XML declaration, because this is done as part of the RFC5424Protocol private static final XMLOutputter PRETTY = new XMLOutputter(Format.getPrettyFormat().setOmitDeclaration(true)); private static final XMLOutputter COMPACT = new XMLOutputter(Format.getCompactFormat().setOmitDeclaration(true)); @Override public void marshal(AuditMessage auditMessage, Writer writer, boolean pretty) throws IOException { serialize(auditMessage, writer, pretty ? PRETTY : COMPACT); } private void serialize(AuditMessage auditMessage, Writer writer, XMLOutputter outputter) throws IOException { Element element = new Element("AuditMessage"); element.addContent(eventIdentification(auditMessage.getEventIdentification())); auditMessage.getActiveParticipants().stream() .map(this::activeParticipant) .forEach(element::addContent); element.addContent(auditSourceIdentification(auditMessage.getAuditSourceIdentification())); auditMessage.getParticipantObjectIdentifications().stream() .map(this::participantObjectIdentification) .forEach(element::addContent); outputter.output(new Document(element), writer); } protected Content activeParticipant(ActiveParticipantType activeParticipant) { Element element = new Element("ActiveParticipant"); element.setAttribute("UserID", activeParticipant.getUserID()); conditionallyAddAttribute(element, "AlternativeUserID", activeParticipant.getAlternativeUserID()); conditionallyAddAttribute(element, "UserName", activeParticipant.getUserName()); element.setAttribute("UserIsRequestor", Boolean.toString(activeParticipant.isUserIsRequestor())); conditionallyAddAttribute(element, "NetworkAccessPointID", activeParticipant.getNetworkAccessPointID()); conditionallyAddAttribute(element, "NetworkAccessPointTypeCode", activeParticipant.getNetworkAccessPointTypeCode()); if (activeParticipant.getMediaType() != null) { element.addContent( new Element("MediaIdentifier") .addContent(codedValueType("MediaType", activeParticipant.getMediaType()))); } if (activeParticipant.getRoleIDCodes() != null) { activeParticipant.getRoleIDCodes().stream() .map(roleIdCode -> codedValueType("RoleIDCode", roleIdCode)) .forEach(element::addContent); } return element; } protected Element eventIdentification(EventIdentificationType eventIdentification) { Element element = new Element("EventIdentification"); if (eventIdentification != null) { element.setAttribute("EventActionCode", eventIdentification.getEventActionCode().getValue()); element.setAttribute("EventDateTime", eventIdentification.getEventDateTime().toString()); element.setAttribute("EventOutcomeIndicator", eventIdentification.getEventOutcomeIndicator().getValue().toString()); if (eventIdentification.getEventID() != null) { element.addContent(codedValueType("EventID", eventIdentification.getEventID())); } eventIdentification.getEventTypeCode().stream() .map(eventTypeCode -> codedValueType("EventTypeCode", eventTypeCode)) .forEach(element::addContent); if (eventIdentification.getEventOutcomeDescription() != null) { element.addContent( new Element("EventOutcomeDescription") .addContent(eventIdentification.getEventOutcomeDescription())); } eventIdentification.getPurposesOfUse().stream() .map(purposeOfUse -> codedValueType("PurposeOfUse", purposeOfUse)) .forEach(element::addContent); } return element; } protected Element participantObjectIdentification(ParticipantObjectIdentificationType poi) { Element element = new Element("ParticipantObjectIdentification"); if (poi != null) { conditionallyAddAttribute(element, "ParticipantObjectID", poi.getParticipantObjectID()); conditionallyAddAttribute(element, "ParticipantObjectTypeCode", poi.getParticipantObjectTypeCode().getValue().toString()); conditionallyAddAttribute(element, "ParticipantObjectTypeCodeRole", poi.getParticipantObjectTypeCodeRole()); conditionallyAddAttribute(element, "ParticipantObjectDataLifeCycle", poi.getParticipantObjectDataLifeCycle()); conditionallyAddAttribute(element, "ParticipantObjectSensitivity", poi.getParticipantObjectSensitivity()); if (poi.getParticipantObjectIDTypeCode() != null) { element.addContent(codedValueType("ParticipantObjectIDTypeCode", poi.getParticipantObjectIDTypeCode())); } if (poi.getParticipantObjectName() != null) { element.addContent(new Element("ParticipantObjectName") .addContent(poi.getParticipantObjectName())); } if (poi.getParticipantObjectQuery() != null) { element.addContent(new Element("ParticipantObjectQuery") .addContent(new String(poi.getParticipantObjectQuery(), StandardCharsets.UTF_8))); } poi.getParticipantObjectDetails().stream() .map(participantObjectDetail -> typeValuePairType("ParticipantObjectDetail", participantObjectDetail)) .forEach(element::addContent); poi.getParticipantObjectDescriptions().stream() .map(this::dicomObjectDescription) .forEach(element::addContent); } return element; } protected Element auditSourceIdentification(AuditSourceIdentificationType auditSourceIdentification) { Element element = new Element("AuditSourceIdentification"); if (auditSourceIdentification != null) { conditionallyAddAttribute(element, "AuditEnterpriseSiteID", auditSourceIdentification.getAuditEnterpriseSiteID()); conditionallyAddAttribute(element, "AuditSourceID", auditSourceIdentification.getAuditSourceID()); auditSourceIdentification.getAuditSourceType().stream() .map(this::auditSourceType) .forEach(element::addContent); } return element; } protected Element auditSourceType(AuditSource auditSourceType) { return new Element("AuditSourceTypeCode").addContent(auditSourceType.getCode()); } protected Element codedValueType(String tagName, CodedValueType codedValue) { Element element = new Element(tagName); element.setAttribute("csd-code", codedValue.getCode()); conditionallyAddAttribute(element, "codeSystemName", codedValue.getCodeSystemName()); conditionallyAddAttribute(element, "displayName", codedValue.getDisplayName()); conditionallyAddAttribute(element, "originalText", codedValue.getOriginalText()); return element; } protected Element typeValuePairType(String tagName, TypeValuePairType typeValuePair) { Element element = new Element(tagName); element.setAttribute("type", typeValuePair.getType()); element.setAttribute("value", new String(typeValuePair.getValue(), StandardCharsets.UTF_8)); return element; } protected Element dicomObjectDescription(DicomObjectDescriptionType dicomObjectDescription) { Element pod = new Element("ParticipantObjectDescription"); dicomObjectDescription.getMPPS().forEach(mpps -> pod.addContent(new Element("MPPS").setAttribute("UID", mpps))); dicomObjectDescription.getAccession().forEach(accession -> pod.addContent(new Element("Accession").setAttribute("Number", accession))); dicomObjectDescription.getSOPClasses().forEach(sop -> { Element sopClass = new Element("SOPClass") .setAttribute("NumberOfInstances", String.valueOf(sop.getNumberOfInstances())); conditionallyAddAttribute(sopClass, "UID", sop.getUid()); sop.getInstanceUids().forEach(uid -> sopClass.addContent(new Element("Instance").setAttribute("UID", uid))); pod.addContent(sopClass); }); if (!dicomObjectDescription.getStudyIDs().isEmpty()) { Element participantObjectContainsStudy = new Element("ParticipantObjectContainsStudy "); dicomObjectDescription.getStudyIDs().forEach(studyID -> participantObjectContainsStudy.addContent( new Element("StudyIDs ") .setAttribute("UID", studyID))); pod.addContent(participantObjectContainsStudy); } if (dicomObjectDescription.getEncrypted() != null) { pod.addContent( new Element("Encrypted") .addContent(String.valueOf(dicomObjectDescription.getEncrypted()))); } if (dicomObjectDescription.getAnonymized() != null) { pod.addContent( new Element("Anonymized") .addContent(String.valueOf(dicomObjectDescription.getAnonymized()))); } return pod; } protected void conditionallyAddAttribute(Element element, String attributeName, String value) { if (value != null) { element.setAttribute(attributeName, value); } } protected void conditionallyAddAttribute(Element element, String attributeName, EnumeratedValueSet<?> value) { if (value != null) { element.setAttribute(attributeName, value.getValue().toString()); } } }
commons/audit/src/main/java/org/openehealth/ipf/commons/audit/marshal/dicom/DICOM2016a.java
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openehealth.ipf.commons.audit.marshal.dicom; import org.jdom2.Content; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.openehealth.ipf.commons.audit.marshal.SerializationStrategy; import org.openehealth.ipf.commons.audit.model.*; import org.openehealth.ipf.commons.audit.types.AuditSource; import org.openehealth.ipf.commons.audit.types.CodedValueType; import org.openehealth.ipf.commons.audit.types.EnumeratedValueSet; import java.io.IOException; import java.io.Writer; import java.nio.charset.StandardCharsets; /** * @author Christian Ohr * @since 3.5 */ public class DICOM2016a implements SerializationStrategy { // Omit XML declaration, because this is done as part of the RFC5424Protocol private static final XMLOutputter PRETTY = new XMLOutputter(Format.getPrettyFormat().setOmitDeclaration(true)); private static final XMLOutputter COMPACT = new XMLOutputter(Format.getCompactFormat().setOmitDeclaration(true)); @Override public void marshal(AuditMessage auditMessage, Writer writer, boolean pretty) throws IOException { serialize(auditMessage, writer, pretty ? PRETTY : COMPACT); } private void serialize(AuditMessage auditMessage, Writer writer, XMLOutputter outputter) throws IOException { Element element = new Element("AuditMessage"); element.addContent(eventIdentification(auditMessage.getEventIdentification())); auditMessage.getActiveParticipants().stream() .map(this::activeParticipant) .forEach(element::addContent); element.addContent(auditSourceIdentification(auditMessage.getAuditSourceIdentification())); auditMessage.getParticipantObjectIdentifications().stream() .map(this::participantObjectIdentification) .forEach(element::addContent); outputter.output(new Document(element), writer); } protected Content activeParticipant(ActiveParticipantType activeParticipant) { Element element = new Element("ActiveParticipant"); element.setAttribute("UserID", activeParticipant.getUserID()); conditionallyAddAttribute(element, "AlternativeUserID", activeParticipant.getAlternativeUserID()); conditionallyAddAttribute(element, "UserName", activeParticipant.getUserName()); element.setAttribute("UserIsRequestor", Boolean.toString(activeParticipant.isUserIsRequestor())); conditionallyAddAttribute(element, "NetworkAccessPointID", activeParticipant.getNetworkAccessPointID()); conditionallyAddAttribute(element, "NetworkAccessPointTypeCode", activeParticipant.getNetworkAccessPointTypeCode()); // TODO mediaidentifier/mediatype if (activeParticipant.getRoleIDCodes() != null) { activeParticipant.getRoleIDCodes().stream() .map(roleIdCode -> codedValueType("RoleIDCode", roleIdCode)) .forEach(element::addContent); } return element; } protected Element eventIdentification(EventIdentificationType eventIdentification) { Element element = new Element("EventIdentification"); if (eventIdentification != null) { element.setAttribute("EventActionCode", eventIdentification.getEventActionCode().getValue()); element.setAttribute("EventDateTime", eventIdentification.getEventDateTime().toString()); element.setAttribute("EventOutcomeIndicator", eventIdentification.getEventOutcomeIndicator().getValue().toString()); if (eventIdentification.getEventID() != null) { element.addContent(codedValueType("EventID", eventIdentification.getEventID())); } eventIdentification.getEventTypeCode().stream() .map(eventTypeCode -> codedValueType("EventTypeCode", eventTypeCode)) .forEach(element::addContent); if (eventIdentification.getEventOutcomeDescription() != null) { element.addContent( new Element("EventOutcomeDescription") .addContent(eventIdentification.getEventOutcomeDescription())); } eventIdentification.getPurposesOfUse().stream() .map(purposeOfUse -> codedValueType("PurposeOfUse", purposeOfUse)) .forEach(element::addContent); } return element; } protected Element participantObjectIdentification(ParticipantObjectIdentificationType poi) { Element element = new Element("ParticipantObjectIdentification"); if (poi != null) { conditionallyAddAttribute(element, "ParticipantObjectID", poi.getParticipantObjectID()); conditionallyAddAttribute(element, "ParticipantObjectTypeCode", poi.getParticipantObjectTypeCode().getValue().toString()); conditionallyAddAttribute(element, "ParticipantObjectTypeCodeRole", poi.getParticipantObjectTypeCodeRole()); conditionallyAddAttribute(element, "ParticipantObjectDataLifeCycle", poi.getParticipantObjectDataLifeCycle()); conditionallyAddAttribute(element, "ParticipantObjectSensitivity", poi.getParticipantObjectSensitivity()); if (poi.getParticipantObjectIDTypeCode() != null) { element.addContent(codedValueType("ParticipantObjectIDTypeCode", poi.getParticipantObjectIDTypeCode())); } if (poi.getParticipantObjectName() != null) { element.addContent(new Element("ParticipantObjectName") .addContent(poi.getParticipantObjectName())); } if (poi.getParticipantObjectQuery() != null) { element.addContent(new Element("ParticipantObjectQuery") .addContent(new String(poi.getParticipantObjectQuery(), StandardCharsets.UTF_8))); } poi.getParticipantObjectDetails().stream() .map(participantObjectDetail -> typeValuePairType("ParticipantObjectDetail", participantObjectDetail)) .forEach(element::addContent); poi.getParticipantObjectDescriptions().stream() .map(this::dicomObjectDescription) .forEach(element::addContent); } return element; } protected Element auditSourceIdentification(AuditSourceIdentificationType auditSourceIdentification) { Element element = new Element("AuditSourceIdentification"); if (auditSourceIdentification != null) { conditionallyAddAttribute(element, "AuditEnterpriseSiteID", auditSourceIdentification.getAuditEnterpriseSiteID()); conditionallyAddAttribute(element, "AuditSourceID", auditSourceIdentification.getAuditSourceID()); auditSourceIdentification.getAuditSourceType().stream() .map(this::auditSourceType) .forEach(element::addContent); } return element; } protected Element auditSourceType(AuditSource auditSourceType) { return new Element("AuditSourceTypeCode").addContent(auditSourceType.getCode()); } protected Element codedValueType(String tagName, CodedValueType codedValue) { Element element = new Element(tagName); element.setAttribute("csd-code", codedValue.getCode()); conditionallyAddAttribute(element, "codeSystemName", codedValue.getCodeSystemName()); conditionallyAddAttribute(element, "displayName", codedValue.getDisplayName()); conditionallyAddAttribute(element, "originalText", codedValue.getOriginalText()); return element; } protected Element typeValuePairType(String tagName, TypeValuePairType typeValuePair) { Element element = new Element(tagName); element.setAttribute("type", typeValuePair.getType()); element.setAttribute("value", new String(typeValuePair.getValue(), StandardCharsets.UTF_8)); return element; } protected Element dicomObjectDescription(DicomObjectDescriptionType dicomObjectDescription) { Element pod = new Element("ParticipantObjectDescription"); dicomObjectDescription.getMPPS().forEach(mpps -> pod.addContent(new Element("MPPS").setAttribute("UID", mpps))); dicomObjectDescription.getAccession().forEach(accession -> pod.addContent(new Element("Accession").setAttribute("Number", accession))); dicomObjectDescription.getSOPClasses().forEach(sop -> { Element sopClass = new Element("SOPClass") .setAttribute("NumberOfInstances", String.valueOf(sop.getNumberOfInstances())); conditionallyAddAttribute(sopClass, "UID", sop.getUid()); sop.getInstanceUids().forEach(uid -> sopClass.addContent(new Element("Instance").setAttribute("UID", uid))); pod.addContent(sopClass); }); if (!dicomObjectDescription.getStudyIDs().isEmpty()) { Element participantObjectContainsStudy = new Element("ParticipantObjectContainsStudy "); dicomObjectDescription.getStudyIDs().forEach(studyID -> participantObjectContainsStudy.addContent( new Element("StudyIDs ") .setAttribute("UID", studyID))); pod.addContent(participantObjectContainsStudy); } if (dicomObjectDescription.getEncrypted() != null) { pod.addContent( new Element("Encrypted") .addContent(String.valueOf(dicomObjectDescription.getEncrypted()))); } if (dicomObjectDescription.getAnonymized() != null) { pod.addContent( new Element("Anonymized") .addContent(String.valueOf(dicomObjectDescription.getAnonymized()))); } return pod; } protected void conditionallyAddAttribute(Element element, String attributeName, String value) { if (value != null) { element.setAttribute(attributeName, value); } } protected void conditionallyAddAttribute(Element element, String attributeName, EnumeratedValueSet<?> value) { if (value != null) { element.setAttribute(attributeName, value.getValue().toString()); } } }
#177: encode mediatype
commons/audit/src/main/java/org/openehealth/ipf/commons/audit/marshal/dicom/DICOM2016a.java
#177: encode mediatype
<ide><path>ommons/audit/src/main/java/org/openehealth/ipf/commons/audit/marshal/dicom/DICOM2016a.java <ide> element.setAttribute("UserIsRequestor", Boolean.toString(activeParticipant.isUserIsRequestor())); <ide> conditionallyAddAttribute(element, "NetworkAccessPointID", activeParticipant.getNetworkAccessPointID()); <ide> conditionallyAddAttribute(element, "NetworkAccessPointTypeCode", activeParticipant.getNetworkAccessPointTypeCode()); <del>// TODO mediaidentifier/mediatype <add> if (activeParticipant.getMediaType() != null) { <add> element.addContent( <add> new Element("MediaIdentifier") <add> .addContent(codedValueType("MediaType", activeParticipant.getMediaType()))); <add> } <ide> if (activeParticipant.getRoleIDCodes() != null) { <ide> activeParticipant.getRoleIDCodes().stream() <ide> .map(roleIdCode -> codedValueType("RoleIDCode", roleIdCode))
Java
apache-2.0
b5cd56abc947358148a91a69d44966bfbdae11f7
0
zml2008/configurate,zml2008/configurate
/* * Configurate * Copyright (C) zml and Configurate contributors * * 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 ninja.leaping.configurate.commented; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.ConfigurationOptions; import ninja.leaping.configurate.SimpleConfigurationNode; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; /** * Basic implementation of {@link CommentedConfigurationNode}. */ public class SimpleCommentedConfigurationNode extends SimpleConfigurationNode implements CommentedConfigurationNode { private String comment =null; @NonNull public static SimpleCommentedConfigurationNode root() { return root(ConfigurationOptions.defaults()); } @NonNull public static SimpleCommentedConfigurationNode root(@NonNull ConfigurationOptions options) { return new SimpleCommentedConfigurationNode(null, null, options); } protected SimpleCommentedConfigurationNode(@Nullable Object path, @Nullable SimpleConfigurationNode parent, @NonNull ConfigurationOptions options) { super(path, parent, options); } protected SimpleCommentedConfigurationNode(@Nullable SimpleConfigurationNode parent, @NonNull SimpleConfigurationNode copyOf) { super(parent, copyOf); } @NonNull @Override public Optional<String> getComment() { return Optional.ofNullable(comment); } @NonNull @Override public SimpleCommentedConfigurationNode setComment(@Nullable String comment) { attachIfNecessary(); this.comment = comment; return this; } // Methods from superclass overridden to have correct return types @Nullable @Override public SimpleCommentedConfigurationNode getParent() { return (SimpleCommentedConfigurationNode) super.getParent(); } @Override protected SimpleCommentedConfigurationNode createNode(Object path) { return new SimpleCommentedConfigurationNode(path, this, getOptions()); } @NonNull @Override public SimpleCommentedConfigurationNode setValue(@Nullable Object value) { if (value instanceof CommentedConfigurationNode && ((CommentedConfigurationNode) value).getComment().isPresent()) { setComment(((CommentedConfigurationNode) value).getComment().get()); } return (SimpleCommentedConfigurationNode) super.setValue(value); } @NonNull @Override public SimpleCommentedConfigurationNode mergeValuesFrom(@NonNull ConfigurationNode other) { if (other instanceof CommentedConfigurationNode) { Optional<String> otherComment = ((CommentedConfigurationNode) other).getComment(); if (comment == null && otherComment.isPresent()) { comment = otherComment.get(); } } return (SimpleCommentedConfigurationNode) super.mergeValuesFrom(other); } @NonNull @Override public SimpleCommentedConfigurationNode getNode(@NonNull Object... path) { return (SimpleCommentedConfigurationNode) super.getNode(path); } @NonNull @Override @SuppressWarnings("unchecked") public List<? extends SimpleCommentedConfigurationNode> getChildrenList() { return (List<SimpleCommentedConfigurationNode>) super.getChildrenList(); } @NonNull @Override @SuppressWarnings("unchecked") public Map<Object, ? extends SimpleCommentedConfigurationNode> getChildrenMap() { return (Map<Object, SimpleCommentedConfigurationNode>) super.getChildrenMap(); } @NonNull @Override public SimpleCommentedConfigurationNode getAppendedNode() { return (SimpleCommentedConfigurationNode) super.getAppendedNode(); } @NonNull @Override public SimpleCommentedConfigurationNode copy() { return copy(null); } @NonNull @Override protected SimpleCommentedConfigurationNode copy(@Nullable SimpleConfigurationNode parent) { SimpleCommentedConfigurationNode copy = new SimpleCommentedConfigurationNode(parent, this); copy.comment = this.comment; return copy; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof SimpleCommentedConfigurationNode)) return false; if (!super.equals(o)) return false; SimpleCommentedConfigurationNode that = (SimpleCommentedConfigurationNode) o; if (!Objects.equals(comment, that.comment)) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + Objects.hashCode(comment); return result; } @Override public String toString() { return "SimpleCommentedConfigurationNode{" + "super=" + super.toString() + ", comment=" + comment + '}'; } }
configurate-core/src/main/java/ninja/leaping/configurate/commented/SimpleCommentedConfigurationNode.java
/* * Configurate * Copyright (C) zml and Configurate contributors * * 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 ninja.leaping.configurate.commented; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.ConfigurationOptions; import ninja.leaping.configurate.SimpleConfigurationNode; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; /** * Basic implementation of {@link CommentedConfigurationNode}. */ public class SimpleCommentedConfigurationNode extends SimpleConfigurationNode implements CommentedConfigurationNode { private String comment =null; @NonNull public static SimpleCommentedConfigurationNode root() { return root(ConfigurationOptions.defaults()); } @NonNull public static SimpleCommentedConfigurationNode root(@NonNull ConfigurationOptions options) { return new SimpleCommentedConfigurationNode(null, null, options); } protected SimpleCommentedConfigurationNode(@Nullable Object path, @Nullable SimpleConfigurationNode parent, @NonNull ConfigurationOptions options) { super(path, parent, options); } protected SimpleCommentedConfigurationNode(@Nullable SimpleConfigurationNode parent, @NonNull SimpleConfigurationNode copyOf) { super(parent, copyOf); } @NonNull @Override public Optional<String> getComment() { return Optional.ofNullable(comment); } @NonNull @Override public SimpleCommentedConfigurationNode setComment(@Nullable String comment) { attachIfNecessary(); this.comment = comment; return this; } // Methods from superclass overridden to have correct return types @Nullable @Override public SimpleCommentedConfigurationNode getParent() { return (SimpleCommentedConfigurationNode) super.getParent(); } @Override protected SimpleCommentedConfigurationNode createNode(Object path) { return new SimpleCommentedConfigurationNode(path, this, getOptions()); } @NonNull @Override public SimpleCommentedConfigurationNode setValue(@Nullable Object value) { if (value instanceof CommentedConfigurationNode && ((CommentedConfigurationNode) value).getComment().isPresent()) { setComment(((CommentedConfigurationNode) value).getComment().get()); } return (SimpleCommentedConfigurationNode) super.setValue(value); } @NonNull @Override public SimpleCommentedConfigurationNode mergeValuesFrom(@NonNull ConfigurationNode other) { if (other instanceof CommentedConfigurationNode) { Optional<String> otherComment = ((CommentedConfigurationNode) other).getComment(); if (comment == null && otherComment.isPresent()) { comment = otherComment.get(); } } return (SimpleCommentedConfigurationNode) super.mergeValuesFrom(other); } @NonNull @Override public SimpleCommentedConfigurationNode getNode(@NonNull Object... path) { return (SimpleCommentedConfigurationNode) super.getNode(path); } @NonNull @Override @SuppressWarnings("unchecked") public List<? extends SimpleCommentedConfigurationNode> getChildrenList() { return (List<SimpleCommentedConfigurationNode>) super.getChildrenList(); } @NonNull @Override @SuppressWarnings("unchecked") public Map<Object, ? extends SimpleCommentedConfigurationNode> getChildrenMap() { return (Map<Object, SimpleCommentedConfigurationNode>) super.getChildrenMap(); } @NonNull @Override public SimpleCommentedConfigurationNode getAppendedNode() { return (SimpleCommentedConfigurationNode) super.getAppendedNode(); } @NonNull @Override public SimpleCommentedConfigurationNode copy() { return copy(null); } @NonNull @Override protected SimpleCommentedConfigurationNode copy(@Nullable SimpleConfigurationNode parent) { SimpleCommentedConfigurationNode copy = new SimpleCommentedConfigurationNode(parent, this); copy.comment = this.comment; return copy; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof SimpleCommentedConfigurationNode)) return false; if (!super.equals(o)) return false; SimpleCommentedConfigurationNode that = (SimpleCommentedConfigurationNode) o; if (!comment.equals(that.comment)) return false; return true; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + comment.hashCode(); return result; } @Override public String toString() { return "SimpleCommentedConfigurationNode{" + "super=" + super.toString() + ", comment=" + comment + '}'; } }
Fix hashcode and equals impl for CommentedConfigurationNodes
configurate-core/src/main/java/ninja/leaping/configurate/commented/SimpleCommentedConfigurationNode.java
Fix hashcode and equals impl for CommentedConfigurationNodes
<ide><path>onfigurate-core/src/main/java/ninja/leaping/configurate/commented/SimpleCommentedConfigurationNode.java <ide> <ide> import java.util.List; <ide> import java.util.Map; <add>import java.util.Objects; <ide> import java.util.Optional; <del>import java.util.concurrent.atomic.AtomicReference; <ide> <ide> /** <ide> * Basic implementation of {@link CommentedConfigurationNode}. <ide> if (!super.equals(o)) return false; <ide> <ide> SimpleCommentedConfigurationNode that = (SimpleCommentedConfigurationNode) o; <del> if (!comment.equals(that.comment)) return false; <add> if (!Objects.equals(comment, that.comment)) return false; <ide> return true; <ide> } <ide> <ide> @Override <ide> public int hashCode() { <ide> int result = super.hashCode(); <del> result = 31 * result + comment.hashCode(); <add> result = 31 * result + Objects.hashCode(comment); <ide> return result; <ide> } <ide>
JavaScript
apache-2.0
8daeb65c961ef7730d0b25a71d3136b2684d0212
0
tessel/gprs-sim900
// Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ /********************************************* Use the GPRS module to send a text to a phone number of your choice. *********************************************/ var tessel = require('tessel'); var hardware = tessel.port['A']; var baud = 115200; // Typically keep this at 115200, but you can set it to 9600 if you're hitting buffer overflows var phoneNumber = '##########'; // Replace the #s with the String representation of 10+ digit number, including country code (1 for USA) var message = 'Text from a Tessel!'; // Port, baud (115200 by default), callback var gprs = require('../').use(hardware, baud); // Replace '../' with 'gprs-sim900' in your own code gprs.on('ready', function() { console.log('GPRS module connected to Tessel. Searching for network...') // Give it 10 more seconds to connect to the network, then try to send an SMS setTimeout(function() { console.log('Sending', message, 'to', phoneNumber, '...'); // Send message gprs.sendSMS(phoneNumber, message, function smsCallback(err, data) { if (err) { return console.log(err); } var success = data[0] !== -1; console.log('Text sent:', success); if (success) { // If successful, log the number of the sent text console.log('GPRS Module sent text #', data[0]); } }); }, 10000); }); // Emit unsolicited messages beginning with... gprs.emitMe(['NORMAL POWER DOWN', 'RING', '+']); gprs.on('NORMAL POWER DOWN', function powerDaemon () { gprs.emit('powered off'); console.log('The GPRS Module is off now.'); }); gprs.on('RING', function someoneCalledUs () { var instructions = 'Someone\'s calling!\nType the command \'ATA\' to answer and \'ATH\' to hang up.\nYou\'ll need a mic and headset connected to talk and hear.\nIf you want to call someone, type \'ATD"[their 10+digit number]"\'.'; console.log(instructions); }); gprs.on('+', function handlePlus (data) { console.log('Got an unsolicited message that begins with a \'+\'! Data:', data); }); // Command the GPRS module via the command line process.stdin.resume(); process.stdin.on('data', function (data) { data = String(data).replace(/[\r\n]*$/, ''); // Removes the line endings console.log('got command', [data]); gprs._txrx(data, 10000, function(err, data) { console.log('\nreply:\nerr:\t', err, '\ndata:'); data.forEach(function(d) { console.log('\t' + d); }); console.log(''); }); }); // Handle errors gprs.on('error', function (err) { console.log('Got an error of some kind:\n', err); });
examples/gprs.js
// Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ /********************************************* Use the GPRS module to send a text to a phone number of your choice. *********************************************/ var tessel = require('tessel'); var hardware = tessel.port['A']; var baud = 115200; // Typically keep this at 115200, but you can set it to 9600 if you're hitting buffer overflows var phoneNumber = '##########'; // Replace the #s with the String representation of 10+ digit number, including country code (1 for USA) var message = 'Text from a Tessel!'; // Port, baud (115200 by default), callback var gprs = require('../').use(hardware, baud); // Replace '../' with 'gprs-sim900' in your own code gprs.on('ready', function() { console.log('GPRS module connected to Tessel. Searching for network...') // Give it 10 more seconds to connect to the network, then try to send an SMS setTimeout(function() { console.log('Sending', message, 'to', phoneNumber, '...'); // Send message gprs.sendSMS(phoneNumber, message, function smsCallback(err, data) { if (err) { return console.log(err); } var success = data[0] !== -1; console.log('Text sent:', success); if (success) { // If successful, log the number of the sent text console.log('GPRS Module sent text #', data[0]); } }); }, 10000); }); // Emit unsolicited messages beginning with... gprs.emitMe(['NORMAL POWER DOWN', 'RING', '+']); gprs.on('NORMAL POWER DOWN', function powerDaemon () { gprs.emit('powered off'); console.log('The GPRS Module is off now.'); }); gprs.on('RING', function someoneCalledUs () { var instructions = 'Someone\'s calling!\nType the command \'ATA\' to answer and \'ATH\' to hang up.\nYou\'ll need a mic and headset connected to talk and hear.\nIf you want to call someone, type \'ATD"[their 10+digit number]"\'.'; console.log(instructions); }); gprs.on('+', function handlePlus (data) { console.log('Got an unsolicited message that begins with a \'+\'! Data:', data); }); // Command the GPRS module via the command line process.stdin.resume(); process.stdin.on('data', function (data) { data = String(data).replace(/[\r\n]*$/, ''); // Removes the line endings console.log('got command', [data]); gprs._txrx(data, 10000, function(err, data) { console.log('\nreply:\nerr:\t', err, '\ndata:'); data.forEach(function(d) { console.log('\t' + d); }); console.log(''); }); });
error handling added to example
examples/gprs.js
error handling added to example
<ide><path>xamples/gprs.js <ide> console.log(''); <ide> }); <ide> }); <add> <add>// Handle errors <add>gprs.on('error', function (err) { <add> console.log('Got an error of some kind:\n', err); <add>});
Java
apache-2.0
e6f0c3ee75a3c0933f041c38a50d6bf3a9d36f01
0
apache/skywalking,apache/skywalking,apache/skywalking,ascrutae/sky-walking,apache/skywalking,hanahmily/sky-walking,apache/skywalking,ascrutae/sky-walking,apache/skywalking,ascrutae/sky-walking,ascrutae/sky-walking,OpenSkywalking/skywalking,OpenSkywalking/skywalking,hanahmily/sky-walking,apache/skywalking
/* * 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.skywalking.apm.collector.ui.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.apache.skywalking.apm.collector.core.UnexpectedException; import org.apache.skywalking.apm.collector.core.util.Const; import org.apache.skywalking.apm.collector.storage.ui.common.Step; import org.apache.skywalking.apm.collector.storage.utils.DurationPoint; import org.joda.time.DateTime; import org.joda.time.Seconds; /** * @author peng-yongsheng */ public enum DurationUtils { INSTANCE; public long exchangeToTimeBucket(String dateStr) throws ParseException { dateStr = dateStr.replaceAll("-", Const.EMPTY_STRING); dateStr = dateStr.replaceAll(" ", Const.EMPTY_STRING); return Long.valueOf(dateStr); } public long durationToSecondTimeBucket(Step step, String dateStr) throws ParseException { long secondTimeBucket = 0; switch (step) { case MONTH: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 * 100 * 100 * 100; break; case DAY: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 * 100 * 100; break; case HOUR: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 * 100; break; case MINUTE: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100; break; case SECOND: secondTimeBucket = exchangeToTimeBucket(dateStr); break; } return secondTimeBucket; } public long secondsBetween(Step step, long start, long end) throws ParseException { Date startDate = null; Date endDate = null; switch (step) { case MONTH: startDate = new SimpleDateFormat("yyyyMM").parse(String.valueOf(start)); endDate = new SimpleDateFormat("yyyyMM").parse(String.valueOf(end)); break; case DAY: startDate = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(start)); endDate = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(end)); break; case HOUR: startDate = new SimpleDateFormat("yyyyMMddHH").parse(String.valueOf(start)); endDate = new SimpleDateFormat("yyyyMMddHH").parse(String.valueOf(end)); break; case MINUTE: startDate = new SimpleDateFormat("yyyyMMddHHmm").parse(String.valueOf(start)); endDate = new SimpleDateFormat("yyyyMMddHHmm").parse(String.valueOf(end)); break; case SECOND: startDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(String.valueOf(start)); endDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(String.valueOf(end)); break; } return Seconds.secondsBetween(new DateTime(startDate), new DateTime(endDate)).getSeconds(); } public long secondsBetween(Step step, DateTime dateTime) throws ParseException { switch (step) { case MONTH: return dateTime.dayOfMonth().getMaximumValue() * 24 * 60 * 60; case DAY: return 24 * 60 * 60; case HOUR: return 60 * 60; case MINUTE: return 60; case SECOND: return 1; default: return 1; } } public DateTime parseToDateTime(Step step, long time) throws ParseException { DateTime dateTime = null; switch (step) { case MONTH: Date date = new SimpleDateFormat("yyyyMM").parse(String.valueOf(time)); dateTime = new DateTime(date); break; case DAY: date = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(time)); dateTime = new DateTime(date); break; case HOUR: date = new SimpleDateFormat("yyyyMMddHH").parse(String.valueOf(time)); dateTime = new DateTime(date); break; case MINUTE: date = new SimpleDateFormat("yyyyMMddHHmm").parse(String.valueOf(time)); dateTime = new DateTime(date); break; case SECOND: date = new SimpleDateFormat("yyyyMMddHHmmss").parse(String.valueOf(time)); dateTime = new DateTime(date); break; } return dateTime; } public List<DurationPoint> getDurationPoints(Step step, long start, long end) throws ParseException { DateTime dateTime = parseToDateTime(step, start); List<DurationPoint> durations = new LinkedList<>(); durations.add(new DurationPoint(start, secondsBetween(step, dateTime))); int i = 0; do { switch (step) { case MONTH: dateTime = dateTime.plusMonths(1); String timeBucket = new SimpleDateFormat("yyyyMM").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; case DAY: dateTime = dateTime.plusDays(1); timeBucket = new SimpleDateFormat("yyyyMMdd").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; case HOUR: dateTime = dateTime.plusHours(1); timeBucket = new SimpleDateFormat("yyyyMMddHH").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; case MINUTE: dateTime = dateTime.plusMinutes(1); timeBucket = new SimpleDateFormat("yyyyMMddHHmm").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; case SECOND: dateTime = dateTime.plusSeconds(1); timeBucket = new SimpleDateFormat("yyyyMMddHHmmss").format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; } i++; if (i > 500) { throw new UnexpectedException("Duration data error, step: " + step.name() + ", start: " + start + ", end: " + end); } } while (end != durations.get(durations.size() - 1).getPoint()); return durations; } }
apm-collector/apm-collector-ui/collector-ui-jetty-provider/src/main/java/org/apache/skywalking/apm/collector/ui/utils/DurationUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.skywalking.apm.collector.ui.utils; import java.text.ParseException; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.apache.skywalking.apm.collector.core.UnexpectedException; import org.apache.skywalking.apm.collector.core.util.Const; import org.apache.skywalking.apm.collector.core.util.TimeBucketUtils; import org.apache.skywalking.apm.collector.storage.ui.common.Step; import org.apache.skywalking.apm.collector.storage.utils.DurationPoint; import org.joda.time.DateTime; import org.joda.time.Seconds; /** * @author peng-yongsheng */ public enum DurationUtils { INSTANCE; public long exchangeToTimeBucket(String dateStr) throws ParseException { dateStr = dateStr.replaceAll("-", Const.EMPTY_STRING); dateStr = dateStr.replaceAll(" ", Const.EMPTY_STRING); return Long.valueOf(dateStr); } public long durationToSecondTimeBucket(Step step, String dateStr) throws ParseException { long secondTimeBucket = 0; switch (step) { case MONTH: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 * 100 * 100 * 100; break; case DAY: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 * 100 * 100; break; case HOUR: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100 * 100; break; case MINUTE: secondTimeBucket = exchangeToTimeBucket(dateStr) * 100; break; case SECOND: secondTimeBucket = exchangeToTimeBucket(dateStr); break; } return secondTimeBucket; } public long secondsBetween(Step step, long start, long end) throws ParseException { Date startDate = null; Date endDate = null; switch (step) { case MONTH: startDate = TimeBucketUtils.MONTH_DATE_FORMAT.parse(String.valueOf(start)); endDate = TimeBucketUtils.MONTH_DATE_FORMAT.parse(String.valueOf(end)); break; case DAY: startDate = TimeBucketUtils.DAY_DATE_FORMAT.parse(String.valueOf(start)); endDate = TimeBucketUtils.DAY_DATE_FORMAT.parse(String.valueOf(end)); break; case HOUR: startDate = TimeBucketUtils.HOUR_DATE_FORMAT.parse(String.valueOf(start)); endDate = TimeBucketUtils.HOUR_DATE_FORMAT.parse(String.valueOf(end)); break; case MINUTE: startDate = TimeBucketUtils.MINUTE_DATE_FORMAT.parse(String.valueOf(start)); endDate = TimeBucketUtils.MINUTE_DATE_FORMAT.parse(String.valueOf(end)); break; case SECOND: startDate = TimeBucketUtils.SECOND_DATE_FORMAT.parse(String.valueOf(start)); endDate = TimeBucketUtils.SECOND_DATE_FORMAT.parse(String.valueOf(end)); break; } return Seconds.secondsBetween(new DateTime(startDate), new DateTime(endDate)).getSeconds(); } public long secondsBetween(Step step, DateTime dateTime) throws ParseException { switch (step) { case MONTH: return dateTime.dayOfMonth().getMaximumValue() * 24 * 60 * 60; case DAY: return 24 * 60 * 60; case HOUR: return 60 * 60; case MINUTE: return 60; case SECOND: return 1; default: return 1; } } public DateTime parseToDateTime(Step step, long time) throws ParseException { DateTime dateTime = null; switch (step) { case MONTH: Date date = TimeBucketUtils.MONTH_DATE_FORMAT.parse(String.valueOf(time)); dateTime = new DateTime(date); break; case DAY: date = TimeBucketUtils.DAY_DATE_FORMAT.parse(String.valueOf(time)); dateTime = new DateTime(date); break; case HOUR: date = TimeBucketUtils.HOUR_DATE_FORMAT.parse(String.valueOf(time)); dateTime = new DateTime(date); break; case MINUTE: date = TimeBucketUtils.MINUTE_DATE_FORMAT.parse(String.valueOf(time)); dateTime = new DateTime(date); break; case SECOND: date = TimeBucketUtils.SECOND_DATE_FORMAT.parse(String.valueOf(time)); dateTime = new DateTime(date); break; } return dateTime; } public List<DurationPoint> getDurationPoints(Step step, long start, long end) throws ParseException { DateTime dateTime = parseToDateTime(step, start); List<DurationPoint> durations = new LinkedList<>(); durations.add(new DurationPoint(start, secondsBetween(step, dateTime))); int i = 0; do { switch (step) { case MONTH: dateTime = dateTime.plusMonths(1); String timeBucket = TimeBucketUtils.MONTH_DATE_FORMAT.format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; case DAY: dateTime = dateTime.plusDays(1); timeBucket = TimeBucketUtils.DAY_DATE_FORMAT.format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; case HOUR: dateTime = dateTime.plusHours(1); timeBucket = TimeBucketUtils.HOUR_DATE_FORMAT.format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; case MINUTE: dateTime = dateTime.plusMinutes(1); timeBucket = TimeBucketUtils.MINUTE_DATE_FORMAT.format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; case SECOND: dateTime = dateTime.plusSeconds(1); timeBucket = TimeBucketUtils.SECOND_DATE_FORMAT.format(dateTime.toDate()); durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); break; } i++; if (i > 500) { throw new UnexpectedException("Duration data error, step: " + step.name() + ", start: " + start + ", end: " + end); } } while (end != durations.get(durations.size() - 1).getPoint()); return durations; } }
Fixed CI fail.
apm-collector/apm-collector-ui/collector-ui-jetty-provider/src/main/java/org/apache/skywalking/apm/collector/ui/utils/DurationUtils.java
Fixed CI fail.
<ide><path>pm-collector/apm-collector-ui/collector-ui-jetty-provider/src/main/java/org/apache/skywalking/apm/collector/ui/utils/DurationUtils.java <ide> package org.apache.skywalking.apm.collector.ui.utils; <ide> <ide> import java.text.ParseException; <add>import java.text.SimpleDateFormat; <ide> import java.util.Date; <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> import org.apache.skywalking.apm.collector.core.UnexpectedException; <ide> import org.apache.skywalking.apm.collector.core.util.Const; <del>import org.apache.skywalking.apm.collector.core.util.TimeBucketUtils; <ide> import org.apache.skywalking.apm.collector.storage.ui.common.Step; <ide> import org.apache.skywalking.apm.collector.storage.utils.DurationPoint; <ide> import org.joda.time.DateTime; <ide> Date endDate = null; <ide> switch (step) { <ide> case MONTH: <del> startDate = TimeBucketUtils.MONTH_DATE_FORMAT.parse(String.valueOf(start)); <del> endDate = TimeBucketUtils.MONTH_DATE_FORMAT.parse(String.valueOf(end)); <add> startDate = new SimpleDateFormat("yyyyMM").parse(String.valueOf(start)); <add> endDate = new SimpleDateFormat("yyyyMM").parse(String.valueOf(end)); <ide> break; <ide> case DAY: <del> startDate = TimeBucketUtils.DAY_DATE_FORMAT.parse(String.valueOf(start)); <del> endDate = TimeBucketUtils.DAY_DATE_FORMAT.parse(String.valueOf(end)); <add> startDate = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(start)); <add> endDate = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(end)); <ide> break; <ide> case HOUR: <del> startDate = TimeBucketUtils.HOUR_DATE_FORMAT.parse(String.valueOf(start)); <del> endDate = TimeBucketUtils.HOUR_DATE_FORMAT.parse(String.valueOf(end)); <add> startDate = new SimpleDateFormat("yyyyMMddHH").parse(String.valueOf(start)); <add> endDate = new SimpleDateFormat("yyyyMMddHH").parse(String.valueOf(end)); <ide> break; <ide> case MINUTE: <del> startDate = TimeBucketUtils.MINUTE_DATE_FORMAT.parse(String.valueOf(start)); <del> endDate = TimeBucketUtils.MINUTE_DATE_FORMAT.parse(String.valueOf(end)); <add> startDate = new SimpleDateFormat("yyyyMMddHHmm").parse(String.valueOf(start)); <add> endDate = new SimpleDateFormat("yyyyMMddHHmm").parse(String.valueOf(end)); <ide> break; <ide> case SECOND: <del> startDate = TimeBucketUtils.SECOND_DATE_FORMAT.parse(String.valueOf(start)); <del> endDate = TimeBucketUtils.SECOND_DATE_FORMAT.parse(String.valueOf(end)); <add> startDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(String.valueOf(start)); <add> endDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(String.valueOf(end)); <ide> break; <ide> } <ide> <ide> <ide> switch (step) { <ide> case MONTH: <del> Date date = TimeBucketUtils.MONTH_DATE_FORMAT.parse(String.valueOf(time)); <add> Date date = new SimpleDateFormat("yyyyMM").parse(String.valueOf(time)); <ide> dateTime = new DateTime(date); <ide> break; <ide> case DAY: <del> date = TimeBucketUtils.DAY_DATE_FORMAT.parse(String.valueOf(time)); <add> date = new SimpleDateFormat("yyyyMMdd").parse(String.valueOf(time)); <ide> dateTime = new DateTime(date); <ide> break; <ide> case HOUR: <del> date = TimeBucketUtils.HOUR_DATE_FORMAT.parse(String.valueOf(time)); <add> date = new SimpleDateFormat("yyyyMMddHH").parse(String.valueOf(time)); <ide> dateTime = new DateTime(date); <ide> break; <ide> case MINUTE: <del> date = TimeBucketUtils.MINUTE_DATE_FORMAT.parse(String.valueOf(time)); <add> date = new SimpleDateFormat("yyyyMMddHHmm").parse(String.valueOf(time)); <ide> dateTime = new DateTime(date); <ide> break; <ide> case SECOND: <del> date = TimeBucketUtils.SECOND_DATE_FORMAT.parse(String.valueOf(time)); <add> date = new SimpleDateFormat("yyyyMMddHHmmss").parse(String.valueOf(time)); <ide> dateTime = new DateTime(date); <ide> break; <ide> } <ide> switch (step) { <ide> case MONTH: <ide> dateTime = dateTime.plusMonths(1); <del> String timeBucket = TimeBucketUtils.MONTH_DATE_FORMAT.format(dateTime.toDate()); <add> String timeBucket = new SimpleDateFormat("yyyyMM").format(dateTime.toDate()); <ide> durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); <ide> break; <ide> case DAY: <ide> dateTime = dateTime.plusDays(1); <del> timeBucket = TimeBucketUtils.DAY_DATE_FORMAT.format(dateTime.toDate()); <add> timeBucket = new SimpleDateFormat("yyyyMMdd").format(dateTime.toDate()); <ide> durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); <ide> break; <ide> case HOUR: <ide> dateTime = dateTime.plusHours(1); <del> timeBucket = TimeBucketUtils.HOUR_DATE_FORMAT.format(dateTime.toDate()); <add> timeBucket = new SimpleDateFormat("yyyyMMddHH").format(dateTime.toDate()); <ide> durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); <ide> break; <ide> case MINUTE: <ide> dateTime = dateTime.plusMinutes(1); <del> timeBucket = TimeBucketUtils.MINUTE_DATE_FORMAT.format(dateTime.toDate()); <add> timeBucket = new SimpleDateFormat("yyyyMMddHHmm").format(dateTime.toDate()); <ide> durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); <ide> break; <ide> case SECOND: <ide> dateTime = dateTime.plusSeconds(1); <del> timeBucket = TimeBucketUtils.SECOND_DATE_FORMAT.format(dateTime.toDate()); <add> timeBucket = new SimpleDateFormat("yyyyMMddHHmmss").format(dateTime.toDate()); <ide> durations.add(new DurationPoint(Long.valueOf(timeBucket), secondsBetween(step, dateTime))); <ide> break; <ide> }
Java
agpl-3.0
820882e13a064129b838944f7d034e9477ec2346
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
e8c4b1ee-2e60-11e5-9284-b827eb9e62be
hello.java
e8bf06d6-2e60-11e5-9284-b827eb9e62be
e8c4b1ee-2e60-11e5-9284-b827eb9e62be
hello.java
e8c4b1ee-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>e8bf06d6-2e60-11e5-9284-b827eb9e62be <add>e8c4b1ee-2e60-11e5-9284-b827eb9e62be
Java
apache-2.0
b4d9458c7b1872b0a64dc381c9cd68b37810d011
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.jcef; import com.intellij.openapi.util.Disposer; import org.cef.CefClient; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; import org.cef.browser.CefMessageRouter; import org.cef.callback.CefQueryCallback; import org.cef.handler.CefMessageRouterHandler; import org.cef.handler.CefMessageRouterHandlerAdapter; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; /** * A JS query callback. * * @author tav */ @ApiStatus.Experimental public class JBCefJSQuery implements JBCefDisposable { @NotNull private final String myJSCallID; @NotNull private final CefMessageRouter myMsgRouter; @NotNull private final CefClient myCefClient; @NotNull private final DisposeHelper myDisposeHelper = new DisposeHelper(); @NotNull private final Map<Function<String, Response>, CefMessageRouterHandler> myHandlerMap = Collections.synchronizedMap(new HashMap<>()); @NotNull private static final AtomicInteger UNIQUE_ID_COUNTER = new AtomicInteger(0); private JBCefJSQuery(@NotNull JBCefBrowser browser, @NotNull String jsCallID) { myJSCallID = jsCallID; CefMessageRouter.CefMessageRouterConfig config = new CefMessageRouter.CefMessageRouterConfig(); config.jsQueryFunction = myJSCallID; config.jsCancelFunction = myJSCallID; myMsgRouter = CefMessageRouter.create(config); myCefClient = browser.getJBCefClient().getCefClient(); myCefClient.addMessageRouter(myMsgRouter); Disposer.register(browser, this); } /** * Creates a unique JS query * * @param browser the associated cef browser */ public static JBCefJSQuery create(@NotNull JBCefBrowser browser) { return new JBCefJSQuery(browser, "cefQuery_" + browser.hashCode() + "_" + UNIQUE_ID_COUNTER.incrementAndGet()); } /** * Returns the query callback to inject into JS code * * @param queryResult the result (JS variable name or JS value) that will be passed to the java handler {@link #addHandler(Function)} */ public String inject(@Nullable String queryResult) { return inject(queryResult, "function(response) {}", "function(error_code, error_message) {}"); } /** * Returns the query callback to inject into JS code * * @param queryResult the result (JS variable name or JS value) that will be passed to the java handler {@link #addHandler(Function)} * @param onSuccessCallback JS callback in format: function(response) {} * @param onFailureCallback JS callback in format: function(error_code, error_message) {} */ public String inject(@Nullable String queryResult, @NotNull String onSuccessCallback, @NotNull String onFailureCallback) { return "window." + myJSCallID + "({request: '' + " + queryResult + "," + "onSuccess: " + onSuccessCallback + "," + "onFailure: " + onFailureCallback + "});"; } public void addHandler(@NotNull Function<String, Response> handler) { CefMessageRouterHandler cefHandler; myMsgRouter.addHandler(cefHandler = new CefMessageRouterHandlerAdapter() { @Override public boolean onQuery(CefBrowser browser, CefFrame frame, long query_id, String request, boolean persistent, CefQueryCallback callback) { Response response = handler.apply(request); if (callback != null && response != null) { if (response.isSuccess() && response.hasResponse()) { callback.success(response.response()); } else { callback.failure(response.errCode(), response.errMsg()); } } return true; } }, true); myHandlerMap.put(handler, cefHandler); } public void removeHandler(@NotNull Function<String, Response> handler) { CefMessageRouterHandler cefHandler = myHandlerMap.remove(handler); if (cefHandler != null) { myMsgRouter.removeHandler(cefHandler); } } @Override public void dispose() { myDisposeHelper.dispose(() -> { myCefClient.removeMessageRouter(myMsgRouter); myHandlerMap.clear(); }); } @Override public boolean isDisposed() { return myDisposeHelper.isDisposed(); } /** * A JS handler response to a query. */ public static class Response { public static final int ERR_CODE_SUCCESS = 0; @Nullable private final String myResponse; private final int myErrCode; @Nullable private final String myErrMsg; public Response(@Nullable String response) { this(response, ERR_CODE_SUCCESS, null); } public Response(@Nullable String response, int errCode, @Nullable String errMsg) { myResponse = response; myErrCode = errCode; myErrMsg = errMsg; } @Nullable public String response() { return myResponse; } public int errCode() { return myErrCode; } @Nullable public String errMsg() { return myErrMsg; } public boolean isSuccess() { return myErrCode == ERR_CODE_SUCCESS; } public boolean hasResponse() { return myResponse != null; } } }
platform/platform-api/src/com/intellij/ui/jcef/JBCefJSQuery.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.jcef; import com.intellij.openapi.util.Disposer; import org.cef.CefClient; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; import org.cef.browser.CefMessageRouter; import org.cef.callback.CefQueryCallback; import org.cef.handler.CefMessageRouterHandler; import org.cef.handler.CefMessageRouterHandlerAdapter; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; /** * A JS query callback. * * @author tav */ @ApiStatus.Experimental public class JBCefJSQuery implements JBCefDisposable { @NotNull private final String myJSCallID; @NotNull private final CefMessageRouter myMsgRouter; @NotNull private final CefClient myCefClient; @NotNull private final DisposeHelper myDisposeHelper = new DisposeHelper(); @NotNull private final Map<Function<String, Response>, CefMessageRouterHandler> myHandlerMap = Collections.synchronizedMap(new HashMap<>()); @NotNull private static final AtomicInteger UNIQUE_ID_COUNTER = new AtomicInteger(0); private JBCefJSQuery(@NotNull JBCefBrowser browser, @NotNull String jsCallID) { myJSCallID = jsCallID; CefMessageRouter.CefMessageRouterConfig config = new CefMessageRouter.CefMessageRouterConfig(); config.jsQueryFunction = myJSCallID; config.jsCancelFunction = myJSCallID; myMsgRouter = CefMessageRouter.create(config); myCefClient = browser.getJBCefClient().getCefClient(); myCefClient.addMessageRouter(myMsgRouter); Disposer.register(browser, this); } /** * Creates a unique JS query * * @param browser the associated cef browser */ public static JBCefJSQuery create(@NotNull JBCefBrowser browser) { return new JBCefJSQuery(browser, "cefQuery_" + browser.hashCode() + "_" + UNIQUE_ID_COUNTER.incrementAndGet()); } /** * Returns the query callback call to inject into JS code * * @param queryResult the result that will be passed to the java handler {@link #addHandler(Function)} */ public String inject(@Nullable String queryResult) { return inject(queryResult, "function(response) {}", "function(error_code, error_message) {}"); } /** * Returns the query callback call to inject into JS code * * @param queryResult the result that weill be passed to the java handler {@link #addHandler(Function)} * @param onSuccessCallback JS callback in format: function(response) {} * @param onFailureCallback JS callback in format: function(error_code, error_message) {} */ public String inject(@Nullable String queryResult, @NotNull String onSuccessCallback, @NotNull String onFailureCallback) { return "window." + myJSCallID + "({request: '' + " + queryResult + "," + "onSuccess: " + onSuccessCallback + "," + "onFailure: " + onFailureCallback + "});"; } public void addHandler(@NotNull Function<String, Response> handler) { CefMessageRouterHandler cefHandler; myMsgRouter.addHandler(cefHandler = new CefMessageRouterHandlerAdapter() { @Override public boolean onQuery(CefBrowser browser, CefFrame frame, long query_id, String request, boolean persistent, CefQueryCallback callback) { Response response = handler.apply(request); if (callback != null && response != null) { if (response.isSuccess() && response.hasResponse()) { callback.success(response.response()); } else { callback.failure(response.errCode(), response.errMsg()); } } return true; } }, true); myHandlerMap.put(handler, cefHandler); } public void removeHandler(@NotNull Function<String, Response> handler) { CefMessageRouterHandler cefHandler = myHandlerMap.remove(handler); if (cefHandler != null) { myMsgRouter.removeHandler(cefHandler); } } @Override public void dispose() { myDisposeHelper.dispose(() -> { myCefClient.removeMessageRouter(myMsgRouter); myHandlerMap.clear(); }); } @Override public boolean isDisposed() { return myDisposeHelper.isDisposed(); } /** * A JS handler response to a query. */ public static class Response { public static final int ERR_CODE_SUCCESS = 0; @Nullable private final String myResponse; private final int myErrCode; @Nullable private final String myErrMsg; public Response(@Nullable String response) { this(response, ERR_CODE_SUCCESS, null); } public Response(@Nullable String response, int errCode, @Nullable String errMsg) { myResponse = response; myErrCode = errCode; myErrMsg = errMsg; } @Nullable public String response() { return myResponse; } public int errCode() { return myErrCode; } @Nullable public String errMsg() { return myErrMsg; } public boolean isSuccess() { return myErrCode == ERR_CODE_SUCCESS; } public boolean hasResponse() { return myResponse != null; } } }
Correct javadoc for JBCefJSQuery.inject GitOrigin-RevId: 1be75c594e602f62a40a43b408caa2f7db3aded9
platform/platform-api/src/com/intellij/ui/jcef/JBCefJSQuery.java
Correct javadoc for JBCefJSQuery.inject
<ide><path>latform/platform-api/src/com/intellij/ui/jcef/JBCefJSQuery.java <ide> } <ide> <ide> /** <del> * Returns the query callback call to inject into JS code <add> * Returns the query callback to inject into JS code <ide> * <del> * @param queryResult the result that will be passed to the java handler {@link #addHandler(Function)} <add> * @param queryResult the result (JS variable name or JS value) that will be passed to the java handler {@link #addHandler(Function)} <ide> */ <ide> public String inject(@Nullable String queryResult) { <ide> return inject(queryResult, "function(response) {}", "function(error_code, error_message) {}"); <ide> } <ide> <ide> /** <del> * Returns the query callback call to inject into JS code <add> * Returns the query callback to inject into JS code <ide> * <del> * @param queryResult the result that weill be passed to the java handler {@link #addHandler(Function)} <add> * @param queryResult the result (JS variable name or JS value) that will be passed to the java handler {@link #addHandler(Function)} <ide> * @param onSuccessCallback JS callback in format: function(response) {} <ide> * @param onFailureCallback JS callback in format: function(error_code, error_message) {} <ide> */
Java
apache-2.0
1995039fb99648e2b695878ea137b898b7b0f328
0
KurtYoung/druid,smartpcr/druid,druid-io/druid,cocosli/druid,zhihuij/druid,druid-io/druid,lizhanhui/data_druid,praveev/druid,milimetric/druid,kevintvh/druid,knoguchi/druid,leventov/druid,du00cs/druid,minewhat/druid,zhaown/druid,taochaoqiang/druid,se7entyse7en/druid,Deebs21/druid,deltaprojects/druid,Fokko/druid,monetate/druid,anupkumardixit/druid,dkhwangbo/druid,dclim/druid,skyportsystems/druid,lcp0578/druid,lcp0578/druid,b-slim/druid,zhaown/druid,zhiqinghuang/druid,mghosh4/druid,implydata/druid,fjy/druid,optimizely/druid,mrijke/druid,Kleagleguo/druid,zhihuij/druid,optimizely/druid,friedhardware/druid,authbox-lib/druid,solimant/druid,b-slim/druid,erikdubbelboer/druid,nishantmonu51/druid,OttoOps/druid,yaochitc/druid-dev,zengzhihai110/druid,deltaprojects/druid,eshen1991/druid,dclim/druid,mghosh4/druid,michaelschiff/druid,elijah513/druid,rasahner/druid,zxs/druid,Deebs21/druid,fjy/druid,zhiqinghuang/druid,erikdubbelboer/druid,qix/druid,liquidm/druid,penuel-leo/druid,mrijke/druid,wenjixin/druid,redBorder/druid,pdeva/druid,redBorder/druid,se7entyse7en/druid,penuel-leo/druid,kevintvh/druid,dclim/druid,milimetric/druid,zhiqinghuang/druid,mrijke/druid,premc/druid,winval/druid,pombredanne/druid,michaelschiff/druid,implydata/druid,se7entyse7en/druid,yaochitc/druid-dev,gianm/druid,skyportsystems/druid,mangeshpardeshiyahoo/druid,deltaprojects/druid,yaochitc/druid-dev,pjain1/druid,nishantmonu51/druid,michaelschiff/druid,qix/druid,premc/druid,potto007/druid-avro,OttoOps/druid,himanshug/druid,dclim/druid,pdeva/druid,calliope7/druid,solimant/druid,liquidm/druid,potto007/druid-avro,guobingkun/druid,eshen1991/druid,penuel-leo/druid,erikdubbelboer/druid,premc/druid,himanshug/druid,eshen1991/druid,guobingkun/druid,friedhardware/druid,pjain1/druid,jon-wei/druid,deltaprojects/druid,amikey/druid,metamx/druid,zxs/druid,jon-wei/druid,optimizely/druid,knoguchi/druid,zhihuij/druid,fjy/druid,nvoron23/druid,cocosli/druid,leventov/druid,du00cs/druid,zxs/druid,leventov/druid,gianm/druid,praveev/druid,wenjixin/druid,erikdubbelboer/druid,knoguchi/druid,andy256/druid,authbox-lib/druid,gianm/druid,amikey/druid,jon-wei/druid,zengzhihai110/druid,yaochitc/druid-dev,penuel-leo/druid,wenjixin/druid,qix/druid,zhihuij/druid,calliope7/druid,minewhat/druid,noddi/druid,anupkumardixit/druid,praveev/druid,OttoOps/druid,mangeshpardeshiyahoo/druid,mghosh4/druid,smartpcr/druid,implydata/druid,calliope7/druid,optimizely/druid,noddi/druid,leventov/druid,eshen1991/druid,nvoron23/druid,cocosli/druid,implydata/druid,mghosh4/druid,authbox-lib/druid,Deebs21/druid,taochaoqiang/druid,winval/druid,dkhwangbo/druid,dkhwangbo/druid,Fokko/druid,nishantmonu51/druid,KurtYoung/druid,nvoron23/druid,metamx/druid,taochaoqiang/druid,amikey/druid,nishantmonu51/druid,b-slim/druid,winval/druid,qix/druid,lizhanhui/data_druid,mangeshpardeshiyahoo/druid,pjain1/druid,michaelschiff/druid,friedhardware/druid,OttoOps/druid,rasahner/druid,zengzhihai110/druid,anupkumardixit/druid,noddi/druid,gianm/druid,skyportsystems/druid,andy256/druid,se7entyse7en/druid,eshen1991/druid,767326791/druid,monetate/druid,dkhwangbo/druid,deltaprojects/druid,wenjixin/druid,du00cs/druid,Deebs21/druid,Fokko/druid,authbox-lib/druid,767326791/druid,zxs/druid,amikey/druid,liquidm/druid,pjain1/druid,amikey/druid,mrijke/druid,lizhanhui/data_druid,tubemogul/druid,fjy/druid,leventov/druid,praveev/druid,milimetric/druid,yaochitc/druid-dev,anupkumardixit/druid,767326791/druid,KurtYoung/druid,redBorder/druid,Fokko/druid,friedhardware/druid,zhaown/druid,liquidm/druid,Deebs21/druid,milimetric/druid,Kleagleguo/druid,lcp0578/druid,tubemogul/druid,monetate/druid,pdeva/druid,liquidm/druid,liquidm/druid,authbox-lib/druid,deltaprojects/druid,nishantmonu51/druid,jon-wei/druid,monetate/druid,taochaoqiang/druid,elijah513/druid,elijah513/druid,Fokko/druid,tubemogul/druid,deltaprojects/druid,fjy/druid,lizhanhui/data_druid,pombredanne/druid,druid-io/druid,Fokko/druid,KurtYoung/druid,kevintvh/druid,lcp0578/druid,OttoOps/druid,jon-wei/druid,solimant/druid,Kleagleguo/druid,767326791/druid,himanshug/druid,gianm/druid,friedhardware/druid,smartpcr/druid,jon-wei/druid,himanshug/druid,skyportsystems/druid,knoguchi/druid,haoch/druid,taochaoqiang/druid,mrijke/druid,wenjixin/druid,druid-io/druid,pombredanne/druid,redBorder/druid,premc/druid,guobingkun/druid,nishantmonu51/druid,pjain1/druid,potto007/druid-avro,mghosh4/druid,zhaown/druid,gianm/druid,elijah513/druid,haoch/druid,minewhat/druid,zengzhihai110/druid,himanshug/druid,rasahner/druid,dkhwangbo/druid,Kleagleguo/druid,KurtYoung/druid,andy256/druid,minewhat/druid,b-slim/druid,rasahner/druid,monetate/druid,tubemogul/druid,zhiqinghuang/druid,qix/druid,pombredanne/druid,erikdubbelboer/druid,optimizely/druid,calliope7/druid,kevintvh/druid,minewhat/druid,du00cs/druid,mghosh4/druid,pdeva/druid,guobingkun/druid,zhihuij/druid,Kleagleguo/druid,solimant/druid,anupkumardixit/druid,implydata/druid,milimetric/druid,767326791/druid,dclim/druid,nishantmonu51/druid,lizhanhui/data_druid,mangeshpardeshiyahoo/druid,lcp0578/druid,skyportsystems/druid,guobingkun/druid,rasahner/druid,haoch/druid,se7entyse7en/druid,zhiqinghuang/druid,premc/druid,noddi/druid,b-slim/druid,potto007/druid-avro,metamx/druid,potto007/druid-avro,mangeshpardeshiyahoo/druid,michaelschiff/druid,redBorder/druid,zengzhihai110/druid,tubemogul/druid,penuel-leo/druid,michaelschiff/druid,cocosli/druid,pjain1/druid,implydata/druid,pjain1/druid,pombredanne/druid,cocosli/druid,smartpcr/druid,haoch/druid,andy256/druid,zhaown/druid,pdeva/druid,Fokko/druid,metamx/druid,winval/druid,noddi/druid,michaelschiff/druid,praveev/druid,nvoron23/druid,calliope7/druid,du00cs/druid,winval/druid,jon-wei/druid,gianm/druid,monetate/druid,solimant/druid,zxs/druid,mghosh4/druid,monetate/druid,nvoron23/druid,elijah513/druid,andy256/druid,metamx/druid,haoch/druid,kevintvh/druid,knoguchi/druid,druid-io/druid,smartpcr/druid
/* * Druid - a distributed column store. * Copyright (C) 2012 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 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 com.metamx.druid.merger.coordinator; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.MinMaxPriorityQueue; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import com.metamx.common.ISE; import com.metamx.common.guava.FunctionalIterable; import com.metamx.common.lifecycle.LifecycleStart; import com.metamx.common.lifecycle.LifecycleStop; import com.metamx.druid.merger.common.TaskCallback; import com.metamx.druid.merger.common.TaskStatus; import com.metamx.druid.merger.common.task.Task; import com.metamx.druid.merger.coordinator.config.RemoteTaskRunnerConfig; import com.metamx.druid.merger.coordinator.setup.WorkerSetupManager; import com.metamx.druid.merger.worker.Worker; import com.metamx.emitter.EmittingLogger; import com.netflix.curator.framework.CuratorFramework; import com.netflix.curator.framework.recipes.cache.PathChildrenCache; import com.netflix.curator.framework.recipes.cache.PathChildrenCacheEvent; import com.netflix.curator.framework.recipes.cache.PathChildrenCacheListener; import com.netflix.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; import org.joda.time.DateTime; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * The RemoteTaskRunner's primary responsibility is to assign tasks to worker nodes and manage retries in failure * scenarios. The RemoteTaskRunner keeps track of which workers are running which tasks and manages coordinator and * worker interactions over Zookeeper. The RemoteTaskRunner is event driven and updates state according to ephemeral * node changes in ZK. * <p/> * The RemoteTaskRunner will assign tasks to a node until the node hits capacity. At that point, task assignment will * fail. The RemoteTaskRunner depends on another component to create additional worker resources. * For example, {@link com.metamx.druid.merger.coordinator.scaling.ResourceManagementScheduler} can take care of these duties. * <p/> * If a worker node becomes inexplicably disconnected from Zk, the RemoteTaskRunner will automatically retry any tasks * that were associated with the node. */ public class RemoteTaskRunner implements TaskRunner { private static final EmittingLogger log = new EmittingLogger(RemoteTaskRunner.class); private static final Joiner JOINER = Joiner.on("/"); private final ObjectMapper jsonMapper; private final RemoteTaskRunnerConfig config; private final CuratorFramework cf; private final PathChildrenCache workerPathCache; private final ScheduledExecutorService scheduledExec; private final RetryPolicyFactory retryPolicyFactory; private final WorkerSetupManager workerSetupManager; // all workers that exist in ZK private final Map<String, ZkWorker> zkWorkers = new ConcurrentHashMap<String, ZkWorker>(); // all tasks that have been assigned to a worker private final TaskRunnerWorkQueue runningTasks = new TaskRunnerWorkQueue(); // tasks that have not yet run private final TaskRunnerWorkQueue pendingTasks = new TaskRunnerWorkQueue(); private final ExecutorService runPendingTasksExec = Executors.newSingleThreadExecutor(); private final Object statusLock = new Object(); private volatile boolean started = false; public RemoteTaskRunner( ObjectMapper jsonMapper, RemoteTaskRunnerConfig config, CuratorFramework cf, PathChildrenCache workerPathCache, ScheduledExecutorService scheduledExec, RetryPolicyFactory retryPolicyFactory, WorkerSetupManager workerSetupManager ) { this.jsonMapper = jsonMapper; this.config = config; this.cf = cf; this.workerPathCache = workerPathCache; this.scheduledExec = scheduledExec; this.retryPolicyFactory = retryPolicyFactory; this.workerSetupManager = workerSetupManager; } @LifecycleStart public void start() { try { if (started) { return; } // Add listener for creation/deletion of workers workerPathCache.getListenable().addListener( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, final PathChildrenCacheEvent event) throws Exception { if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)) { final Worker worker = jsonMapper.readValue( event.getData().getData(), Worker.class ); log.info("New worker[%s] found!", worker.getHost()); addWorker(worker); } else if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)) { final Worker worker = jsonMapper.readValue( event.getData().getData(), Worker.class ); log.info("Worker[%s] removed!", worker.getHost()); removeWorker(worker); } } } ); workerPathCache.start(); started = true; } catch (Exception e) { throw Throwables.propagate(e); } } @LifecycleStop public void stop() { try { if (!started) { return; } for (ZkWorker zkWorker : zkWorkers.values()) { zkWorker.close(); } } catch (Exception e) { throw Throwables.propagate(e); } finally { started = false; } } @Override public Collection<ZkWorker> getWorkers() { return zkWorkers.values(); } @Override public Collection<TaskRunnerWorkItem> getRunningTasks() { return runningTasks.values(); } @Override public Collection<TaskRunnerWorkItem> getPendingTasks() { return pendingTasks.values(); } public ZkWorker findWorkerRunningTask(String taskId) { for (ZkWorker zkWorker : zkWorkers.values()) { if (zkWorker.getRunningTasks().contains(taskId)) { return zkWorker; } } return null; } /** * A task will be run only if there is no current knowledge in the RemoteTaskRunner of the task. * * @param task task to run * @param callback callback to be called exactly once */ @Override public void run(Task task, TaskCallback callback) { if (runningTasks.containsKey(task.getId()) || pendingTasks.containsKey(task.getId())) { throw new ISE("Assigned a task[%s] that is already running or pending, WTF is happening?!", task.getId()); } TaskRunnerWorkItem taskRunnerWorkItem = new TaskRunnerWorkItem( task, callback, retryPolicyFactory.makeRetryPolicy(), new DateTime() ); addPendingTask(taskRunnerWorkItem); } private void addPendingTask(final TaskRunnerWorkItem taskRunnerWorkItem) { log.info("Added pending task %s", taskRunnerWorkItem.getTask().getId()); pendingTasks.put(taskRunnerWorkItem.getTask().getId(), taskRunnerWorkItem); runPendingTasks(); } /** * This method uses a single threaded executor to extract all pending tasks and attempt to run them. Any tasks that * are successfully assigned to a worker will be moved from pendingTasks to runningTasks. This method is thread-safe. * This method should be run each time there is new worker capacity or if new tasks are assigned. */ private void runPendingTasks() { runPendingTasksExec.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { // make a copy of the pending tasks because assignTask may delete tasks from pending and move them // into running status List<TaskRunnerWorkItem> copy = Lists.newArrayList(pendingTasks.values()); for (TaskRunnerWorkItem taskWrapper : copy) { assignTask(taskWrapper); } } catch (Exception e) { log.makeAlert(e, "Exception in running pending tasks").emit(); } return null; } } ); } /** * Retries a task by inserting it back into the pending queue after a given delay. * This method will also clean up any status paths that were associated with the task. * * @param taskRunnerWorkItem - the task to retry * @param workerId - the worker that was previously running this task */ private void retryTask(final TaskRunnerWorkItem taskRunnerWorkItem, final String workerId) { final String taskId = taskRunnerWorkItem.getTask().getId(); log.info("Retry scheduled in %s for %s", taskRunnerWorkItem.getRetryPolicy().getRetryDelay(), taskId); scheduledExec.schedule( new Runnable() { @Override public void run() { cleanup(workerId, taskId); addPendingTask(taskRunnerWorkItem); } }, taskRunnerWorkItem.getRetryPolicy().getAndIncrementRetryDelay().getMillis(), TimeUnit.MILLISECONDS ); } /** * Removes a task from the running queue and clears out the ZK status path of the task. * * @param workerId - the worker that was previously running the task * @param taskId - the task to cleanup */ private void cleanup(final String workerId, final String taskId) { runningTasks.remove(taskId); final String statusPath = JOINER.join(config.getStatusPath(), workerId, taskId); try { cf.delete().guaranteed().forPath(statusPath); } catch (Exception e) { log.info("Tried to delete status path[%s] that didn't exist! Must've gone away already?", statusPath); } } /** * Ensures no workers are already running a task before assigning the task to a worker. * It is possible that a worker is running a task that the RTR has no knowledge of. This occurs when the RTR * needs to bootstrap after a restart. * * @param taskRunnerWorkItem - the task to assign */ private void assignTask(TaskRunnerWorkItem taskRunnerWorkItem) { try { final String taskId = taskRunnerWorkItem.getTask().getId(); ZkWorker zkWorker = findWorkerRunningTask(taskId); // If a worker is already running this task, we don't need to announce it if (zkWorker != null) { final Worker worker = zkWorker.getWorker(); log.info("Worker[%s] is already running task[%s].", worker.getHost(), taskId); runningTasks.put(taskId, pendingTasks.remove(taskId)); log.info("Task %s switched from pending to running", taskId); } else { // Nothing running this task, announce it in ZK for a worker to run it zkWorker = findWorkerForTask(); if (zkWorker != null) { announceTask(zkWorker.getWorker(), taskRunnerWorkItem); } } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Creates a ZK entry under a specific path associated with a worker. The worker is responsible for * removing the task ZK entry and creating a task status ZK entry. * * @param theWorker The worker the task is assigned to * @param taskRunnerWorkItem The task to be assigned */ private void announceTask(Worker theWorker, TaskRunnerWorkItem taskRunnerWorkItem) throws Exception { final Task task = taskRunnerWorkItem.getTask(); log.info("Coordinator asking Worker[%s] to add task[%s]", theWorker.getHost(), task.getId()); byte[] rawBytes = jsonMapper.writeValueAsBytes(task); if (rawBytes.length > config.getMaxNumBytes()) { throw new ISE("Length of raw bytes for task too large[%,d > %,d]", rawBytes.length, config.getMaxNumBytes()); } cf.create() .withMode(CreateMode.EPHEMERAL) .forPath( JOINER.join( config.getTaskPath(), theWorker.getHost(), task.getId() ), rawBytes ); runningTasks.put(task.getId(), pendingTasks.remove(task.getId())); log.info("Task %s switched from pending to running", task.getId()); // Syncing state with Zookeeper - don't assign new tasks until the task we just assigned is actually running // on a worker - this avoids overflowing a worker with tasks synchronized (statusLock) { while (findWorkerRunningTask(task.getId()) == null) { statusLock.wait(config.getTaskAssignmentTimeoutDuration().getMillis()); } } } /** * When a new worker appears, listeners are registered for status changes associated with tasks assigned to * the worker. Status changes indicate the creation or completion of a task. * The RemoteTaskRunner updates state according to these changes. * * @param worker - contains metadata for a worker that has appeared in ZK */ private void addWorker(final Worker worker) { try { final String workerStatusPath = JOINER.join(config.getStatusPath(), worker.getHost()); final PathChildrenCache statusCache = new PathChildrenCache(cf, workerStatusPath, true); final ZkWorker zkWorker = new ZkWorker( worker, statusCache, jsonMapper ); // Add status listener to the watcher for status changes statusCache.getListenable().addListener( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { log.info("Event: %s", event.getType()); if (event.getData() != null) { log.info("Data: %s", event.getData().getPath()); } try { if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)) { final String taskId = ZKPaths.getNodeFromPath(event.getData().getPath()); final TaskStatus taskStatus; // This can fail if a worker writes a bogus status. Retry if so. try { taskStatus = jsonMapper.readValue( event.getData().getData(), TaskStatus.class ); if (!taskStatus.getId().equals(taskId)) { // Sanity check throw new ISE( "Worker[%s] status id does not match payload id: %s != %s", worker.getHost(), taskId, taskStatus.getId() ); } } catch (Exception e) { log.warn(e, "Worker[%s] wrote bogus status for task: %s", worker.getHost(), taskId); retryTask(runningTasks.get(taskId), worker.getHost()); throw Throwables.propagate(e); } log.info( "Worker[%s] wrote %s status for task: %s", worker.getHost(), taskStatus.getStatusCode(), taskId ); // Synchronizing state with ZK synchronized (statusLock) { statusLock.notify(); } final TaskRunnerWorkItem taskRunnerWorkItem = runningTasks.get(taskId); if (taskRunnerWorkItem == null) { log.warn( "WTF?! Worker[%s] announcing a status for a task I didn't know about: %s", worker.getHost(), taskId ); } if (taskStatus.isComplete()) { if (taskRunnerWorkItem != null) { final TaskCallback callback = taskRunnerWorkItem.getCallback(); if (callback != null) { callback.notify(taskStatus); } } // Worker is done with this task zkWorker.setLastCompletedTaskTime(new DateTime()); cleanup(worker.getHost(), taskId); runPendingTasks(); } } else if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)) { final String taskId = ZKPaths.getNodeFromPath(event.getData().getPath()); if (runningTasks.containsKey(taskId)) { log.info("Task %s just disappeared!", taskId); retryTask(runningTasks.get(taskId), worker.getHost()); } else { log.info("Lost a task I didn't know about: %s", taskId); } } } catch (Exception e) { log.makeAlert(e, "Failed to handle new worker status") .addData("worker", worker.getHost()) .addData("znode", event.getData().getPath()) .emit(); } } } ); zkWorkers.put(worker.getHost(), zkWorker); statusCache.start(); runPendingTasks(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * When a ephemeral worker node disappears from ZK, incomplete running tasks will be retried by * the logic in the status listener. We still have to make sure there are no tasks assigned * to the worker but not yet running. * * @param worker - the removed worker */ private void removeWorker(final Worker worker) { ZkWorker zkWorker = zkWorkers.get(worker.getHost()); if (zkWorker != null) { try { Set<String> tasksPending = Sets.newHashSet( cf.getChildren() .forPath(JOINER.join(config.getTaskPath(), worker.getHost())) ); log.info("%s had %d tasks pending", worker.getHost(), tasksPending.size()); for (String taskId : tasksPending) { TaskRunnerWorkItem taskRunnerWorkItem = pendingTasks.get(taskId); if (taskRunnerWorkItem != null) { cf.delete().guaranteed().forPath(JOINER.join(config.getTaskPath(), worker.getHost(), taskId)); retryTask(taskRunnerWorkItem, worker.getHost()); } else { log.warn("RemoteTaskRunner has no knowledge of pending task %s", taskId); } } zkWorker.getStatusCache().close(); } catch (Exception e) { throw Throwables.propagate(e); } finally { zkWorkers.remove(worker.getHost()); } } } private ZkWorker findWorkerForTask() { try { final MinMaxPriorityQueue<ZkWorker> workerQueue = MinMaxPriorityQueue.<ZkWorker>orderedBy( new Comparator<ZkWorker>() { @Override public int compare(ZkWorker w1, ZkWorker w2) { return -Ints.compare(w1.getRunningTasks().size(), w2.getRunningTasks().size()); } } ).create( FunctionalIterable.create(zkWorkers.values()).filter( new Predicate<ZkWorker>() { @Override public boolean apply(ZkWorker input) { return (!input.isAtCapacity() && input.getWorker() .getVersion() .compareTo(workerSetupManager.getWorkerSetupData().getMinVersion()) >= 0); } } ) ); if (workerQueue.isEmpty()) { log.info("Worker nodes %s do not have capacity to run any more tasks!", zkWorkers.values()); return null; } return workerQueue.peek(); } catch (Exception e) { throw Throwables.propagate(e); } } }
merger/src/main/java/com/metamx/druid/merger/coordinator/RemoteTaskRunner.java
/* * Druid - a distributed column store. * Copyright (C) 2012 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 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 com.metamx.druid.merger.coordinator; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.MinMaxPriorityQueue; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import com.metamx.common.ISE; import com.metamx.common.guava.FunctionalIterable; import com.metamx.common.lifecycle.LifecycleStart; import com.metamx.common.lifecycle.LifecycleStop; import com.metamx.druid.merger.common.TaskCallback; import com.metamx.druid.merger.common.TaskStatus; import com.metamx.druid.merger.common.task.Task; import com.metamx.druid.merger.coordinator.config.RemoteTaskRunnerConfig; import com.metamx.druid.merger.coordinator.setup.WorkerSetupManager; import com.metamx.druid.merger.worker.Worker; import com.metamx.emitter.EmittingLogger; import com.netflix.curator.framework.CuratorFramework; import com.netflix.curator.framework.recipes.cache.PathChildrenCache; import com.netflix.curator.framework.recipes.cache.PathChildrenCacheEvent; import com.netflix.curator.framework.recipes.cache.PathChildrenCacheListener; import com.netflix.curator.utils.ZKPaths; import org.apache.zookeeper.CreateMode; import org.joda.time.DateTime; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * The RemoteTaskRunner's primary responsibility is to assign tasks to worker nodes and manage retries in failure * scenarios. The RemoteTaskRunner keeps track of which workers are running which tasks and manages coordinator and * worker interactions over Zookeeper. The RemoteTaskRunner is event driven and updates state according to ephemeral * node changes in ZK. * <p/> * The RemoteTaskRunner will assign tasks to a node until the node hits capacity. At that point, task assignment will * fail. The RemoteTaskRunner depends on another component to create additional worker resources. * For example, {@link com.metamx.druid.merger.coordinator.scaling.ResourceManagementScheduler} can take care of these duties. * <p/> * If a worker node becomes inexplicably disconnected from Zk, the RemoteTaskRunner will automatically retry any tasks * that were associated with the node. */ public class RemoteTaskRunner implements TaskRunner { private static final EmittingLogger log = new EmittingLogger(RemoteTaskRunner.class); private static final Joiner JOINER = Joiner.on("/"); private final ObjectMapper jsonMapper; private final RemoteTaskRunnerConfig config; private final CuratorFramework cf; private final PathChildrenCache workerPathCache; private final ScheduledExecutorService scheduledExec; private final RetryPolicyFactory retryPolicyFactory; private final WorkerSetupManager workerSetupManager; // all workers that exist in ZK private final Map<String, ZkWorker> zkWorkers = new ConcurrentHashMap<String, ZkWorker>(); // all tasks that have been assigned to a worker private final TaskRunnerWorkQueue runningTasks = new TaskRunnerWorkQueue(); // tasks that have not yet run private final TaskRunnerWorkQueue pendingTasks = new TaskRunnerWorkQueue(); private final ExecutorService runPendingTasksExec = Executors.newSingleThreadExecutor(); private final Object statusLock = new Object(); private volatile boolean started = false; public RemoteTaskRunner( ObjectMapper jsonMapper, RemoteTaskRunnerConfig config, CuratorFramework cf, PathChildrenCache workerPathCache, ScheduledExecutorService scheduledExec, RetryPolicyFactory retryPolicyFactory, WorkerSetupManager workerSetupManager ) { this.jsonMapper = jsonMapper; this.config = config; this.cf = cf; this.workerPathCache = workerPathCache; this.scheduledExec = scheduledExec; this.retryPolicyFactory = retryPolicyFactory; this.workerSetupManager = workerSetupManager; } @LifecycleStart public void start() { try { if (started) { return; } // Add listener for creation/deletion of workers workerPathCache.getListenable().addListener( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, final PathChildrenCacheEvent event) throws Exception { if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)) { final Worker worker = jsonMapper.readValue( event.getData().getData(), Worker.class ); log.info("New worker[%s] found!", worker.getHost()); addWorker(worker); } else if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)) { final Worker worker = jsonMapper.readValue( event.getData().getData(), Worker.class ); log.info("Worker[%s] removed!", worker.getHost()); removeWorker(worker); } } } ); workerPathCache.start(); started = true; } catch (Exception e) { throw Throwables.propagate(e); } } @LifecycleStop public void stop() { try { if (!started) { return; } for (ZkWorker zkWorker : zkWorkers.values()) { zkWorker.close(); } } catch (Exception e) { throw Throwables.propagate(e); } finally { started = false; } } @Override public Collection<ZkWorker> getWorkers() { return zkWorkers.values(); } @Override public Collection<TaskRunnerWorkItem> getRunningTasks() { return runningTasks.values(); } @Override public Collection<TaskRunnerWorkItem> getPendingTasks() { return pendingTasks.values(); } public ZkWorker findWorkerRunningTask(String taskId) { for (ZkWorker zkWorker : zkWorkers.values()) { if (zkWorker.getRunningTasks().contains(taskId)) { return zkWorker; } } return null; } /** * A task will be run only if there is no current knowledge in the RemoteTaskRunner of the task. * * @param task task to run * @param callback callback to be called exactly once */ @Override public void run(Task task, TaskCallback callback) { if (runningTasks.containsKey(task.getId()) || pendingTasks.containsKey(task.getId())) { throw new ISE("Assigned a task[%s] that is already running or pending, WTF is happening?!", task.getId()); } TaskRunnerWorkItem taskRunnerWorkItem = new TaskRunnerWorkItem( task, callback, retryPolicyFactory.makeRetryPolicy(), new DateTime() ); addPendingTask(taskRunnerWorkItem); } private void addPendingTask(final TaskRunnerWorkItem taskRunnerWorkItem) { log.info("Added pending task %s", taskRunnerWorkItem.getTask().getId()); pendingTasks.put(taskRunnerWorkItem.getTask().getId(), taskRunnerWorkItem); runPendingTasks(); } /** * This method uses a single threaded executor to extract all pending tasks and attempt to run them. Any tasks that * are successfully assigned to a worker will be moved from pendingTasks to runningTasks. This method is thread-safe. * This method should be run each time there is new worker capacity or if new tasks are assigned. */ private void runPendingTasks() { runPendingTasksExec.submit( new Callable<Void>() { @Override public Void call() throws Exception { try { // make a copy of the pending tasks because assignTask may delete tasks from pending and move them // into running status List<TaskRunnerWorkItem> copy = Lists.newArrayList(pendingTasks.values()); for (TaskRunnerWorkItem taskWrapper : copy) { assignTask(taskWrapper); } } catch (Exception e) { log.makeAlert(e, "Exception in running pending tasks").emit(); } return null; } } ); } /** * Retries a task by inserting it back into the pending queue after a given delay. * This method will also clean up any status paths that were associated with the task. * * @param taskRunnerWorkItem - the task to retry * @param workerId - the worker that was previously running this task */ private void retryTask(final TaskRunnerWorkItem taskRunnerWorkItem, final String workerId) { final String taskId = taskRunnerWorkItem.getTask().getId(); log.info("Retry scheduled in %s for %s", taskRunnerWorkItem.getRetryPolicy().getRetryDelay(), taskId); scheduledExec.schedule( new Runnable() { @Override public void run() { cleanup(workerId, taskId); addPendingTask(taskRunnerWorkItem); } }, taskRunnerWorkItem.getRetryPolicy().getAndIncrementRetryDelay().getMillis(), TimeUnit.MILLISECONDS ); } /** * Removes a task from the running queue and clears out the ZK status path of the task. * * @param workerId - the worker that was previously running the task * @param taskId - the task to cleanup */ private void cleanup(final String workerId, final String taskId) { runningTasks.remove(taskId); final String statusPath = JOINER.join(config.getStatusPath(), workerId, taskId); try { cf.delete().guaranteed().forPath(statusPath); } catch (Exception e) { log.info("Tried to delete status path[%s] that didn't exist! Must've gone away already?", statusPath); } } /** * Ensures no workers are already running a task before assigning the task to a worker. * It is possible that a worker is running a task that the RTR has no knowledge of. This occurs when the RTR * needs to bootstrap after a restart. * * @param taskRunnerWorkItem - the task to assign */ private void assignTask(TaskRunnerWorkItem taskRunnerWorkItem) { try { final String taskId = taskRunnerWorkItem.getTask().getId(); ZkWorker zkWorker = findWorkerRunningTask(taskId); // If a worker is already running this task, we don't need to announce it if (zkWorker != null) { final Worker worker = zkWorker.getWorker(); log.info("Worker[%s] is already running task[%s].", worker.getHost(), taskId); runningTasks.put(taskId, pendingTasks.remove(taskId)); log.info("Task %s switched from pending to running", taskId); } else { // Nothing running this task, announce it in ZK for a worker to run it zkWorker = findWorkerForTask(); if (zkWorker != null) { announceTask(zkWorker.getWorker(), taskRunnerWorkItem); } } } catch (Exception e) { throw Throwables.propagate(e); } } /** * Creates a ZK entry under a specific path associated with a worker. The worker is responsible for * removing the task ZK entry and creating a task status ZK entry. * * @param theWorker The worker the task is assigned to * @param taskRunnerWorkItem The task to be assigned */ private void announceTask(Worker theWorker, TaskRunnerWorkItem taskRunnerWorkItem) throws Exception { final Task task = taskRunnerWorkItem.getTask(); log.info("Coordinator asking Worker[%s] to add task[%s]", theWorker.getHost(), task.getId()); byte[] rawBytes = jsonMapper.writeValueAsBytes(task); if (rawBytes.length > config.getMaxNumBytes()) { throw new ISE("Length of raw bytes for task too large[%,d > %,d]", rawBytes.length, config.getMaxNumBytes()); } cf.create() .withMode(CreateMode.EPHEMERAL) .forPath( JOINER.join( config.getTaskPath(), theWorker.getHost(), task.getId() ), rawBytes ); runningTasks.put(task.getId(), pendingTasks.remove(task.getId())); log.info("Task %s switched from pending to running", task.getId()); // Syncing state with Zookeeper - don't assign new tasks until the task we just assigned is actually running // on a worker - this avoids overflowing a worker with tasks synchronized (statusLock) { while (findWorkerRunningTask(task.getId()) == null) { statusLock.wait(config.getTaskAssignmentTimeoutDuration().getMillis()); } } } /** * When a new worker appears, listeners are registered for status changes associated with tasks assigned to * the worker. Status changes indicate the creation or completion of a task. * The RemoteTaskRunner updates state according to these changes. * * @param worker - contains metadata for a worker that has appeared in ZK */ private void addWorker(final Worker worker) { try { final String workerStatusPath = JOINER.join(config.getStatusPath(), worker.getHost()); final PathChildrenCache statusCache = new PathChildrenCache(cf, workerStatusPath, true); final ZkWorker zkWorker = new ZkWorker( worker, statusCache, jsonMapper ); // Add status listener to the watcher for status changes statusCache.getListenable().addListener( new PathChildrenCacheListener() { @Override public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { try { if (event.getData() != null) { log.info("Event[%s]: %s", event.getType(), event.getData().getPath()); } if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)) { final String taskId = ZKPaths.getNodeFromPath(event.getData().getPath()); final TaskStatus taskStatus; // This can fail if a worker writes a bogus status. Retry if so. try { taskStatus = jsonMapper.readValue( event.getData().getData(), TaskStatus.class ); if (!taskStatus.getId().equals(taskId)) { // Sanity check throw new ISE( "Worker[%s] status id does not match payload id: %s != %s", worker.getHost(), taskId, taskStatus.getId() ); } } catch (Exception e) { log.warn(e, "Worker[%s] wrote bogus status for task: %s", worker.getHost(), taskId); retryTask(runningTasks.get(taskId), worker.getHost()); throw Throwables.propagate(e); } log.info( "Worker[%s] wrote %s status for task: %s", worker.getHost(), taskStatus.getStatusCode(), taskId ); // Synchronizing state with ZK synchronized (statusLock) { statusLock.notify(); } final TaskRunnerWorkItem taskRunnerWorkItem = runningTasks.get(taskId); if (taskRunnerWorkItem == null) { log.warn( "WTF?! Worker[%s] announcing a status for a task I didn't know about: %s", worker.getHost(), taskId ); } if (taskStatus.isComplete()) { if (taskRunnerWorkItem != null) { final TaskCallback callback = taskRunnerWorkItem.getCallback(); if (callback != null) { callback.notify(taskStatus); } } // Worker is done with this task zkWorker.setLastCompletedTaskTime(new DateTime()); cleanup(worker.getHost(), taskId); runPendingTasks(); } } else if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) || event.getType().equals(PathChildrenCacheEvent.Type.CONNECTION_LOST)) { final String taskId = ZKPaths.getNodeFromPath(event.getData().getPath()); if (runningTasks.containsKey(taskId)) { log.info("Task %s just disappeared!", taskId); retryTask(runningTasks.get(taskId), worker.getHost()); } } } catch (Exception e) { log.makeAlert(e, "Failed to handle new worker status") .addData("worker", worker.getHost()) .addData("znode", event.getData().getPath()) .emit(); } } } ); zkWorkers.put(worker.getHost(), zkWorker); statusCache.start(); runPendingTasks(); } catch (Exception e) { throw Throwables.propagate(e); } } /** * When a ephemeral worker node disappears from ZK, incomplete running tasks will be retried by * the logic in the status listener. We still have to make sure there are no tasks assigned * to the worker but not yet running. * * @param worker - the removed worker */ private void removeWorker(final Worker worker) { ZkWorker zkWorker = zkWorkers.get(worker.getHost()); if (zkWorker != null) { try { Set<String> tasksPending = Sets.newHashSet( cf.getChildren() .forPath(JOINER.join(config.getTaskPath(), worker.getHost())) ); log.info("%s had %d tasks pending", worker.getHost(), tasksPending.size()); for (String taskId : tasksPending) { TaskRunnerWorkItem taskRunnerWorkItem = pendingTasks.get(taskId); if (taskRunnerWorkItem != null) { cf.delete().guaranteed().forPath(JOINER.join(config.getTaskPath(), worker.getHost(), taskId)); retryTask(taskRunnerWorkItem, worker.getHost()); } else { log.warn("RemoteTaskRunner has no knowledge of pending task %s", taskId); } } zkWorker.getStatusCache().close(); } catch (Exception e) { throw Throwables.propagate(e); } finally { zkWorkers.remove(worker.getHost()); } } } private ZkWorker findWorkerForTask() { try { final MinMaxPriorityQueue<ZkWorker> workerQueue = MinMaxPriorityQueue.<ZkWorker>orderedBy( new Comparator<ZkWorker>() { @Override public int compare(ZkWorker w1, ZkWorker w2) { return -Ints.compare(w1.getRunningTasks().size(), w2.getRunningTasks().size()); } } ).create( FunctionalIterable.create(zkWorkers.values()).filter( new Predicate<ZkWorker>() { @Override public boolean apply(ZkWorker input) { return (!input.isAtCapacity() && input.getWorker() .getVersion() .compareTo(workerSetupManager.getWorkerSetupData().getMinVersion()) >= 0); } } ) ); if (workerQueue.isEmpty()) { log.info("Worker nodes %s do not have capacity to run any more tasks!", zkWorkers.values()); return null; } return workerQueue.peek(); } catch (Exception e) { throw Throwables.propagate(e); } } }
additional logs
merger/src/main/java/com/metamx/druid/merger/coordinator/RemoteTaskRunner.java
additional logs
<ide><path>erger/src/main/java/com/metamx/druid/merger/coordinator/RemoteTaskRunner.java <ide> import java.util.Set; <ide> import java.util.concurrent.Callable; <ide> import java.util.concurrent.ConcurrentHashMap; <del>import java.util.concurrent.ExecutionException; <ide> import java.util.concurrent.ExecutorService; <ide> import java.util.concurrent.Executors; <del>import java.util.concurrent.Future; <ide> import java.util.concurrent.ScheduledExecutorService; <ide> import java.util.concurrent.TimeUnit; <ide> <ide> @Override <ide> public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception <ide> { <add> log.info("Event: %s", event.getType()); <add> if (event.getData() != null) { <add> log.info("Data: %s", event.getData().getPath()); <add> } <ide> try { <del> if (event.getData() != null) { <del> log.info("Event[%s]: %s", event.getType(), event.getData().getPath()); <del> } <del> <ide> if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED) || <ide> event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)) { <ide> <ide> cleanup(worker.getHost(), taskId); <ide> runPendingTasks(); <ide> } <del> } else if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED) <del> || event.getType().equals(PathChildrenCacheEvent.Type.CONNECTION_LOST)) { <add> } else if (event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)) { <ide> final String taskId = ZKPaths.getNodeFromPath(event.getData().getPath()); <ide> if (runningTasks.containsKey(taskId)) { <ide> log.info("Task %s just disappeared!", taskId); <ide> retryTask(runningTasks.get(taskId), worker.getHost()); <add> } else { <add> log.info("Lost a task I didn't know about: %s", taskId); <ide> } <ide> } <ide> }
Java
lgpl-2.1
8fc910204cefba37972177eeef59ac0a81c6dd30
0
stuartwdouglas/jboss-remoting,kabir/jboss-remoting,rhusar/jboss-remoting,bmaxwell/jboss-remoting,dpospisil/jboss-remoting,seeburger-ag/jboss-remoting
/* * JBoss, Home of Professional Open Source * Copyright 2011, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.remoting3.remote; import java.io.IOException; import java.nio.ByteBuffer; import org.jboss.remoting3.MessageCancelledException; import org.jboss.remoting3.MessageInputStream; import org.xnio.Pooled; import org.xnio.channels.Channels; import org.xnio.streams.BufferPipeInputStream; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ final class InboundMessage { final short messageId; final RemoteConnectionChannel channel; int inboundWindow; boolean closed; boolean cancelled; static final IntIndexer<InboundMessage> INDEXER = new IntIndexer<InboundMessage>() { public int getKey(final InboundMessage argument) { return argument.messageId & 0xffff; } public boolean equals(final InboundMessage argument, final int index) { return (argument.messageId & 0xffff) == index; } }; InboundMessage(final short messageId, final RemoteConnectionChannel channel, int inboundWindow) { this.messageId = messageId; this.channel = channel; this.inboundWindow = inboundWindow; } BufferPipeInputStream inputStream = new BufferPipeInputStream(new BufferPipeInputStream.InputHandler() { public void acknowledge(final Pooled<ByteBuffer> acked) throws IOException { int consumed = acked.getResource().position(); openInboundWindow(consumed); Pooled<ByteBuffer> pooled = allocate(Protocol.MESSAGE_WINDOW_OPEN); try { ByteBuffer buffer = pooled.getResource(); buffer.putInt(consumed); // Open window by buffer size buffer.flip(); Channels.sendBlocking(channel.getConnection().getChannel(), buffer); } finally { pooled.free(); } } public void close() throws IOException { sendAsyncClose(); } }); MessageInputStream messageInputStream = new MessageInputStream() { public int read() throws IOException { return inputStream.read(); } public int read(final byte[] bytes, final int offs, final int length) throws IOException { return inputStream.read(bytes, offs, length); } public long skip(final long l) throws IOException { return inputStream.skip(l); } public int available() throws IOException { return inputStream.available(); } public void close() throws IOException { synchronized (InboundMessage.this) { if (cancelled) { throw new MessageCancelledException(); } } inputStream.close(); } }; void sendAsyncClose() throws IOException { Pooled<ByteBuffer> pooled = allocate(Protocol.MESSAGE_ASYNC_CLOSE); try { ByteBuffer buffer = pooled.getResource(); buffer.flip(); Channels.sendBlocking(channel.getConnection().getChannel(), buffer); } finally { pooled.free(); } } Pooled<ByteBuffer> allocate(byte protoId) { Pooled<ByteBuffer> pooled = channel.allocate(protoId); ByteBuffer buffer = pooled.getResource(); buffer.putShort(messageId); return pooled; } void openInboundWindow(int consumed) { synchronized (this) { inboundWindow += consumed; } } void closeInboundWindow(int produced) { synchronized (this) { if ((inboundWindow -= produced) < 0) { channel.getConnection().handleException(new IOException("Input overrun")); } } } void handleIncoming(Pooled<ByteBuffer> pooledBuffer) { boolean eof = false; synchronized (this) { if (closed) { // ignore pooledBuffer.free(); return; } if (inboundWindow == 0) { pooledBuffer.free(); // TODO log window overrun try { sendAsyncClose(); } catch (IOException e) { // todo log it } return; } ByteBuffer buffer = pooledBuffer.getResource(); closeInboundWindow(buffer.remaining() - 8); buffer.position(buffer.position() - 1); byte flags = buffer.get(); eof = (flags & Protocol.MSG_FLAG_EOF) != 0; if (eof) { closed = true; channel.freeInboundMessage(messageId); } boolean cancelled = (flags & Protocol.MSG_FLAG_CANCELLED) != 0; if (cancelled) { this.cancelled = true; } } inputStream.push(pooledBuffer); if (eof) { inputStream.pushEof(); } } }
src/main/java/org/jboss/remoting3/remote/InboundMessage.java
/* * JBoss, Home of Professional Open Source * Copyright 2011, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.remoting3.remote; import java.io.IOException; import java.nio.ByteBuffer; import org.jboss.remoting3.MessageCancelledException; import org.jboss.remoting3.MessageInputStream; import org.xnio.ChannelThread; import org.xnio.Pooled; import org.xnio.Xnio; import org.xnio.channels.Channels; import org.xnio.streams.BufferPipeInputStream; /** * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ final class InboundMessage { final short messageId; final RemoteConnectionChannel channel; int inboundWindow; boolean closed; boolean cancelled; static final IntIndexer<InboundMessage> INDEXER = new IntIndexer<InboundMessage>() { public int getKey(final InboundMessage argument) { return argument.messageId & 0xffff; } public boolean equals(final InboundMessage argument, final int index) { return (argument.messageId & 0xffff) == index; } }; InboundMessage(final short messageId, final RemoteConnectionChannel channel, int inboundWindow) { this.messageId = messageId; this.channel = channel; this.inboundWindow = inboundWindow; } BufferPipeInputStream inputStream = new BufferPipeInputStream(new BufferPipeInputStream.InputHandler() { public void acknowledge(final Pooled<ByteBuffer> acked) throws IOException { int consumed = acked.getResource().position(); openInboundWindow(consumed); Pooled<ByteBuffer> pooled = allocate(Protocol.MESSAGE_WINDOW_OPEN); try { ByteBuffer buffer = pooled.getResource(); buffer.putInt(consumed); // Open window by buffer size buffer.flip(); Channels.sendBlocking(channel.getConnection().getChannel(), buffer); } finally { pooled.free(); } } public void close() throws IOException { sendAsyncClose(); } }); MessageInputStream messageInputStream = new MessageInputStream() { public int read() throws IOException { return inputStream.read(); } public int read(final byte[] bytes, final int offs, final int length) throws IOException { return inputStream.read(bytes, offs, length); } public long skip(final long l) throws IOException { return inputStream.skip(l); } public int available() throws IOException { return inputStream.available(); } public void close() throws IOException { synchronized (InboundMessage.this) { if (cancelled) { throw new MessageCancelledException(); } } inputStream.close(); } }; void sendAsyncClose() throws IOException { Pooled<ByteBuffer> pooled = allocate(Protocol.MESSAGE_ASYNC_CLOSE); try { ByteBuffer buffer = pooled.getResource(); buffer.flip(); Channels.sendBlocking(channel.getConnection().getChannel(), buffer); } finally { pooled.free(); } } Pooled<ByteBuffer> allocate(byte protoId) { Pooled<ByteBuffer> pooled = channel.allocate(protoId); ByteBuffer buffer = pooled.getResource(); buffer.putShort(messageId); return pooled; } void openInboundWindow(int consumed) { synchronized (this) { inboundWindow += consumed; } } void closeInboundWindow(int produced) { synchronized (this) { if ((inboundWindow -= produced) < 0) { channel.getConnection().handleException(new IOException("Input overrun")); } } } void handleIncoming(Pooled<ByteBuffer> pooledBuffer) { boolean eof = false; synchronized (this) { if (closed) { // ignore pooledBuffer.free(); return; } if (inboundWindow == 0) { pooledBuffer.free(); // TODO log window overrun try { sendAsyncClose(); } catch (IOException e) { // todo log it } return; } ByteBuffer buffer = pooledBuffer.getResource(); closeInboundWindow(buffer.remaining() - 8); buffer.position(buffer.position() - 1); byte flags = buffer.get(); eof = (flags & Protocol.MSG_FLAG_EOF) != 0; if (eof) { closed = true; channel.freeInboundMessage(messageId); } boolean cancelled = (flags & Protocol.MSG_FLAG_CANCELLED) != 0; if (cancelled) { this.cancelled = true; } } inputStream.push(pooledBuffer); if (eof) { inputStream.pushEof(); } } }
Clean up imports
src/main/java/org/jboss/remoting3/remote/InboundMessage.java
Clean up imports
<ide><path>rc/main/java/org/jboss/remoting3/remote/InboundMessage.java <ide> <ide> import org.jboss.remoting3.MessageCancelledException; <ide> import org.jboss.remoting3.MessageInputStream; <del>import org.xnio.ChannelThread; <ide> import org.xnio.Pooled; <del>import org.xnio.Xnio; <ide> import org.xnio.channels.Channels; <ide> import org.xnio.streams.BufferPipeInputStream; <ide>