gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* 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.drill.common.expression;
import java.math.BigDecimal;
import org.apache.drill.common.expression.IfExpression.IfCondition;
import org.apache.drill.common.expression.ValueExpressions.BooleanExpression;
import org.apache.drill.common.expression.ValueExpressions.DateExpression;
import org.apache.drill.common.expression.ValueExpressions.Decimal18Expression;
import org.apache.drill.common.expression.ValueExpressions.Decimal28Expression;
import org.apache.drill.common.expression.ValueExpressions.Decimal38Expression;
import org.apache.drill.common.expression.ValueExpressions.Decimal9Expression;
import org.apache.drill.common.expression.ValueExpressions.DoubleExpression;
import org.apache.drill.common.expression.ValueExpressions.FloatExpression;
import org.apache.drill.common.expression.ValueExpressions.IntExpression;
import org.apache.drill.common.expression.ValueExpressions.IntervalDayExpression;
import org.apache.drill.common.expression.ValueExpressions.IntervalYearExpression;
import org.apache.drill.common.expression.ValueExpressions.LongExpression;
import org.apache.drill.common.expression.ValueExpressions.QuotedString;
import org.apache.drill.common.expression.ValueExpressions.TimeExpression;
import org.apache.drill.common.expression.ValueExpressions.TimeStampExpression;
import org.apache.drill.common.expression.ValueExpressions.VarDecimalExpression;
import org.apache.drill.common.expression.visitors.AbstractExprVisitor;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.joda.time.Period;
import org.apache.drill.shaded.guava.com.google.common.collect.ImmutableList;
public class ExpressionStringBuilder extends AbstractExprVisitor<Void, StringBuilder, RuntimeException>{
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ExpressionStringBuilder.class);
static final ExpressionStringBuilder INSTANCE = new ExpressionStringBuilder();
public static String toString(LogicalExpression expr) {
StringBuilder sb = new StringBuilder();
expr.accept(INSTANCE, sb);
return sb.toString();
}
public static void toString(LogicalExpression expr, StringBuilder sb) {
expr.accept(INSTANCE, sb);
}
public static String escapeSingleQuote(String input) {
return input.replaceAll("(['\\\\])", "\\\\$1");
}
public static String escapeBackTick(String input) {
return input.replaceAll("([`\\\\])", "\\\\$1");
}
@Override
public Void visitFunctionCall(FunctionCall call, StringBuilder sb) throws RuntimeException {
ImmutableList<LogicalExpression> args = call.args;
sb.append(call.getName());
sb.append("(");
for (int i = 0; i < args.size(); i++) {
if (i != 0) {
sb.append(", ");
}
args.get(i).accept(this, sb);
}
sb.append(") ");
return null;
}
@Override
public Void visitBooleanOperator(BooleanOperator op, StringBuilder sb) throws RuntimeException {
return visitFunctionCall(op, sb);
}
@Override
public Void visitFunctionHolderExpression(FunctionHolderExpression holder, StringBuilder sb) throws RuntimeException {
ImmutableList<LogicalExpression> args = holder.args;
sb.append(holder.getName());
sb.append("(");
for (int i = 0; i < args.size(); i++) {
if (i != 0) {
sb.append(", ");
}
args.get(i).accept(this, sb);
}
sb.append(") ");
return null;
}
@Override
public Void visitIfExpression(IfExpression ifExpr, StringBuilder sb) throws RuntimeException {
// serialize the if expression
sb.append(" ( ");
IfCondition c = ifExpr.ifCondition;
sb.append("if (");
c.condition.accept(this, sb);
sb.append(" ) then (");
c.expression.accept(this, sb);
sb.append(" ) ");
sb.append(" else (");
ifExpr.elseExpression.accept(this, sb);
sb.append(" ) ");
sb.append(" end ");
sb.append(" ) ");
return null;
}
@Override
public Void visitSchemaPath(SchemaPath path, StringBuilder sb) throws RuntimeException {
PathSegment seg = path.getRootSegment();
if (seg.isArray()) {
throw new IllegalStateException("Drill doesn't currently support top level arrays");
}
sb.append('`');
sb.append(escapeBackTick(seg.getNameSegment().getPath()));
sb.append('`');
while ( (seg = seg.getChild()) != null) {
if (seg.isNamed()) {
sb.append('.');
sb.append('`');
sb.append(escapeBackTick(seg.getNameSegment().getPath()));
sb.append('`');
} else {
sb.append('[');
sb.append(seg.getArraySegment().getIndex());
sb.append(']');
}
}
return null;
}
@Override
public Void visitLongConstant(LongExpression lExpr, StringBuilder sb) throws RuntimeException {
sb.append(lExpr.getLong());
return null;
}
@Override
public Void visitDateConstant(DateExpression lExpr, StringBuilder sb) throws RuntimeException {
sb.append("cast( ");
sb.append(lExpr.getDate());
sb.append(" as DATE)");
return null;
}
@Override
public Void visitTimeConstant(TimeExpression lExpr, StringBuilder sb) throws RuntimeException {
sb.append("cast( ");
sb.append(lExpr.getTime());
sb.append(" as TIME)");
return null;
}
@Override
public Void visitTimeStampConstant(TimeStampExpression lExpr, StringBuilder sb) throws RuntimeException {
sb.append("cast( ");
sb.append(lExpr.getTimeStamp());
sb.append(" as TIMESTAMP)");
return null;
}
@Override
public Void visitIntervalYearConstant(IntervalYearExpression lExpr, StringBuilder sb) throws RuntimeException {
sb.append("cast( '");
sb.append(Period.months(lExpr.getIntervalYear()).toString());
sb.append("' as INTERVALYEAR)");
return null;
}
@Override
public Void visitIntervalDayConstant(IntervalDayExpression lExpr, StringBuilder sb) throws RuntimeException {
sb.append("cast( '");
sb.append(Period.days(lExpr.getIntervalDay()).plusMillis(lExpr.getIntervalMillis()).toString());
sb.append("' as INTERVALDAY)");
return null;
}
@Override
public Void visitDecimal9Constant(Decimal9Expression decExpr, StringBuilder sb) throws RuntimeException {
BigDecimal value = new BigDecimal(decExpr.getIntFromDecimal());
sb.append((value.setScale(decExpr.getScale())).toString());
return null;
}
@Override
public Void visitDecimal18Constant(Decimal18Expression decExpr, StringBuilder sb) throws RuntimeException {
BigDecimal value = new BigDecimal(decExpr.getLongFromDecimal());
sb.append((value.setScale(decExpr.getScale())).toString());
return null;
}
@Override
public Void visitDecimal28Constant(Decimal28Expression decExpr, StringBuilder sb) throws RuntimeException {
sb.append(decExpr.toString());
return null;
}
@Override
public Void visitDecimal38Constant(Decimal38Expression decExpr, StringBuilder sb) throws RuntimeException {
sb.append(decExpr.getBigDecimal().toString());
return null;
}
@Override
public Void visitVarDecimalConstant(VarDecimalExpression decExpr, StringBuilder sb) throws RuntimeException {
sb.append(decExpr.getBigDecimal().toString());
return null;
}
@Override
public Void visitDoubleConstant(DoubleExpression dExpr, StringBuilder sb) throws RuntimeException {
sb.append(dExpr.getDouble());
return null;
}
@Override
public Void visitBooleanConstant(BooleanExpression e, StringBuilder sb) throws RuntimeException {
sb.append(e.getBoolean());
return null;
}
@Override
public Void visitQuotedStringConstant(QuotedString e, StringBuilder sb) throws RuntimeException {
sb.append("'");
sb.append(escapeSingleQuote(e.value));
sb.append("'");
return null;
}
@Override
public Void visitConvertExpression(ConvertExpression e, StringBuilder sb) throws RuntimeException {
sb.append(e.getConvertFunction()).append("(");
e.getInput().accept(this, sb);
sb.append(", '").append(e.getEncodingType()).append("')");
return null;
}
@Override
public Void visitAnyValueExpression(AnyValueExpression e, StringBuilder sb) throws RuntimeException {
sb.append("any(");
e.getInput().accept(this, sb);
sb.append(")");
return null;
}
@Override
public Void visitCastExpression(CastExpression e, StringBuilder sb) throws RuntimeException {
MajorType mt = e.getMajorType();
sb.append("cast( (");
e.getInput().accept(this, sb);
sb.append(" ) as ");
sb.append(mt.getMinorType().name());
switch(mt.getMinorType()) {
case FLOAT4:
case FLOAT8:
case BIT:
case INT:
case TINYINT:
case SMALLINT:
case BIGINT:
case UINT1:
case UINT2:
case UINT4:
case UINT8:
case DATE:
case TIMESTAMP:
case TIMESTAMPTZ:
case TIME:
case INTERVAL:
case INTERVALDAY:
case INTERVALYEAR:
// do nothing else.
break;
case VAR16CHAR:
case VARBINARY:
case VARCHAR:
case FIXED16CHAR:
case FIXEDBINARY:
case FIXEDCHAR:
// add size in parens
sb.append("(");
sb.append(mt.getPrecision());
sb.append(")");
break;
case DECIMAL9:
case DECIMAL18:
case DECIMAL28DENSE:
case DECIMAL28SPARSE:
case DECIMAL38DENSE:
case DECIMAL38SPARSE:
case VARDECIMAL:
// add scale and precision
sb.append("(");
sb.append(mt.getPrecision());
sb.append(", ");
sb.append(mt.getScale());
sb.append(")");
break;
default:
throw new UnsupportedOperationException(String.format("Unable to convert cast expression %s into string.", e));
}
sb.append(" )");
return null;
}
@Override
public Void visitFloatConstant(FloatExpression fExpr, StringBuilder sb) throws RuntimeException {
sb.append(fExpr.getFloat());
return null;
}
@Override
public Void visitIntConstant(IntExpression intExpr, StringBuilder sb) throws RuntimeException {
sb.append(intExpr.getInt());
return null;
}
@Override
public Void visitNullConstant(TypedNullConstant e, StringBuilder sb) throws RuntimeException {
sb.append("NULL");
return null;
}
@Override
public Void visitNullExpression(NullExpression e, StringBuilder sb) throws RuntimeException {
sb.append("NULL");
return null;
}
@Override
public Void visitUnknown(LogicalExpression e, StringBuilder sb) {
sb.append(e.toString());
return null;
}
}
| |
/*
* Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.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.orientechnologies.orient.core.storage.impl.local;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OStorageTxConfiguration;
import com.orientechnologies.orient.core.db.record.ORecordOperation;
import com.orientechnologies.orient.core.exception.OTransactionException;
import com.orientechnologies.orient.core.hook.ORecordHook;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OPhysicalPosition;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.tx.OTransactionAbstract;
import com.orientechnologies.orient.core.tx.OTxListener;
public class OStorageLocalTxExecuter {
private final OStorageLocal storage;
private final OTxSegment txSegment;
private OTransaction currentTransaction;
public OStorageLocalTxExecuter(final OStorageLocal iStorage, final OStorageTxConfiguration iConfig) throws IOException {
storage = iStorage;
iConfig.path = OStorageVariableParser.DB_PATH_VARIABLE + "/txlog.otx";
txSegment = new OTxSegment(storage, iStorage.getConfiguration().txSegment);
}
public void open() throws IOException {
txSegment.open();
}
public void create() throws IOException {
txSegment.create(1000000);
}
public void close() throws IOException {
txSegment.close();
}
protected long createRecord(final int iTxId, final OCluster iClusterSegment, final ORecordId iRid, final byte[] iContent,
final byte iRecordType) {
iRid.clusterPosition = -1;
try {
storage.createRecord(iClusterSegment, iContent, iRecordType, iRid);
// SAVE INTO THE LOG THE POSITION OF THE RECORD JUST CREATED. IF TX FAILS AT THIS POINT A GHOST RECORD IS CREATED UNTIL DEFRAG
txSegment.addLog(OTxSegment.OPERATION_CREATE, iTxId, iRid.clusterId, iRid.clusterPosition, iRecordType, 0, null);
} catch (IOException e) {
OLogManager.instance().error(this, "Error on creating entry in log segment: " + iClusterSegment, e,
OTransactionException.class);
}
return iRid.clusterPosition;
}
/**
* Stores the new content in a new position, then saves in the log the coords of the new position. At free time the
*
* @param iTxId
* @param iClusterSegment
* @param iRid
* @param iContent
* @param iVersion
* @param iRecordType
* @return
*/
protected int updateRecord(final int iTxId, final OCluster iClusterSegment, final ORecordId iRid, final byte[] iContent,
final int iVersion, final byte iRecordType) {
try {
// READ CURRENT RECORD CONTENT
final ORawBuffer buffer = storage.readRecord(iClusterSegment, iRid, false);
// SAVE INTO THE LOG THE POSITION OF THE OLD RECORD JUST DELETED. IF TX FAILS AT THIS POINT AS ABOVE
txSegment.addLog(OTxSegment.OPERATION_UPDATE, iTxId, iRid.clusterId, iRid.clusterPosition, iRecordType, buffer.version,
buffer.buffer);
final OPhysicalPosition ppos = storage.updateRecord(iClusterSegment, iRid, iContent, iVersion, iRecordType);
if(ppos != null)
return ppos.version;
return -1;
} catch (IOException e) {
OLogManager.instance().error(this, "Error on updating entry #" + iRid + " in log segment: " + iClusterSegment, e,
OTransactionException.class);
}
return -1;
}
protected boolean deleteRecord(final int iTxId, final OCluster iClusterSegment, final long iPosition, final int iVersion) {
try {
final ORecordId rid = new ORecordId(iClusterSegment.getId(), iPosition);
// READ CURRENT RECORD CONTENT
final ORawBuffer buffer = storage.readRecord(iClusterSegment, rid, false);
// SAVE INTO THE LOG THE OLD RECORD
txSegment.addLog(OTxSegment.OPERATION_DELETE, iTxId, iClusterSegment.getId(), iPosition, buffer.recordType, buffer.version,
buffer.buffer);
return storage.deleteRecord(iClusterSegment, rid, iVersion) != null;
} catch (IOException e) {
OLogManager.instance().error(this, "Error on deleting entry #" + iPosition + " in log segment: " + iClusterSegment, e,
OTransactionException.class);
}
return false;
}
public OTxSegment getTxSegment() {
return txSegment;
}
public void commitAllPendingRecords(final OTransaction iTx) throws IOException {
currentTransaction = iTx;
try {
// COPY ALL THE ENTRIES IN SEPARATE COLLECTION SINCE DURING THE COMMIT PHASE SOME NEW ENTRIES COULD BE CREATED AND
// CONCURRENT-EXCEPTION MAY OCCURS
final List<ORecordOperation> tmpEntries = new ArrayList<ORecordOperation>();
while (iTx.getCurrentRecordEntries().iterator().hasNext()) {
for (ORecordOperation txEntry : iTx.getCurrentRecordEntries())
tmpEntries.add(txEntry);
iTx.clearRecordEntries();
if (!tmpEntries.isEmpty()) {
for (ORecordOperation txEntry : tmpEntries)
// COMMIT ALL THE SINGLE ENTRIES ONE BY ONE
commitEntry(iTx, txEntry, iTx.isUsingLog());
}
}
// UPDATE THE CACHE ONLY IF THE ITERATOR ALLOWS IT
OTransactionAbstract.updateCacheFromEntries(storage, iTx, iTx.getAllRecordEntries(), true);
} finally {
currentTransaction = null;
}
}
public void clearLogEntries(final OTransaction iTx) throws IOException {
// CLEAR ALL TEMPORARY RECORDS
txSegment.clearLogEntries(iTx.getId());
}
private void commitEntry(final OTransaction iTx, final ORecordOperation txEntry, final boolean iUseLog) throws IOException {
if (txEntry.type != ORecordOperation.DELETED && !txEntry.getRecord().isDirty())
return;
final ORecordId rid = (ORecordId) txEntry.getRecord().getIdentity();
final boolean wasNew = rid.isNew();
if (rid.clusterId == ORID.CLUSTER_ID_INVALID && txEntry.getRecord() instanceof ODocument
&& ((ODocument) txEntry.getRecord()).getSchemaClass() != null) {
// TRY TO FIX CLUSTER ID TO THE DEFAULT CLUSTER ID DEFINED IN SCHEMA CLASS
rid.clusterId = ((ODocument) txEntry.getRecord()).getSchemaClass().getDefaultClusterId();
}
final OCluster cluster = storage.getClusterById(rid.clusterId);
if (cluster.getName().equals(OStorage.CLUSTER_INDEX_NAME))
// AVOID TO COMMIT INDEX STUFF
return;
if (!(cluster instanceof OClusterLocal))
// ONLY LOCAL CLUSTER ARE INVOLVED IN TX
return;
if (txEntry.getRecord() instanceof OTxListener)
((OTxListener) txEntry.getRecord()).onEvent(txEntry, OTxListener.EVENT.BEFORE_COMMIT);
switch (txEntry.type) {
case ORecordOperation.LOADED:
break;
case ORecordOperation.CREATED: {
// CHECK 2 TIMES TO ASSURE THAT IT'S A CREATE OR AN UPDATE BASED ON RECURSIVE TO-STREAM METHOD
byte[] stream = txEntry.getRecord().toStream();
if (wasNew) {
if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_CREATE, txEntry.getRecord()))
// RECORD CHANGED: RE-STREAM IT
stream = txEntry.getRecord().toStream();
} else {
if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_UPDATE, txEntry.getRecord()))
// RECORD CHANGED: RE-STREAM IT
stream = txEntry.getRecord().toStream();
}
if (rid.isNew()) {
txEntry.getRecord().onBeforeIdentityChanged(rid);
rid.clusterId = cluster.getId();
}
if (rid.isNew()) {
if (iUseLog)
rid.clusterPosition = createRecord(iTx.getId(), cluster, rid, stream, txEntry.getRecord().getRecordType());
else
rid.clusterPosition = iTx.getDatabase().getStorage()
.createRecord(rid, stream, txEntry.getRecord().getRecordType(), (byte) 0, null);
txEntry.getRecord().onAfterIdentityChanged(txEntry.getRecord());
iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_CREATE, txEntry.getRecord());
} else {
if (iUseLog)
txEntry.getRecord()
.setVersion(
updateRecord(iTx.getId(), cluster, rid, stream, txEntry.getRecord().getVersion(), txEntry.getRecord()
.getRecordType()));
else
txEntry.getRecord()
.setVersion(
iTx.getDatabase()
.getStorage()
.updateRecord(rid, stream, txEntry.getRecord().getVersion(), txEntry.getRecord().getRecordType(), (byte) 0,
null));
}
break;
}
case ORecordOperation.UPDATED: {
byte[] stream = txEntry.getRecord().toStream();
if (iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_UPDATE, txEntry.getRecord()))
// RECORD CHANGED: RE-STREAM IT
stream = txEntry.getRecord().toStream();
if (iUseLog)
txEntry.getRecord().setVersion(
updateRecord(iTx.getId(), cluster, rid, stream, txEntry.getRecord().getVersion(), txEntry.getRecord().getRecordType()));
else
txEntry.getRecord().setVersion(
iTx.getDatabase().getStorage()
.updateRecord(rid, stream, txEntry.getRecord().getVersion(), txEntry.getRecord().getRecordType(), (byte) 0, null));
iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_UPDATE, txEntry.getRecord());
break;
}
case ORecordOperation.DELETED: {
iTx.getDatabase().callbackHooks(ORecordHook.TYPE.BEFORE_DELETE, txEntry.getRecord());
if (iUseLog)
deleteRecord(iTx.getId(), cluster, rid.clusterPosition, txEntry.getRecord().getVersion());
else
iTx.getDatabase().getStorage().deleteRecord(rid, txEntry.getRecord().getVersion(), (byte) 0, null);
iTx.getDatabase().callbackHooks(ORecordHook.TYPE.AFTER_DELETE, txEntry.getRecord());
}
break;
}
txEntry.getRecord().unsetDirty();
if (txEntry.getRecord() instanceof OTxListener)
((OTxListener) txEntry.getRecord()).onEvent(txEntry, OTxListener.EVENT.AFTER_COMMIT);
}
public boolean isCommitting() {
return currentTransaction != null;
}
public OTransaction getCurrentTransaction() {
return currentTransaction;
}
}
| |
/*
* Copyright (C) 2013 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.pkmmte.techdissected.view;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
import android.widget.AbsListView;
/**
* The SwipeRefreshLayout should be used whenever the user can refresh the
* contents of a view via a vertical swipe gesture. The activity that
* instantiates this view should add an OnRefreshListener to be notified
* whenever the swipe to refresh gesture is completed. The SwipeRefreshLayout
* will notify the listener each and every time the gesture is completed again;
* the listener is responsible for correctly determining when to actually
* initiate a refresh of its content. If the listener determines there should
* not be a refresh, it must call setRefreshing(false) to cancel any visual
* indication of a refresh. If an activity wishes to show just the progress
* animation, it should call setRefreshing(true). To disable the gesture and progress
* animation, call setEnabled(false) on the view.
*
* <p> This layout should be made the parent of the view that will be refreshed as a
* result of the gesture and can only support one direct child. This view will
* also be made the target of the gesture and will be forced to match both the
* width and the height supplied in this layout. The SwipeRefreshLayout does not
* provide accessibility events; instead, a menu item must be provided to allow
* refresh of the content wherever this gesture is used.</p>
*/
public class PkSwipeRefreshLayout extends ViewGroup {
private static final String LOG_TAG = PkSwipeRefreshLayout.class.getSimpleName();
private static final long RETURN_TO_ORIGINAL_POSITION_TIMEOUT = 300;
private static final float ACCELERATE_INTERPOLATION_FACTOR = 1.5f;
private static final float DECELERATE_INTERPOLATION_FACTOR = 2f;
private static final float PROGRESS_BAR_HEIGHT = 4;
private static final float MAX_SWIPE_DISTANCE_FACTOR = .6f;
private static final int REFRESH_TRIGGER_DISTANCE = 120;
private static final int INVALID_POINTER = -1;
private SwipeProgressBar mProgressBar; //the thing that shows progress is going
private View mTarget; //the content that gets pulled down
private View mScrollTarget;
private int mOriginalOffsetTop;
private OnRefreshListener mListener;
private int mFrom;
private boolean mRefreshing = false;
private int mTouchSlop;
private float mDistanceToTriggerSync = -1;
private int mMediumAnimationDuration;
private float mFromPercentage = 0;
private float mCurrPercentage = 0;
private int mProgressBarHeight;
private int mCurrentTargetOffsetTop;
private boolean mContentPullEnabled = true;
private float mInitialMotionY;
private float mLastMotionY;
private boolean mIsBeingDragged;
private int mActivePointerId = INVALID_POINTER;
// Target is returning to its start offset because it was cancelled or a
// refresh was triggered.
private boolean mReturningToStart;
private final DecelerateInterpolator mDecelerateInterpolator;
private final AccelerateInterpolator mAccelerateInterpolator;
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.enabled
};
private final Animation mAnimateToStartPosition = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
int targetTop = 0;
if (mFrom != mOriginalOffsetTop) {
targetTop = (mFrom + (int)((mOriginalOffsetTop - mFrom) * interpolatedTime));
}
int offset = targetTop - mTarget.getTop();
final int currentTop = mTarget.getTop();
if (offset + currentTop < 0) {
offset = 0 - currentTop;
}
setTargetOffsetTopAndBottom(offset);
}
};
private Animation mShrinkTrigger = new Animation() {
@Override
public void applyTransformation(float interpolatedTime, Transformation t) {
float percent = mFromPercentage + ((0 - mFromPercentage) * interpolatedTime);
mProgressBar.setTriggerPercentage(percent);
}
};
private final AnimationListener mReturnToStartPositionListener = new BaseAnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
// Once the target content has returned to its start position, reset
// the target offset to 0
mCurrentTargetOffsetTop = 0;
}
};
private final AnimationListener mShrinkAnimationListener = new BaseAnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
mCurrPercentage = 0;
}
};
private final Runnable mReturnToStartPosition = new Runnable() {
@Override
public void run() {
mReturningToStart = true;
animateOffsetToStartPosition(mCurrentTargetOffsetTop + getPaddingTop(),
mReturnToStartPositionListener);
}
};
// Cancel the refresh gesture and animate everything back to its original state.
private final Runnable mCancel = new Runnable() {
@Override
public void run() {
mReturningToStart = true;
// Timeout fired since the user last moved their finger; animate the
// trigger to 0 and put the target back at its original position
if (mProgressBar != null) {
mFromPercentage = mCurrPercentage;
mShrinkTrigger.setDuration(mMediumAnimationDuration);
mShrinkTrigger.setAnimationListener(mShrinkAnimationListener);
mShrinkTrigger.reset();
mShrinkTrigger.setInterpolator(mDecelerateInterpolator);
startAnimation(mShrinkTrigger);
}
animateOffsetToStartPosition(mCurrentTargetOffsetTop + getPaddingTop(),
mReturnToStartPositionListener);
}
};
/**
* Simple constructor to use when creating a SwipeRefreshLayout from code.
* @param context
*/
public PkSwipeRefreshLayout(Context context) {
this(context, null);
}
/**
* Constructor that is called when inflating SwipeRefreshLayout from XML.
* @param context
* @param attrs
*/
public PkSwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
mMediumAnimationDuration = getResources().getInteger(
android.R.integer.config_mediumAnimTime);
setWillNotDraw(false);
mProgressBar = new SwipeProgressBar(this);
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mProgressBarHeight = (int) (metrics.density * PROGRESS_BAR_HEIGHT);
mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR);
mAccelerateInterpolator = new AccelerateInterpolator(ACCELERATE_INTERPOLATION_FACTOR);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
setEnabled(a.getBoolean(0, true));
a.recycle();
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
removeCallbacks(mCancel);
removeCallbacks(mReturnToStartPosition);
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
removeCallbacks(mReturnToStartPosition);
removeCallbacks(mCancel);
}
private void animateOffsetToStartPosition(int from, AnimationListener listener) {
mFrom = from;
mAnimateToStartPosition.reset();
mAnimateToStartPosition.setDuration(mMediumAnimationDuration);
mAnimateToStartPosition.setAnimationListener(listener);
mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator);
mTarget.startAnimation(mAnimateToStartPosition);
}
/**
* Set whether or not to pull child views while swiping.
* @param contentPullEnabled
*/
public void setContentPullEnabled(boolean contentPullEnabled) {
this.mContentPullEnabled = contentPullEnabled;
}
public void setScrollTarget(View target) {
this.mScrollTarget = target;
}
/**
* Set the listener to be notified when a refresh is triggered via the swipe
* gesture.
*/
public void setOnRefreshListener(OnRefreshListener listener) {
mListener = listener;
}
private void setTriggerPercentage(float percent) {
if (percent == 0f) {
// No-op. A null trigger means it's uninitialized, and setting it to zero-percent
// means we're trying to reset state, so there's nothing to reset in this case.
mCurrPercentage = 0;
return;
}
mCurrPercentage = percent;
mProgressBar.setTriggerPercentage(percent);
}
/**
* Notify the widget that refresh state has changed. Do not call this when
* refresh is triggered by a swipe gesture.
*
* @param refreshing Whether or not the view should show refresh progress.
*/
public void setRefreshing(boolean refreshing) {
if (mRefreshing != refreshing) {
ensureTarget();
mCurrPercentage = 0;
mRefreshing = refreshing;
if (mRefreshing) {
mProgressBar.start();
} else {
mProgressBar.stop();
}
}
}
/**
* @deprecated Use {@link #setColorSchemeResources(int, int, int, int)}
*/
@Deprecated
public void setColorScheme(int colorRes1, int colorRes2, int colorRes3, int colorRes4) {
setColorSchemeResources(colorRes1, colorRes2, colorRes3, colorRes4);
}
/**
* Set the four colors used in the progress animation from color resources.
* The first color will also be the color of the bar that grows in response
* to a user swipe gesture.
*/
public void setColorSchemeResources(int colorRes1, int colorRes2, int colorRes3,
int colorRes4) {
final Resources res = getResources();
setColorSchemeColors(res.getColor(colorRes1), res.getColor(colorRes2),
res.getColor(colorRes3), res.getColor(colorRes4));
}
/**
* Set the four colors used in the progress animation. The first color will
* also be the color of the bar that grows in response to a user swipe
* gesture.
*/
public void setColorSchemeColors(int color1, int color2, int color3, int color4) {
ensureTarget();
mProgressBar.setColorScheme(color1, color2, color3, color4);
}
/**
* @return Whether the SwipeRefreshWidget is actively showing refresh
* progress.
*/
public boolean isRefreshing() {
return mRefreshing;
}
private void ensureTarget() {
// Don't bother getting the parent height if the parent hasn't been laid out yet.
if (mTarget == null) {
if (getChildCount() > 1 && !isInEditMode()) {
throw new IllegalStateException(
"SwipeRefreshLayout can host only one direct child");
}
mTarget = getChildAt(0);
mOriginalOffsetTop = mTarget.getTop() + getPaddingTop();
}
if (mDistanceToTriggerSync == -1) {
if (getParent() != null && ((View)getParent()).getHeight() > 0) {
final DisplayMetrics metrics = getResources().getDisplayMetrics();
mDistanceToTriggerSync = (int) Math.min(
((View) getParent()) .getHeight() * MAX_SWIPE_DISTANCE_FACTOR,
REFRESH_TRIGGER_DISTANCE * metrics.density);
}
}
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
mProgressBar.draw(canvas);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int width = getMeasuredWidth();
final int height = getMeasuredHeight();
mProgressBar.setBounds(0, 0, width, mProgressBarHeight);
if (getChildCount() == 0) {
return;
}
final View child = getChildAt(0);
final int childLeft = getPaddingLeft();
final int childTop = mCurrentTargetOffsetTop + getPaddingTop();
final int childWidth = width - getPaddingLeft() - getPaddingRight();
final int childHeight = height - getPaddingTop() - getPaddingBottom();
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (getChildCount() > 1 && !isInEditMode()) {
throw new IllegalStateException("SwipeRefreshLayout can host only one direct child");
}
if (getChildCount() > 0) {
getChildAt(0).measure(
MeasureSpec.makeMeasureSpec(
getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(
getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
MeasureSpec.EXACTLY));
}
}
/**
* @return Whether it is possible for the child view of this layout to
* scroll up. Override this if the child view is a custom view.
*/
public boolean canChildScrollUp() {
if(mScrollTarget != null) {
if (mScrollTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mScrollTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
}
else
return mScrollTarget.getScrollY() != 0.0;
}
if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
ensureTarget();
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp()) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
mLastMotionY = mInitialMotionY = ev.getY();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
mCurrPercentage = 0;
break;
case MotionEvent.ACTION_MOVE:
if (mActivePointerId == INVALID_POINTER) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id.");
return false;
}
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex < 0) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
return false;
}
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = y - mInitialMotionY;
if (yDiff > mTouchSlop) {
mLastMotionY = y;
mIsBeingDragged = true;
}
break;
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsBeingDragged = false;
mCurrPercentage = 0;
mActivePointerId = INVALID_POINTER;
break;
}
return mIsBeingDragged;
}
@Override
public void requestDisallowInterceptTouchEvent(boolean b) {
// Nope.
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
if (mReturningToStart && action == MotionEvent.ACTION_DOWN) {
mReturningToStart = false;
}
if (!isEnabled() || mReturningToStart || canChildScrollUp()) {
// Fail fast if we're not in a state where a swipe is possible
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN:
mLastMotionY = mInitialMotionY = ev.getY();
mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
mIsBeingDragged = false;
mCurrPercentage = 0;
break;
case MotionEvent.ACTION_MOVE:
final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
if (pointerIndex < 0) {
Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id.");
return false;
}
final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = y - mInitialMotionY;
if (!mIsBeingDragged && yDiff > mTouchSlop) {
mIsBeingDragged = true;
}
if (mIsBeingDragged) {
// User velocity passed min velocity; trigger a refresh
if (yDiff > mDistanceToTriggerSync) {
// User movement passed distance; trigger a refresh
startRefresh();
} else {
// Just track the user's movement
setTriggerPercentage(
mAccelerateInterpolator.getInterpolation(
yDiff / mDistanceToTriggerSync));
updateContentOffsetTop((int) (yDiff));
if (mLastMotionY > y && mTarget.getTop() == getPaddingTop()) {
// If the user puts the view back at the top, we
// don't need to. This shouldn't be considered
// cancelling the gesture as the user can restart from the top.
removeCallbacks(mCancel);
} else {
updatePositionTimeout();
}
}
mLastMotionY = y;
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
final int index = MotionEventCompat.getActionIndex(ev);
mLastMotionY = MotionEventCompat.getY(ev, index);
mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mIsBeingDragged = false;
mCurrPercentage = 0;
mActivePointerId = INVALID_POINTER;
return false;
}
return true;
}
private void startRefresh() {
removeCallbacks(mCancel);
mReturnToStartPosition.run();
setRefreshing(true);
mListener.onRefresh();
}
private void updateContentOffsetTop(int targetTop) {
// Prevent content animation is not enabled
if(!mContentPullEnabled) {
setTargetOffsetTopAndBottom (0);
return;
}
final int currentTop = mTarget.getTop();
if (targetTop > mDistanceToTriggerSync) {
targetTop = (int) mDistanceToTriggerSync;
} else if (targetTop < 0) {
targetTop = 0;
}
setTargetOffsetTopAndBottom(targetTop - currentTop);
}
private void setTargetOffsetTopAndBottom(int offset) {
mTarget.offsetTopAndBottom(offset);
mCurrentTargetOffsetTop = mTarget.getTop();
}
private void updatePositionTimeout() {
removeCallbacks(mCancel);
postDelayed(mCancel, RETURN_TO_ORIGINAL_POSITION_TIMEOUT);
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = MotionEventCompat.getActionIndex(ev);
final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionY = MotionEventCompat.getY(ev, newPointerIndex);
mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
}
}
/**
* Classes that wish to be notified when the swipe gesture correctly
* triggers a refresh should implement this interface.
*/
public interface OnRefreshListener {
public void onRefresh();
}
/**
* Simple AnimationListener to avoid having to implement unneeded methods in
* AnimationListeners.
*/
private class BaseAnimationListener implements AnimationListener {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
}
}
| |
/*
* @(#)Reversi.java 2005/11/19
*
* Part of the reversi console application that uses the strategy game framework.
* Copyright (c) Michael Patricios, lurgee.net.
*
*/
package net.lurgee.reversi.console;
import java.util.ArrayList;
import net.lurgee.common.console.AbstractCompetitor;
import net.lurgee.common.console.AbstractGame;
import net.lurgee.common.console.ComputerCompetitor;
import net.lurgee.reversi.Colour;
import net.lurgee.reversi.ReversiBoard;
import net.lurgee.reversi.ReversiEvaluator;
import net.lurgee.reversi.ReversiLibrary;
import net.lurgee.reversi.ReversiMoveFactory;
import net.lurgee.reversi.ReversiMoveRanker;
import net.lurgee.reversi.ReversiPlayer;
import net.lurgee.sgf.AbstractSearcher;
import net.lurgee.sgf.Evaluator;
import net.lurgee.sgf.GameContext;
import net.lurgee.sgf.Library;
import net.lurgee.sgf.MoveRanker;
import net.lurgee.sgf.ObjectPool;
import net.lurgee.sgf.Player;
import net.lurgee.sgf.SearchProgressListener;
/**
* Main class for the reversi console application.
* @author mpatric
*/
public class ReversiGame extends AbstractGame {
private static final ReversiPlayer BLACK_PLAYER = ReversiPlayer.getInstance(Colour.BLACK);
private static final ReversiPlayer WHITE_PLAYER = ReversiPlayer.getInstance(Colour.WHITE);
private static final String NA = "N/A";
private ReversiGameStats gameStats = new ReversiGameStats();
protected String getGameName() {
return "Reversi";
}
protected void init() {
Player[] reversiPlayers = new Player[] {BLACK_PLAYER, WHITE_PLAYER};
ObjectPool reversiBoardPool = new ObjectPool(ExtendedReversiBoard.class);
ReversiMoveFactory reversiMoveFactory = new ReversiMoveFactory();
gameContext = new GameContext(reversiPlayers, reversiBoardPool, reversiMoveFactory, true);
board = gameContext.checkOutBoard();
addCompetitor(configureCompetitor("BLACK", Colour.BLACK));
addCompetitor(configureCompetitor("WHITE", Colour.WHITE));
}
protected void done() {
gameContext.checkInBoard(board);
}
protected void printCurrentState() {
output.print((System.currentTimeMillis() - startTime) + "ms");
output.print("; Score: ");
output.print(BLACK_PLAYER.getName() + " (" + BLACK_PLAYER.getSymbol() + "): " + ((ReversiBoard) board).getCount(Colour.BLACK));
output.print(", " + WHITE_PLAYER.getName() + " (" + WHITE_PLAYER.getSymbol() + "): " + ((ReversiBoard) board).getCount(Colour.WHITE));
output.println();
output.println(board.toString());
}
protected void printEndGameState(AbstractCompetitor startCompetitor) {
printCurrentState();
int blackScore = ((ReversiBoard) board).getCount(Colour.BLACK);
int whiteScore = ((ReversiBoard) board).getCount(Colour.WHITE);
printResults(blackScore, whiteScore);
AbstractCompetitor blackCompetitor = getCompetitor(BLACK_PLAYER);
AbstractCompetitor whiteCompetitor = getCompetitor(WHITE_PLAYER);
int startColour = ((ReversiPlayer) startCompetitor.getPlayer()).getColour();
int opening = blackCompetitor instanceof ComputerCompetitor ? ((ReversiLibrary)((ComputerCompetitor) blackCompetitor).getLibrary()).getOpeningPlayed() : ReversiLibrary.NONE;
gameStats.addStat(((ReversiPlayer) blackCompetitor.getPlayer()), startColour == Colour.BLACK, blackScore > whiteScore, blackCompetitor.getMovesPlayed(), blackScore, blackScore + whiteScore < 64, opening);
opening = whiteCompetitor instanceof ComputerCompetitor ? ((ReversiLibrary)((ComputerCompetitor) whiteCompetitor).getLibrary()).getOpeningPlayed() : ReversiLibrary.NONE;
gameStats.addStat(((ReversiPlayer) whiteCompetitor.getPlayer()), startColour == Colour.WHITE, whiteScore > blackScore, whiteCompetitor.getMovesPlayed(), whiteScore, blackScore + whiteScore < 64, opening);
}
private void printResults(int blackScore, int whiteScore) {
boolean early = (blackScore + whiteScore < 64);
if (blackScore > whiteScore) {
printResult(getCompetitor(BLACK_PLAYER), early);
} else if (blackScore < whiteScore) {
printResult(getCompetitor(WHITE_PLAYER), early);
} else {
output.print("Draw");
}
}
private void printResult(AbstractCompetitor winner, boolean early) {
String winnerText = winner.getPlayer() + " (" + winner.getPlayer().getSymbol() + ")";
output.print(winnerText + " wins");
if (early) output.println(" early");
else output.println();
}
protected void printStats(long startTime, long endTime) {
AbstractCompetitor blackCompetitor = getCompetitor(BLACK_PLAYER);
AbstractCompetitor whiteCompetitor = getCompetitor(WHITE_PLAYER);
ReversiPlayer blackPlayer = ((ReversiPlayer) blackCompetitor.getPlayer());
ReversiPlayer whitePlayer = ((ReversiPlayer) whiteCompetitor.getPlayer());
int totalGames = gameStats.getGameCount();
output.println();
printStat("STATS", BLACK_PLAYER.getName() + " (" + BLACK_PLAYER.getSymbol() + ")", WHITE_PLAYER.getName() + " (" + WHITE_PLAYER.getSymbol() + ")");
printStat("Total wins", valueAndPercentage(gameStats.countWins(blackPlayer), totalGames),
valueAndPercentage(gameStats.countWins(whitePlayer), totalGames));
printStat("Wins when starting", valueAndPercentage(gameStats.countStartWins(blackPlayer), totalGames),
valueAndPercentage(gameStats.countStartWins(whitePlayer), totalGames));
printStat("Early wins", Integer.toString(gameStats.countEarlyWins(blackPlayer)),
Integer.toString(gameStats.countEarlyWins(whitePlayer)));
printStat("Average score", Float.toString(gameStats.calculateAverageScore(blackPlayer)),
Float.toString(gameStats.calculateAverageScore(whitePlayer)));
printStat("Parallel openings", Integer.toString(gameStats.countOpenings(blackPlayer, ReversiLibrary.PARALLEL)),
Integer.toString(gameStats.countOpenings(whitePlayer, ReversiLibrary.PARALLEL)));
printStat("Diagonal openings", Integer.toString(gameStats.countOpenings(blackPlayer, ReversiLibrary.DIAGONAL)),
Integer.toString(gameStats.countOpenings(whitePlayer, ReversiLibrary.DIAGONAL)));
printStat("Perpendicular openings", Integer.toString(gameStats.countOpenings(blackPlayer, ReversiLibrary.PERPENDICULAR)),
Integer.toString(gameStats.countOpenings(whitePlayer, ReversiLibrary.PERPENDICULAR)));
printStat("Moves considered", gameStats.getMovesConsidered(blackPlayer), gameStats.getMovesConsidered(whitePlayer));
printStat("Moves discarded", gameStats.getMovesConsideredInIncompleteIterations(blackPlayer), gameStats.getMovesConsideredInIncompleteIterations(whitePlayer));
printStat("Moves played", Integer.toString(gameStats.countMovesPlayed(blackPlayer)), Integer.toString(gameStats.countMovesPlayed(whitePlayer)));
printStat("Evaluations done", gameStats.getEvaluationsDone(blackPlayer), gameStats.getEvaluationsDone(whitePlayer));
printStat("Evaluations discarded", gameStats.getEvaluationsDoneInIncompleteIterations(blackPlayer), gameStats.getEvaluationsDoneInIncompleteIterations(whitePlayer));
printStat("Search depths", gameStats.getSearchDepths(blackPlayer), gameStats.getSearchDepths(whitePlayer));
printStat("Searcher", blackCompetitor instanceof ComputerCompetitor ? ((ComputerCompetitor) blackCompetitor).getSearcher().toString() : NA,
whiteCompetitor instanceof ComputerCompetitor ? ((ComputerCompetitor) whiteCompetitor).getSearcher().toString() : NA);
printStat("Evaluator", blackCompetitor instanceof ComputerCompetitor ? ((ComputerCompetitor) blackCompetitor).getEvaluator().toString() : NA,
whiteCompetitor instanceof ComputerCompetitor ? ((ComputerCompetitor) whiteCompetitor).getEvaluator().toString() : NA);
printStat("Tree depth", blackCompetitor instanceof ComputerCompetitor ? ((ComputerCompetitor) blackCompetitor).getThinker().getDepth() + "" : NA,
whiteCompetitor instanceof ComputerCompetitor ? ((ComputerCompetitor) whiteCompetitor).getThinker().getDepth() + "" : NA);
printStat("Games played", totalGames + "", "");
printStat("Time taken", (endTime - startTime) + " ms", "");
printStat("Scores", gameStats.listScores(blackPlayer, whitePlayer), "");
}
private void printStat(String message, String blackValue, String whiteValue) {
output.printAndPad(message, 24);
output.printAndPad(blackValue, 21);
output.printAndPad(whiteValue, 21);
output.println();
}
private String valueAndPercentage(int value, int total) {
return value + " (" + ((100 * value) / total) + "%)";
}
private AbstractCompetitor configureCompetitor(String playerName, int colour) {
AbstractCompetitor competitor = null;
ArrayList<String> list = new ArrayList<String>();
list.add("Computer (default)");
list.add("Human");
int competitorType = input.selectFromList(playerName, list, 1);
int searchDepth = 0;
if (competitorType == 1) {
searchDepth = (int) input.enterInteger("Search depth (5)", 5, 1, 16);
}
ReversiPlayer player = ReversiPlayer.getInstance(colour);
SearchProgressListener searchProgressListener = gameStats.registerPlayer(player, searchDepth);
if (competitorType == 1) {
list.clear();
list.add("Negascout (default)");
list.add("Negamax");
boolean useNegamax = (input.selectFromList("Searcher to use", list, 1) != 1);
list.clear();
list.add("Yes (default)");
list.add("No");
boolean useKillerHeuristic = (input.selectFromList("Use killer move heuristic", list, 1) == 1);
list.clear();
list.add("Yes (default)");
list.add("No");
boolean useIterativeDeepening = (input.selectFromList("Iterative deeping on search", list, 1) == 1);
long evaluationThreshold = 0;
if (useIterativeDeepening) {
evaluationThreshold = input.enterInteger("Iterative deepening evaluation threshold [" + AbstractSearcher.NO_EVALUATION_THRESHOLD + " = none] (" + AbstractSearcher.NO_EVALUATION_THRESHOLD + ")", AbstractSearcher.NO_EVALUATION_THRESHOLD, 0, 10000000);
}
list.clear();
list.add("Standard (default)");
list.add("Alternative");
boolean useAlternativeEvaluator = (input.selectFromList("Evaluator to use", list, 1) != 1);
list.clear();
list.add("Weighted random (default)");
list.add("Parallel");
list.add("Diagonal");
list.add("Perpendicular");
int useOpening = input.selectFromList("Library opening to use", list, 1) - 2;
// create competitor
Evaluator evaluator;
if (useAlternativeEvaluator) {
evaluator = new AlternativeEvaluator();
} else {
evaluator = new ReversiEvaluator();
}
Library library = new ReversiLibrary((GameContext) gameContext, useOpening);
MoveRanker moveRanker = new ReversiMoveRanker();
competitor = new ComputerCompetitor(gameContext, moveRanker, evaluator, library, player, searchProgressListener, useNegamax, useKillerHeuristic, useIterativeDeepening, true);
((ComputerCompetitor) competitor).setEvaluationThreshold(evaluationThreshold);
((ComputerCompetitor) competitor).setTreeDepth(searchDepth);
} else {
competitor = new ReversiHumanCompetitor(gameContext, player);
}
return competitor;
}
public static void main(String[] args) {
ReversiGame reversi = new ReversiGame();
reversi.run();
}
}
| |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.formatter.java;
import com.intellij.formatting.*;
import com.intellij.formatting.alignment.AlignmentStrategy;
import com.intellij.formatting.blocks.CStyleCommentBlock;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.formatter.common.AbstractBlock;
import com.intellij.psi.formatter.java.wrap.JavaWrapManager;
import com.intellij.psi.formatter.java.wrap.ReservedWrapsProvider;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.codeStyle.ShiftIndentInsideHelper;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.impl.source.tree.java.ClassElement;
import com.intellij.psi.jsp.JspElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.intellij.psi.formatter.java.JavaFormatterUtil.getWrapType;
import static com.intellij.psi.formatter.java.MultipleFieldDeclarationHelper.findLastFieldInGroup;
public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock, ReservedWrapsProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.AbstractJavaBlock");
@NotNull protected final CommonCodeStyleSettings mySettings;
@NotNull protected final JavaCodeStyleSettings myJavaSettings;
protected final CommonCodeStyleSettings.IndentOptions myIndentSettings;
private final Indent myIndent;
protected Indent myChildIndent;
protected Alignment myChildAlignment;
protected boolean myUseChildAttributes;
@NotNull protected final AlignmentStrategy myAlignmentStrategy;
private boolean myIsAfterClassKeyword;
protected Alignment myReservedAlignment;
protected Alignment myReservedAlignment2;
private final JavaWrapManager myWrapManager;
private Map<IElementType, Wrap> myPreferredWraps;
private AbstractJavaBlock myParentBlock;
private final FormattingMode myFormattingMode;
private final BlockFactory myBlockFactory = new BlockFactory() {
@Override
public Block createBlock(ASTNode node, Indent indent, Alignment alignment, Wrap wrap, @NotNull FormattingMode formattingMode) {
return new SimpleJavaBlock(node, wrap, AlignmentStrategy.wrap(alignment), indent, mySettings, myJavaSettings, formattingMode);
}
@Override
public CommonCodeStyleSettings getSettings() {
return mySettings;
}
@Override
public JavaCodeStyleSettings getJavaSettings() {
return myJavaSettings;
}
@Override
public FormattingMode getFormattingMode() {
return myFormattingMode;
}
};
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
final Alignment alignment,
final Indent indent,
@NotNull final CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@NotNull FormattingMode formattingMode)
{
this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, AlignmentStrategy.wrap(alignment), formattingMode);
}
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
@NotNull final AlignmentStrategy alignmentStrategy,
final Indent indent,
@NotNull final CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@NotNull FormattingMode formattingMode)
{
this(node, wrap, indent, settings, javaSettings, JavaWrapManager.INSTANCE, alignmentStrategy, formattingMode);
}
private AbstractJavaBlock(@NotNull ASTNode ignored,
@NotNull CommonCodeStyleSettings commonSettings,
@NotNull JavaCodeStyleSettings javaSettings,
@NotNull FormattingMode formattingMode) {
super(ignored, null, null);
mySettings = commonSettings;
myJavaSettings = javaSettings;
myIndentSettings = commonSettings.getIndentOptions();
myIndent = null;
myWrapManager = JavaWrapManager.INSTANCE;
myAlignmentStrategy = AlignmentStrategy.getNullStrategy();
myFormattingMode = formattingMode;
}
protected AbstractJavaBlock(@NotNull final ASTNode node,
final Wrap wrap,
final Indent indent,
@NotNull final CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
final JavaWrapManager wrapManager,
@NotNull final AlignmentStrategy alignmentStrategy,
@NotNull final FormattingMode formattingMode) {
super(node, wrap, createBlockAlignment(alignmentStrategy, node));
mySettings = settings;
myJavaSettings = javaSettings;
myIndentSettings = settings.getIndentOptions();
myIndent = indent;
myWrapManager = wrapManager;
myAlignmentStrategy = alignmentStrategy;
myFormattingMode = formattingMode;
}
@Nullable
private static Alignment createBlockAlignment(@NotNull AlignmentStrategy strategy, @NotNull ASTNode node) {
// There is a possible case that 'implements' section is incomplete (e.g. ends with comma). We may want to align lbrace
// to the first implemented interface reference then.
if (node.getElementType() == JavaElementType.IMPLEMENTS_LIST) {
return null;
}
return strategy.getAlignment(node.getElementType());
}
@NotNull
public Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
@Nullable Wrap wrap,
Alignment alignment,
@NotNull FormattingMode formattingMode) {
return createJavaBlock(child, settings, javaSettings,indent, wrap, AlignmentStrategy.wrap(alignment), formattingMode);
}
@NotNull
public Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
final Indent indent,
@Nullable Wrap wrap,
@NotNull AlignmentStrategy alignmentStrategy,
@NotNull FormattingMode formattingMode) {
return createJavaBlock(child, settings, javaSettings, indent, wrap, alignmentStrategy, -1, formattingMode);
}
@NotNull
private Block createJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
Wrap wrap,
@NotNull AlignmentStrategy alignmentStrategy,
int startOffset,
@NotNull FormattingMode formattingMode) {
Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child, getJavaIndentOptions(settings)) : indent;
IElementType elementType = child.getElementType();
Alignment alignment = alignmentStrategy.getAlignment(elementType);
PsiElement childPsi = child.getPsi();
if (childPsi instanceof PsiWhiteSpace) {
String text = child.getText();
int start = CharArrayUtil.shiftForward(text, 0, " \t\n");
int end = CharArrayUtil.shiftBackward(text, text.length() - 1, " \t\n") + 1;
LOG.assertTrue(start < end);
TextRange range = new TextRange(start + child.getStartOffset(), end + child.getStartOffset());
return new PartialWhitespaceBlock(child, range, wrap, alignment, actualIndent, settings, javaSettings, myFormattingMode);
}
if (childPsi instanceof PsiClass || childPsi instanceof PsiJavaModule) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings, formattingMode);
}
if (child.getElementType() == JavaElementType.METHOD) {
return new BlockContainingJavaBlock(child, actualIndent, alignmentStrategy, mySettings, myJavaSettings, formattingMode);
}
if (isBlockType(elementType)) {
return new BlockContainingJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings, formattingMode);
}
if (isStatement(child, child.getTreeParent())) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings, myFormattingMode);
}
if (!isBuildIndentsOnly() &&
child instanceof PsiComment &&
child instanceof PsiLanguageInjectionHost &&
InjectedLanguageUtil.hasInjections((PsiLanguageInjectionHost)child)) {
return new CommentWithInjectionBlock(child, wrap, alignment, indent, settings, javaSettings, formattingMode);
}
if (child instanceof LeafElement || childPsi instanceof PsiJavaModuleReferenceElement) {
if (child.getElementType() == JavaTokenType.C_STYLE_COMMENT) {
return new CStyleCommentBlock(child, actualIndent);
}
final LeafBlock block = new LeafBlock(child, wrap, alignment, actualIndent);
block.setStartOffset(startOffset);
return block;
}
if (isLikeExtendsList(elementType)) {
return new ExtendsListBlock(child, wrap, alignmentStrategy, settings, javaSettings, formattingMode);
}
if (elementType == JavaElementType.CODE_BLOCK) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings, javaSettings, formattingMode);
}
if (elementType == JavaElementType.LABELED_STATEMENT) {
return new LabeledJavaBlock(child, wrap, alignment, actualIndent, settings, javaSettings, formattingMode);
}
if (elementType == JavaDocElementType.DOC_COMMENT) {
return new DocCommentBlock(child, wrap, alignment, actualIndent, settings, javaSettings, formattingMode);
}
final SimpleJavaBlock simpleJavaBlock = new SimpleJavaBlock(child, wrap, alignmentStrategy, actualIndent, settings, javaSettings, myFormattingMode);
simpleJavaBlock.setStartOffset(startOffset);
return simpleJavaBlock;
}
@NotNull
public static Block newJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@NotNull FormattingMode formattingMode) {
final Indent indent = getDefaultSubtreeIndent(child, getJavaIndentOptions(settings));
return newJavaBlock(child, settings, javaSettings, indent, null, AlignmentStrategy.getNullStrategy(), formattingMode);
}
@NotNull
public static Block newJavaBlock(@NotNull ASTNode child,
@NotNull CommonCodeStyleSettings settings,
@NotNull JavaCodeStyleSettings javaSettings,
@Nullable Indent indent,
@Nullable Wrap wrap,
@NotNull AlignmentStrategy strategy,
@NotNull FormattingMode formattingMode) {
return new AbstractJavaBlock(child, settings, javaSettings, formattingMode) {
@Override
protected List<Block> buildChildren() {
return null;
}
}.createJavaBlock(child, settings, javaSettings, indent, wrap, strategy, formattingMode);
}
@NotNull
private static CommonCodeStyleSettings.IndentOptions getJavaIndentOptions(CommonCodeStyleSettings settings) {
CommonCodeStyleSettings.IndentOptions indentOptions = settings.getIndentOptions();
assert indentOptions != null : "Java indent options are not initialized";
return indentOptions;
}
private static boolean isLikeExtendsList(final IElementType elementType) {
return elementType == JavaElementType.EXTENDS_LIST
|| elementType == JavaElementType.IMPLEMENTS_LIST
|| elementType == JavaElementType.THROWS_LIST;
}
private static boolean isBlockType(final IElementType elementType) {
return elementType == JavaElementType.SWITCH_STATEMENT
|| elementType == JavaElementType.FOR_STATEMENT
|| elementType == JavaElementType.WHILE_STATEMENT
|| elementType == JavaElementType.DO_WHILE_STATEMENT
|| elementType == JavaElementType.TRY_STATEMENT
|| elementType == JavaElementType.CATCH_SECTION
|| elementType == JavaElementType.IF_STATEMENT
|| elementType == JavaElementType.METHOD
|| elementType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION
|| elementType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER
|| elementType == JavaElementType.CLASS_INITIALIZER
|| elementType == JavaElementType.SYNCHRONIZED_STATEMENT
|| elementType == JavaElementType.FOREACH_STATEMENT;
}
@Nullable
private static Indent getDefaultSubtreeIndent(@NotNull ASTNode child, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) {
final ASTNode parent = child.getTreeParent();
final IElementType childNodeType = child.getElementType();
if (childNodeType == JavaElementType.ANNOTATION) {
if (parent.getPsi() instanceof PsiArrayInitializerMemberValue) {
return Indent.getNormalIndent();
}
return Indent.getNoneIndent();
}
final ASTNode prevElement = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (prevElement != null && prevElement.getElementType() == JavaElementType.MODIFIER_LIST && !isMethodParameterAnnotation(prevElement)) {
return Indent.getNoneIndent();
}
if (childNodeType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (childNodeType == JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS) return Indent.getSpaceIndent(1);
if (child.getPsi() instanceof PsiFile) return Indent.getNoneIndent();
if (parent != null) {
final Indent defaultChildIndent = getChildIndent(parent, indentOptions);
if (defaultChildIndent != null) return defaultChildIndent;
if (parent.getPsi() instanceof PsiLambdaExpression && child instanceof PsiCodeBlock) {
return Indent.getNoneIndent();
}
}
return null;
}
private static boolean isMethodParameterAnnotation(@NotNull ASTNode element) {
ASTNode parent = element.getTreeParent();
if (parent != null && parent.getElementType() == JavaElementType.PARAMETER) {
ASTNode lastChild = element.getLastChildNode();
return lastChild != null && lastChild.getElementType() == JavaElementType.ANNOTATION;
}
return false;
}
@Nullable
private static Indent getChildIndent(@NotNull ASTNode parent, @NotNull CommonCodeStyleSettings.IndentOptions indentOptions) {
final IElementType parentType = parent.getElementType();
if (parentType == JavaElementType.MODIFIER_LIST) return Indent.getNoneIndent();
if (parentType == JspElementType.JSP_CODE_BLOCK) return Indent.getNormalIndent();
if (parentType == JspElementType.JSP_CLASS_LEVEL_DECLARATION_STATEMENT) return Indent.getNormalIndent();
if (parentType == TokenType.DUMMY_HOLDER) return Indent.getNoneIndent();
if (parentType == JavaElementType.CLASS) return Indent.getNoneIndent();
if (parentType == JavaElementType.IF_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.TRY_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.CATCH_SECTION) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOR_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.FOREACH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.BLOCK_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.WHILE_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.SWITCH_STATEMENT) return Indent.getNoneIndent();
if (parentType == JavaElementType.METHOD) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_COMMENT) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (parentType == JavaDocElementType.DOC_INLINE_TAG) return Indent.getNoneIndent();
if (parentType == JavaElementType.IMPORT_LIST) return Indent.getNoneIndent();
if (parentType == JavaElementType.FIELD) return Indent.getContinuationWithoutFirstIndent(indentOptions.USE_RELATIVE_INDENTS);
if (parentType == JavaElementType.EXPRESSION_STATEMENT) return Indent.getNoneIndent();
if (SourceTreeToPsiMap.treeElementToPsi(parent) instanceof PsiFile) {
return Indent.getNoneIndent();
}
return null;
}
protected static boolean isRBrace(@NotNull final ASTNode child) {
return child.getElementType() == JavaTokenType.RBRACE;
}
@Nullable
@Override
public Spacing getSpacing(Block child1, @NotNull Block child2) {
return JavaSpacePropertyProcessor.getSpacing(child2, mySettings, myJavaSettings);
}
@Override
public ASTNode getFirstTreeNode() {
return myNode;
}
@Override
public Indent getIndent() {
return myIndent;
}
protected static boolean isStatement(final ASTNode child, @Nullable final ASTNode parentNode) {
if (parentNode != null) {
final IElementType parentType = parentNode.getElementType();
if (parentType == JavaElementType.CODE_BLOCK) return false;
final int role = ((CompositeElement)parentNode).getChildRole(child);
if (parentType == JavaElementType.IF_STATEMENT) return role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH;
if (parentType == JavaElementType.FOR_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.DO_WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentType == JavaElementType.FOREACH_STATEMENT) return role == ChildRole.LOOP_BODY;
}
return false;
}
@Nullable
protected Wrap createChildWrap() {
//when detecting indent we do not care about wraps
return isBuildIndentsOnly() ? null : myWrapManager.createChildBlockWrap(this, getSettings(), this);
}
@Nullable
protected Alignment createChildAlignment() {
IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION;
if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (myNode.getTreeParent() != null
&& myNode.getTreeParent().getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION
&& myAlignment != null) {
return myAlignment;
}
return createAlignment(mySettings.ALIGN_MULTILINE_ASSIGNMENT, null);
}
if (nodeType == JavaElementType.PARENTH_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION, null);
}
if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_TERNARY_OPERATION, null);
}
if (nodeType == JavaElementType.FOR_STATEMENT) {
return createAlignment(mySettings.ALIGN_MULTILINE_FOR, null);
}
if (nodeType == JavaElementType.EXTENDS_LIST || nodeType == JavaElementType.IMPLEMENTS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null);
}
if (nodeType == JavaElementType.THROWS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_THROWS_LIST, null);
}
if (nodeType == JavaElementType.PARAMETER_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARAMETERS, null);
}
if (nodeType == JavaElementType.RESOURCE_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_RESOURCES, null);
}
if (nodeType == JavaElementType.BINARY_EXPRESSION) {
Alignment defaultAlignment = null;
if (shouldInheritAlignment()) {
defaultAlignment = myAlignment;
}
return createAlignment(mySettings.ALIGN_MULTILINE_BINARY_OPERATION, defaultAlignment);
}
return null;
}
@Nullable
protected Alignment chooseAlignment(@Nullable Alignment alignment, @Nullable Alignment alignment2, @NotNull ASTNode child) {
if (isTernaryOperatorToken(child)) {
return alignment2;
}
return alignment;
}
private boolean isTernaryOperatorToken(@NotNull final ASTNode child) {
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.CONDITIONAL_EXPRESSION) {
IElementType childType = child.getElementType();
return childType == JavaTokenType.QUEST || childType ==JavaTokenType.COLON;
}
else {
return false;
}
}
private boolean shouldInheritAlignment() {
if (myNode instanceof PsiPolyadicExpression) {
final ASTNode treeParent = myNode.getTreeParent();
if (treeParent instanceof PsiPolyadicExpression) {
return JavaFormatterUtil.areSamePriorityBinaryExpressions(myNode, treeParent);
}
}
return false;
}
@Nullable
protected ASTNode processChild(@NotNull final List<Block> result,
@NotNull ASTNode child,
Alignment defaultAlignment,
final Wrap defaultWrap,
final Indent childIndent) {
return processChild(result, child, AlignmentStrategy.wrap(defaultAlignment), defaultWrap, childIndent, -1);
}
@Nullable
protected ASTNode processChild(@NotNull final List<Block> result,
@NotNull ASTNode child,
@NotNull AlignmentStrategy alignmentStrategy,
@Nullable final Wrap defaultWrap,
final Indent childIndent) {
return processChild(result, child, alignmentStrategy, defaultWrap, childIndent, -1);
}
@Nullable
protected ASTNode processChild(@NotNull final List<Block> result,
@NotNull ASTNode child,
@NotNull AlignmentStrategy alignmentStrategy,
final Wrap defaultWrap,
Indent childIndent,
int childOffset) {
final IElementType childType = child.getElementType();
if (childType == JavaTokenType.CLASS_KEYWORD || childType == JavaTokenType.INTERFACE_KEYWORD) {
myIsAfterClassKeyword = true;
}
if (childType == JavaElementType.METHOD_CALL_EXPRESSION) {
Alignment alignment = shouldAlignChild(child) ? alignmentStrategy.getAlignment(childType) : null;
result.add(createMethodCallExpressionBlock(child, arrangeChildWrap(child, defaultWrap), alignment, childIndent));
}
else {
IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.POLYADIC_EXPRESSION) nodeType = JavaElementType.BINARY_EXPRESSION;
if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ARRAY_INITIALIZER_EXPRESSION) {
ArrayInitializerBlocksBuilder builder = new ArrayInitializerBlocksBuilder(myNode, myBlockFactory);
List<Block> newlyCreated = builder.buildBlocks();
child = myNode.getLastChildNode();
result.addAll(newlyCreated);
}
else if (childType == JavaTokenType.LBRACE && nodeType == JavaElementType.ANNOTATION_ARRAY_INITIALIZER) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
child = processParenthesisBlock(JavaTokenType.LBRACE, JavaTokenType.RBRACE,
result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.EXPRESSION_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
if (mySettings.PREFER_PARAMETERS_WRAP && !isInsideMethodCall(myNode.getPsi())) {
wrap.ignoreParentWraps();
}
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARAMETER_LIST) {
ASTNode parent = myNode.getTreeParent();
boolean isLambdaParameterList = parent != null && parent.getElementType() == JavaElementType.LAMBDA_EXPRESSION;
Wrap wrapToUse = isLambdaParameterList ? null : getMethodParametersWrap();
WrappingStrategy wrapStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(wrapToUse);
child = processParenthesisBlock(result, child, wrapStrategy, mySettings.ALIGN_MULTILINE_PARAMETERS);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.RESOURCE_LIST) {
Wrap wrap = Wrap.createWrap(getWrapType(mySettings.RESOURCE_LIST_WRAP), false);
child = processParenthesisBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_RESOURCES);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.ANNOTATION_PARAMETER_LIST) {
AnnotationInitializerBlocksBuilder builder = new AnnotationInitializerBlocksBuilder(myNode, myBlockFactory);
List<Block> newlyCreated = builder.buildBlocks();
child = myNode.getLastChildNode();
result.addAll(newlyCreated);
}
else if (childType == JavaTokenType.LPARENTH && nodeType == JavaElementType.PARENTH_EXPRESSION) {
child = processParenthesisBlock(result, child,
WrappingStrategy.DO_NOT_WRAP,
mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION);
}
else if (childType == JavaElementType.ENUM_CONSTANT && myNode instanceof ClassElement) {
child = processEnumBlock(result, child, ((ClassElement)myNode).findEnumConstantListDelimiterPlace());
}
else if (mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE && isTernaryOperationSign(child)) {
child = processTernaryOperationRange(result, child, defaultWrap, childIndent);
}
else if (childType == JavaElementType.FIELD) {
child = processField(result, child, alignmentStrategy, defaultWrap, childIndent);
}
else if (childType == JavaElementType.LOCAL_VARIABLE
|| childType == JavaElementType.DECLARATION_STATEMENT
&& (nodeType == JavaElementType.METHOD || nodeType == JavaElementType.CODE_BLOCK))
{
result.add(new SimpleJavaBlock(child, defaultWrap, alignmentStrategy, childIndent, mySettings, myJavaSettings, myFormattingMode));
}
else if (childType == JavaElementType.METHOD) {
Wrap wrap = arrangeChildWrap(child, defaultWrap);
Block block = createJavaBlock(child, mySettings, myJavaSettings, childIndent, wrap, alignmentStrategy, myFormattingMode);
result.add(block);
}
else {
Alignment alignment = alignmentStrategy.getAlignment(childType);
ChildAttributes delegateAttributes = getDelegateAttributes(result);
if (delegateAttributes != null) {
alignment = delegateAttributes.getAlignment();
if (delegateAttributes.getChildIndent() != null) {
childIndent = delegateAttributes.getChildIndent();
}
}
AlignmentStrategy alignmentStrategyToUse = shouldAlignChild(child)
? AlignmentStrategy.wrap(alignment)
: AlignmentStrategy.getNullStrategy();
if (myAlignmentStrategy.getAlignment(nodeType, childType) != null &&
(nodeType == JavaElementType.IMPLEMENTS_LIST || nodeType == JavaElementType.CLASS)) {
alignmentStrategyToUse = myAlignmentStrategy;
}
Wrap wrap = arrangeChildWrap(child, defaultWrap);
Block block = createJavaBlock(child, mySettings, myJavaSettings, childIndent, wrap, alignmentStrategyToUse, childOffset, myFormattingMode);
if (block instanceof AbstractJavaBlock) {
final AbstractJavaBlock javaBlock = (AbstractJavaBlock)block;
if (nodeType == JavaElementType.METHOD_CALL_EXPRESSION && childType == JavaElementType.REFERENCE_EXPRESSION ||
nodeType == JavaElementType.REFERENCE_EXPRESSION && childType == JavaElementType.METHOD_CALL_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap(nodeType), nodeType);
javaBlock.setReservedWrap(getReservedWrap(childType), childType);
}
else if (nodeType == JavaElementType.BINARY_EXPRESSION) {
javaBlock.setReservedWrap(defaultWrap, nodeType);
}
}
result.add(block);
}
}
return child;
}
@Nullable
private ChildAttributes getDelegateAttributes(@NotNull List<Block> result) {
if (FormattingMode.ADJUST_INDENT_ON_ENTER.equals(myFormattingMode) && !result.isEmpty()) {
final int lastIndex = result.size() - 1;
Block lastBlock = result.get(lastIndex);
if (lastBlock.isIncomplete()) {
return lastBlock.getChildAttributes(lastBlock.getSubBlocks().size());
}
}
return null;
}
private static boolean isAfterErrorElement(@NotNull ASTNode currNode) {
ASTNode prev = currNode.getTreePrev();
while (prev != null && (prev instanceof PsiWhiteSpace || prev.getTextLength() == 0)) {
if (prev instanceof PsiErrorElement) return true;
prev = prev.getTreePrev();
}
return false;
}
private static boolean isInsideMethodCall(@NotNull PsiElement element) {
PsiElement e = element.getParent();
int parentsVisited = 0;
while (e != null && !(e instanceof PsiStatement) && parentsVisited < 5) {
if (e instanceof PsiExpressionList) {
return true;
}
e = e.getParent();
parentsVisited++;
}
return false;
}
@NotNull
private Wrap getMethodParametersWrap() {
Wrap preferredWrap = getModifierListWrap();
if (preferredWrap == null) {
return Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
} else {
return Wrap.createChildWrap(preferredWrap, getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
}
}
@Nullable
private Wrap getModifierListWrap() {
AbstractJavaBlock parentBlock = getParentBlock();
if (parentBlock != null) {
return parentBlock.getReservedWrap(JavaElementType.MODIFIER_LIST);
}
return null;
}
private ASTNode processField(@NotNull final List<Block> result,
ASTNode child,
@NotNull final AlignmentStrategy alignmentStrategy,
final Wrap defaultWrap,
final Indent childIndent) {
ASTNode lastFieldInGroup = findLastFieldInGroup(child);
if (lastFieldInGroup == child) {
result.add(createJavaBlock(child, getSettings(), myJavaSettings, childIndent, arrangeChildWrap(child, defaultWrap), alignmentStrategy, myFormattingMode));
return child;
}
else {
final ArrayList<Block> localResult = new ArrayList<>();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
localResult.add(createJavaBlock(
child, getSettings(), myJavaSettings,
Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS),
arrangeChildWrap(child, defaultWrap),
alignmentStrategy,
myFormattingMode
)
);
}
if (child == lastFieldInGroup) break;
child = child.getTreeNext();
}
if (!localResult.isEmpty()) {
result.add(new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, childIndent, null));
}
return lastFieldInGroup;
}
}
@Nullable
private ASTNode processTernaryOperationRange(@NotNull final List<Block> result,
@NotNull final ASTNode child,
final Wrap defaultWrap,
final Indent childIndent) {
final ArrayList<Block> localResult = new ArrayList<>();
final Wrap wrap = arrangeChildWrap(child, defaultWrap);
final Alignment alignment = myReservedAlignment;
final Alignment alignment2 = myReservedAlignment2;
localResult.add(new LeafBlock(child, wrap, chooseAlignment(alignment, alignment2, child), childIndent));
ASTNode current = child.getTreeNext();
while (current != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(current) && current.getTextLength() > 0) {
if (isTernaryOperationSign(current)) break;
current = processChild(localResult, current, chooseAlignment(alignment, alignment2, current), defaultWrap, childIndent);
}
if (current != null) {
current = current.getTreeNext();
}
}
result.add(new SyntheticCodeBlock(localResult, chooseAlignment(alignment, alignment2, child), getSettings(), myJavaSettings, null, wrap));
if (current == null) {
return null;
}
return current.getTreePrev();
}
private boolean isTernaryOperationSign(@NotNull final ASTNode child) {
if (myNode.getElementType() != JavaElementType.CONDITIONAL_EXPRESSION) return false;
final int role = ((CompositeElement)child.getTreeParent()).getChildRole(child);
return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON;
}
@NotNull
private Block createMethodCallExpressionBlock(@NotNull ASTNode node, Wrap blockWrap, Alignment alignment, Indent indent) {
final ArrayList<ASTNode> nodes = new ArrayList<>();
collectNodes(nodes, node);
return new ChainMethodCallsBlockBuilder(alignment, blockWrap, indent, mySettings, myJavaSettings, myFormattingMode).build(nodes);
}
private static void collectNodes(@NotNull List<ASTNode> nodes, @NotNull ASTNode node) {
ASTNode child = node.getFirstChildNode();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
IElementType type = child.getElementType();
if (type == JavaElementType.METHOD_CALL_EXPRESSION ||
type == JavaElementType.REFERENCE_EXPRESSION) {
collectNodes(nodes, child);
}
else {
nodes.add(child);
}
}
child = child.getTreeNext();
}
}
private boolean shouldAlignChild(@NotNull final ASTNode child) {
int role = getChildRole(child);
final IElementType nodeType = myNode.getElementType();
if (nodeType == JavaElementType.FOR_STATEMENT) {
if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) {
return true;
}
return false;
}
else if (nodeType == JavaElementType.EXTENDS_LIST ||
nodeType == JavaElementType.IMPLEMENTS_LIST ||
nodeType == JavaElementType.THROWS_LIST) {
return role == ChildRole.REFERENCE_IN_LIST;
}
else if (nodeType == JavaElementType.CLASS) {
if (role == ChildRole.CLASS_OR_INTERFACE_KEYWORD) return true;
if (myIsAfterClassKeyword) return false;
if (role == ChildRole.MODIFIER_LIST) return true;
return false;
}
else if (JavaElementType.FIELD == nodeType) {
return shouldAlignFieldInColumns(child);
}
else if (nodeType == JavaElementType.METHOD) {
if (role == ChildRole.MODIFIER_LIST) return true;
if (role == ChildRole.TYPE_PARAMETER_LIST) return true;
if (role == ChildRole.TYPE) return true;
if (role == ChildRole.NAME) return true;
if (role == ChildRole.THROWS_LIST && mySettings.ALIGN_THROWS_KEYWORD) return true;
if (role == ChildRole.METHOD_BODY) return !getNode().textContains('\n');
return false;
}
else if (nodeType == JavaElementType.ASSIGNMENT_EXPRESSION) {
if (role == ChildRole.LOPERAND) return true;
if (role == ChildRole.ROPERAND && child.getElementType() == JavaElementType.ASSIGNMENT_EXPRESSION) {
return true;
}
return false;
}
else if (child.getElementType() == JavaTokenType.END_OF_LINE_COMMENT) {
ASTNode previous = child.getTreePrev();
// There is a special case - comment block that is located at the very start of the line. We don't reformat such a blocks,
// hence, no alignment should be applied to them in order to avoid subsequent blocks aligned with the same alignment to
// be located at the left editor edge as well.
CharSequence prevChars;
if (previous != null && previous.getElementType() == TokenType.WHITE_SPACE && (prevChars = previous.getChars()).length() > 0
&& prevChars.charAt(prevChars.length() - 1) == '\n') {
return false;
}
return true;
}
else if (nodeType == JavaElementType.MODIFIER_LIST) {
// There is a possible case that modifier list contains from more than one elements, e.g. 'private final'. It's also possible
// that the list is aligned. We want to apply alignment rule only to the first element then.
ASTNode previous = child.getTreePrev();
if (previous == null || previous.getTreeParent() != myNode) {
return true;
}
return false;
}
else {
return true;
}
}
private static int getChildRole(@NotNull ASTNode child) {
return ((CompositeElement)child.getTreeParent()).getChildRole(child);
}
/**
* Encapsulates alignment retrieval logic for variable declaration use-case assuming that given node is a child node
* of basic variable declaration node.
*
* @param child variable declaration child node which alignment is to be defined
* @return alignment to use for the given node
* @see CommonCodeStyleSettings#ALIGN_GROUP_FIELD_DECLARATIONS
*/
private boolean shouldAlignFieldInColumns(@NotNull ASTNode child) {
// The whole idea of variable declarations alignment is that complete declaration blocks which children are to be aligned hold
// reference to the same AlignmentStrategy object, hence, reuse the same Alignment objects. So, there is no point in checking
// if it's necessary to align sub-blocks if shared strategy is not defined.
if (!mySettings.ALIGN_GROUP_FIELD_DECLARATIONS) {
return false;
}
IElementType childType = child.getElementType();
// We don't want to align subsequent identifiers in single-line declarations like 'int i1, i2, i3'. I.e. only 'i1'
// should be aligned then.
ASTNode previousNode = FormatterUtil.getPreviousNonWhitespaceSibling(child);
if (childType == JavaTokenType.IDENTIFIER && (previousNode == null || previousNode.getElementType() == JavaTokenType.COMMA)) {
return false;
}
return true;
}
@Nullable
public static Alignment createAlignment(final boolean alignOption, @Nullable final Alignment defaultAlignment) {
return alignOption ? createAlignmentOrDefault(null, defaultAlignment) : defaultAlignment;
}
@Nullable
public static Alignment createAlignment(Alignment base, final boolean alignOption, @Nullable final Alignment defaultAlignment) {
return alignOption ? createAlignmentOrDefault(base, defaultAlignment) : defaultAlignment;
}
@Nullable
protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) {
//when detecting indent we do not care about wraps
return isBuildIndentsOnly() ? null : myWrapManager.arrangeChildWrap(child, myNode, mySettings, myJavaSettings, defaultWrap, this);
}
@NotNull
private ASTNode processParenthesisBlock(@NotNull List<Block> result,
@NotNull ASTNode child,
@NotNull WrappingStrategy wrappingStrategy,
final boolean doAlign) {
myUseChildAttributes = true;
final IElementType from = JavaTokenType.LPARENTH;
final IElementType to = JavaTokenType.RPARENTH;
return processParenthesisBlock(from, to, result, child, wrappingStrategy, doAlign);
}
@NotNull
private ASTNode processParenthesisBlock(@NotNull IElementType from,
@Nullable final IElementType to,
@NotNull final List<Block> result,
@NotNull ASTNode child,
@NotNull final WrappingStrategy wrappingStrategy,
final boolean doAlign)
{
Indent externalIndent = Indent.getNoneIndent();
Indent internalIndent = Indent.getContinuationWithoutFirstIndent(false);
if (isInsideMethodCallParenthesis(child)) {
internalIndent = Indent.getSmartIndent(Indent.Type.CONTINUATION);
}
AlignmentStrategy alignmentStrategy = AlignmentStrategy.wrap(createAlignment(doAlign, null), JavaTokenType.COMMA);
setChildIndent(internalIndent);
setChildAlignment(alignmentStrategy.getAlignment(null));
boolean methodParametersBlock = true;
ASTNode lBracketParent = child.getTreeParent();
if (lBracketParent != null) {
ASTNode methodCandidate = lBracketParent.getTreeParent();
methodParametersBlock = methodCandidate != null && (methodCandidate.getElementType() == JavaElementType.METHOD
|| methodCandidate.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION);
}
Alignment bracketAlignment = methodParametersBlock && mySettings.ALIGN_MULTILINE_METHOD_BRACKETS ? Alignment.createAlignment() : null;
AlignmentStrategy anonymousClassStrategy = doAlign ? alignmentStrategy
: AlignmentStrategy.wrap(Alignment.createAlignment(),
false,
JavaTokenType.NEW_KEYWORD,
JavaElementType.NEW_EXPRESSION,
JavaTokenType.RBRACE);
setChildIndent(internalIndent);
setChildAlignment(alignmentStrategy.getAlignment(null));
ASTNode prev = child;
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
if (child.getElementType() == from) {
result.add(createJavaBlock(child, mySettings, myJavaSettings, externalIndent, null, bracketAlignment, myFormattingMode));
}
else if (child.getElementType() == to) {
boolean isAfterIncomplete = isAfterErrorElement(child);
Indent parenIndent = isAfterIncomplete ? internalIndent : externalIndent;
Alignment parenAlignment = isAfterIncomplete ? alignmentStrategy.getAlignment(null) : bracketAlignment;
ChildAttributes attributes = getDelegateAttributes(result);
if (attributes != null) {
parenIndent = attributes.getChildIndent();
parenAlignment = attributes.getAlignment();
}
Block block = createJavaBlock(child, mySettings, myJavaSettings,
parenIndent,
null,
parenAlignment, myFormattingMode);
result.add(block);
return child;
}
else {
final IElementType elementType = child.getElementType();
AlignmentStrategy alignmentStrategyToUse = canUseAnonymousClassAlignment(child) ? anonymousClassStrategy : alignmentStrategy;
processChild(result, child, alignmentStrategyToUse.getAlignment(elementType), wrappingStrategy.getWrap(elementType), internalIndent);
if (to == null) {//process only one statement
return child;
}
}
}
prev = child;
child = child.getTreeNext();
}
return prev;
}
private static boolean isInsideMethodCallParenthesis(ASTNode child) {
ASTNode currentPredecessor = child.getTreeParent();
if (currentPredecessor != null) {
currentPredecessor = currentPredecessor.getTreeParent();
return currentPredecessor != null && currentPredecessor.getElementType() == JavaElementType.METHOD_CALL_EXPRESSION;
}
return false;
}
private static boolean canUseAnonymousClassAlignment(@NotNull ASTNode child) {
// The general idea is to handle situations like below:
// test(new Runnable() {
// public void run() {
// }
// }, new Runnable() {
// public void run() {
// }
// }
// );
// I.e. we want to align subsequent anonymous class argument to the previous one if it's not preceded by another argument
// at the same line, e.g.:
// test("this is a long argument", new Runnable() {
// public void run() {
// }
// }, new Runnable() {
// public void run() {
// }
// }
// );
if (!isAnonymousClass(child)) {
return false;
}
for (ASTNode node = child.getTreePrev(); node != null; node = node.getTreePrev()) {
if (node.getElementType() == TokenType.WHITE_SPACE) {
if (StringUtil.countNewLines(node.getChars()) > 0) {
return false;
}
}
else if (node.getElementType() == JavaTokenType.LPARENTH) {
// First method call argument.
return true;
}
else if (node.getElementType() != JavaTokenType.COMMA && !isAnonymousClass(node)) {
return false;
}
}
return true;
}
private static boolean isAnonymousClass(@Nullable ASTNode node) {
if (node == null || node.getElementType() != JavaElementType.NEW_EXPRESSION) {
return false;
}
ASTNode lastChild = node.getLastChildNode();
return lastChild != null && lastChild.getElementType() == JavaElementType.ANONYMOUS_CLASS;
}
@Nullable
private ASTNode processEnumBlock(@NotNull List<Block> result,
@Nullable ASTNode child,
ASTNode last)
{
final WrappingStrategy wrappingStrategy = new WrappingStrategy(Wrap.createWrap(getWrapType(mySettings.ENUM_CONSTANTS_WRAP), true)) {
@Override
protected boolean shouldWrap(IElementType type) {
return type == JavaElementType.ENUM_CONSTANT;
}
};
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
result.add(createJavaBlock(child, mySettings, myJavaSettings, Indent.getNormalIndent(),
wrappingStrategy.getWrap(child.getElementType()), AlignmentStrategy.getNullStrategy(), myFormattingMode));
if (child == last) return child;
}
child = child.getTreeNext();
}
return null;
}
private void setChildAlignment(final Alignment alignment) {
myChildAlignment = alignment;
}
private void setChildIndent(final Indent internalIndent) {
myChildIndent = internalIndent;
}
@Nullable
private static Alignment createAlignmentOrDefault(@Nullable Alignment base, @Nullable final Alignment defaultAlignment) {
if (defaultAlignment == null) {
return base == null ? Alignment.createAlignment() : Alignment.createChildAlignment(base);
}
return defaultAlignment;
}
private int getBraceStyle() {
final PsiElement psiNode = SourceTreeToPsiMap.treeElementToPsi(myNode);
if (psiNode instanceof PsiClass) {
return mySettings.CLASS_BRACE_STYLE;
}
if (psiNode instanceof PsiMethod
|| psiNode instanceof PsiCodeBlock && psiNode.getParent() != null && psiNode.getParent() instanceof PsiMethod) {
return mySettings.METHOD_BRACE_STYLE;
}
return mySettings.BRACE_STYLE;
}
protected Indent getCodeBlockInternalIndent(int baseChildrenIndent) {
if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) {
return Indent.getNoneIndent();
}
final int braceStyle = getBraceStyle();
final int shift = braceStyle == CommonCodeStyleSettings.NEXT_LINE_SHIFTED ? 1 : 0;
return createNormalIndent(baseChildrenIndent - shift);
}
protected static Indent createNormalIndent() {
return createNormalIndent(1);
}
protected static Indent createNormalIndent(int baseChildrenIndent) {
assert baseChildrenIndent <= 1 : baseChildrenIndent;
if (baseChildrenIndent <= 0) {
return Indent.getNoneIndent();
}
else {
return Indent.getIndent(Indent.Type.NORMAL, false, false);
}
}
private boolean isTopLevelClass() {
return myNode.getElementType() == JavaElementType.CLASS &&
SourceTreeToPsiMap.treeElementToPsi(myNode.getTreeParent()) instanceof PsiFile;
}
protected Indent getCodeBlockExternalIndent() {
final int braceStyle = getBraceStyle();
if (braceStyle == CommonCodeStyleSettings.END_OF_LINE || braceStyle == CommonCodeStyleSettings.NEXT_LINE ||
braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
protected Indent getCodeBlockChildExternalIndent(final int newChildIndex) {
final int braceStyle = getBraceStyle();
if (!isAfterCodeBlock(newChildIndex)) {
return Indent.getNormalIndent();
}
if (braceStyle == CommonCodeStyleSettings.NEXT_LINE ||
braceStyle == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED ||
braceStyle == CommonCodeStyleSettings.END_OF_LINE) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
private boolean isAfterCodeBlock(final int newChildIndex) {
if (newChildIndex == 0) return false;
Block blockBefore = getSubBlocks().get(newChildIndex - 1);
return blockBefore instanceof CodeBlockBlock;
}
/**
* <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing
* is refactored
*
* @param elementType target element type
* @return {@code null} all the time
*/
@Nullable
@Override
public Wrap getReservedWrap(IElementType elementType) {
return myPreferredWraps != null ? myPreferredWraps.get(elementType) : null;
}
/**
* Defines contract for associating operation type and particular wrap instance. I.e. given wrap object <b>may</b> be returned
* from subsequent {@link #getReservedWrap(IElementType)} call if given operation type is used as an argument there.
* <p/>
* Default implementation ({@link AbstractJavaBlock#setReservedWrap(Wrap, IElementType)}) does nothing.
* <p/>
* <b>Note:</b> this method is considered to be a legacy heritage and is assumed to be removed as soon as formatting processing
* is refactored
*
* @param reservedWrap reserved wrap instance
* @param operationType target operation type to associate with the given wrap instance
*/
public void setReservedWrap(final Wrap reservedWrap, final IElementType operationType) {
if (myPreferredWraps == null) {
myPreferredWraps = ContainerUtil.newHashMap();
}
myPreferredWraps.put(operationType, reservedWrap);
}
@Nullable
protected static ASTNode getTreeNode(final Block block) {
if (block instanceof JavaBlock) {
return ((JavaBlock)block).getFirstTreeNode();
}
if (block instanceof LeafBlock) {
return ((LeafBlock)block).getTreeNode();
}
if (block instanceof CStyleCommentBlock) {
return ((CStyleCommentBlock)block).getNode();
}
return null;
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myUseChildAttributes) {
return new ChildAttributes(myChildIndent, myChildAlignment);
}
if (isAfter(newChildIndex, new IElementType[]{JavaDocElementType.DOC_COMMENT})) {
return new ChildAttributes(Indent.getNoneIndent(), myChildAlignment);
}
return super.getChildAttributes(newChildIndex);
}
@Override
@Nullable
protected Indent getChildIndent() {
return getChildIndent(myNode, myIndentSettings);
}
@NotNull
public CommonCodeStyleSettings getSettings() {
return mySettings;
}
protected boolean isAfter(final int newChildIndex, @NotNull final IElementType[] elementTypes) {
if (newChildIndex == 0) return false;
final Block previousBlock = getSubBlocks().get(newChildIndex - 1);
if (!(previousBlock instanceof AbstractBlock)) return false;
final IElementType previousElementType = ((AbstractBlock)previousBlock).getNode().getElementType();
for (IElementType elementType : elementTypes) {
if (previousElementType == elementType) return true;
}
return false;
}
@Nullable
protected Alignment getUsedAlignment(final int newChildIndex) {
final List<Block> subBlocks = getSubBlocks();
for (int i = 0; i < newChildIndex; i++) {
if (i >= subBlocks.size()) return null;
final Block block = subBlocks.get(i);
final Alignment alignment = block.getAlignment();
if (alignment != null) return alignment;
}
return null;
}
@Override
public boolean isLeaf() {
return ShiftIndentInsideHelper.mayShiftIndentInside(myNode);
}
@Nullable
protected ASTNode composeCodeBlock(@NotNull final List<Block> result,
ASTNode child,
final Indent indent,
final int childrenIndent,
@Nullable final Wrap childWrap) {
final ArrayList<Block> localResult = new ArrayList<>();
processChild(localResult, child, AlignmentStrategy.getNullStrategy(), null, Indent.getNoneIndent());
child = child.getTreeNext();
ChildAlignmentStrategyProvider alignmentStrategyProvider = getStrategyProvider();
while (child != null) {
if (FormatterUtil.containsWhiteSpacesOnly(child)) {
child = child.getTreeNext();
continue;
}
Indent childIndent = getIndentForCodeBlock(child, childrenIndent);
AlignmentStrategy alignmentStrategyToUse = alignmentStrategyProvider.getNextChildStrategy(child);
final boolean isRBrace = isRBrace(child);
child = processChild(localResult, child, alignmentStrategyToUse, childWrap, childIndent);
if (isRBrace) {
result.add(createCodeBlockBlock(localResult, indent, childrenIndent));
return child;
}
if (child != null) {
child = child.getTreeNext();
}
}
result.add(createCodeBlockBlock(localResult, indent, childrenIndent));
return null;
}
protected ChildAlignmentStrategyProvider getStrategyProvider() {
if (myNode.getElementType() == JavaElementType.CLASS) {
return new SubsequentClassMemberAlignment(mySettings);
}
ASTNode parent = myNode.getTreeParent();
IElementType parentType = parent != null ? parent.getElementType() : null;
if (mySettings.ALIGN_CONSECUTIVE_VARIABLE_DECLARATIONS
&& (parentType == JavaElementType.METHOD || myNode instanceof PsiCodeBlock)) {
return new SubsequentVariablesAligner();
}
return ChildAlignmentStrategyProvider.NULL_STRATEGY_PROVIDER;
}
private Indent getIndentForCodeBlock(ASTNode child, int childrenIndent) {
if (child.getElementType() == JavaElementType.CODE_BLOCK
&& (getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED
|| getBraceStyle() == CommonCodeStyleSettings.NEXT_LINE_SHIFTED2))
{
return Indent.getNormalIndent();
}
return isRBrace(child) ? Indent.getNoneIndent() : getCodeBlockInternalIndent(childrenIndent);
}
public AbstractJavaBlock getParentBlock() {
return myParentBlock;
}
public void setParentBlock(@NotNull AbstractJavaBlock parentBlock) {
myParentBlock = parentBlock;
}
@NotNull
public SyntheticCodeBlock createCodeBlockBlock(final List<Block> localResult, final Indent indent, final int childrenIndent) {
final SyntheticCodeBlock result = new SyntheticCodeBlock(localResult, null, getSettings(), myJavaSettings, indent, null);
result.setChildAttributes(new ChildAttributes(getCodeBlockInternalIndent(childrenIndent), null));
return result;
}
protected FormattingMode getFormattingMode() {
return myFormattingMode;
}
}
| |
package net.i2p.router.update;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URI;
import java.util.List;
import java.util.Locale;
import net.i2p.crypto.TrustedUpdate;
import net.i2p.router.RouterContext;
import net.i2p.router.RouterVersion;
import net.i2p.router.web.ConfigUpdateHandler;
import net.i2p.update.*;
import static net.i2p.update.UpdateMethod.*;
import net.i2p.util.EepGet;
import net.i2p.util.I2PAppThread;
import net.i2p.util.Log;
import net.i2p.util.PartialEepGet;
import net.i2p.util.PortMapper;
import net.i2p.util.SSLEepGet;
import net.i2p.util.VersionComparator;
/**
* The downloader for router signed updates,
* and the base class for all the other Checkers and Runners.
*
* @since 0.9.4 moved from UpdateHandler
*
*/
class UpdateRunner extends I2PAppThread implements UpdateTask, EepGet.StatusListener {
protected final RouterContext _context;
protected final Log _log;
protected final ConsoleUpdateManager _mgr;
protected final UpdateType _type;
protected final UpdateMethod _method;
protected final List<URI> _urls;
protected final String _updateFile;
protected volatile boolean _isRunning;
protected boolean done;
protected EepGet _get;
/** tells the listeners what mode we are in - set to true in extending classes for checks */
protected boolean _isPartial;
/** set by the listeners on completion */
protected String _newVersion;
/** 56 byte header, only used for suds */
protected final ByteArrayOutputStream _baos;
protected URI _currentURI;
private final String _currentVersion;
protected static final long CONNECT_TIMEOUT = 55*1000;
protected static final long INACTIVITY_TIMEOUT = 5*60*1000;
protected static final long NOPROXY_INACTIVITY_TIMEOUT = 60*1000;
/**
* Uses router version for partial checks
*/
public UpdateRunner(RouterContext ctx, ConsoleUpdateManager mgr, UpdateType type, List<URI> uris) {
this(ctx, mgr, type, uris, RouterVersion.VERSION);
}
/**
* Uses router version for partial checks
* @since 0.9.9
*/
public UpdateRunner(RouterContext ctx, ConsoleUpdateManager mgr, UpdateType type,
UpdateMethod method, List<URI> uris) {
this(ctx, mgr, type, method, uris, RouterVersion.VERSION);
}
/**
* @param currentVersion used for partial checks
* @since 0.9.7
*/
public UpdateRunner(RouterContext ctx, ConsoleUpdateManager mgr, UpdateType type,
List<URI> uris, String currentVersion) {
this(ctx, mgr, type, HTTP, uris, currentVersion);
}
/**
* @param method HTTP, HTTP_CLEARNET, or HTTPS_CLEARNET
* @param currentVersion used for partial checks
* @since 0.9.9
*/
public UpdateRunner(RouterContext ctx, ConsoleUpdateManager mgr, UpdateType type,
UpdateMethod method, List<URI> uris, String currentVersion) {
super("Update Runner");
setDaemon(true);
_context = ctx;
_log = ctx.logManager().getLog(getClass());
_mgr = mgr;
_type = type;
_method = method;
_urls = uris;
_baos = new ByteArrayOutputStream(TrustedUpdate.HEADER_BYTES);
_updateFile = (new File(ctx.getTempDir(), "update" + ctx.random().nextInt() + ".tmp")).getAbsolutePath();
_currentVersion = currentVersion;
}
//////// begin UpdateTask methods
public boolean isRunning() { return _isRunning; }
public void shutdown() {
_isRunning = false;
interrupt();
}
public UpdateType getType() { return _type; }
public UpdateMethod getMethod() { return _method; }
public URI getURI() { return _currentURI; }
public String getID() { return ""; }
//////// end UpdateTask methods
@Override
public void run() {
_isRunning = true;
try {
update();
} catch (Throwable t) {
_mgr.notifyTaskFailed(this, "", t);
} finally {
_isRunning = false;
}
}
/**
* Loop through the entire list of update URLs.
* For each one, first get the version from the first 56 bytes and see if
* it is newer than what we are running now.
* If it is, get the whole thing.
*/
protected void update() {
// Do a PartialEepGet on the selected URL, check for version we expect,
// and loop if it isn't what we want.
// This will allows us to do a release without waiting for the last host to install the update.
// Alternative: In bytesTransferred(), Check the data in the output file after
// we've received at least 56 bytes. Need a cancel() method in EepGet ?
boolean shouldProxy;
String proxyHost;
int proxyPort;
boolean isSSL = false;
if (_method == HTTP) {
shouldProxy = _context.getProperty(ConfigUpdateHandler.PROP_SHOULD_PROXY, ConfigUpdateHandler.DEFAULT_SHOULD_PROXY);
if (shouldProxy) {
proxyHost = _context.getProperty(ConfigUpdateHandler.PROP_PROXY_HOST, ConfigUpdateHandler.DEFAULT_PROXY_HOST);
proxyPort = ConfigUpdateHandler.proxyPort(_context);
if (proxyPort == ConfigUpdateHandler.DEFAULT_PROXY_PORT_INT &&
proxyHost.equals(ConfigUpdateHandler.DEFAULT_PROXY_HOST) &&
_context.portMapper().getPort(PortMapper.SVC_HTTP_PROXY) < 0) {
String msg = _("HTTP client proxy tunnel must be running");
if (_log.shouldWarn())
_log.warn(msg);
updateStatus("<b>" + msg + "</b>");
_mgr.notifyTaskFailed(this, msg, null);
return;
}
} else {
// TODO, wrong method, fail
proxyHost = null;
proxyPort = 0;
}
} else if (_method == HTTP_CLEARNET) {
shouldProxy = false;
proxyHost = null;
proxyPort = 0;
} else if (_method == HTTPS_CLEARNET) {
shouldProxy = false;
proxyHost = null;
proxyPort = 0;
isSSL = true;
} else {
throw new IllegalArgumentException();
}
if (_urls.isEmpty()) {
// not likely, don't bother translating
String msg = "Update source list is empty, cannot download update";
updateStatus("<b>" + msg + "</b>");
_log.error(msg);
_mgr.notifyTaskFailed(this, msg, null);
return;
}
for (URI uri : _urls) {
_currentURI = uri;
String updateURL = uri.toString();
if ((_method == HTTP && !"http".equals(uri.getScheme())) ||
(_method == HTTP_CLEARNET && !"http".equals(uri.getScheme())) ||
(_method == HTTPS_CLEARNET && !"https".equals(uri.getScheme())) ||
uri.getHost() == null ||
(_method != HTTP && uri.getHost().toLowerCase(Locale.US).endsWith(".i2p"))) {
if (_log.shouldLog(Log.WARN))
_log.warn("Bad update URI " + uri + " for method " + _method);
continue;
}
updateStatus("<b>" + _("Updating from {0}", linkify(updateURL)) + "</b>");
if (_log.shouldLog(Log.DEBUG))
_log.debug("Selected update URL: " + updateURL);
// Check the first 56 bytes for the version
// FIXME PartialEepGet works with clearnet but not with SSL
_newVersion = null;
if (!isSSL) {
_isPartial = true;
_baos.reset();
try {
// no retries
_get = new PartialEepGet(_context, proxyHost, proxyPort, _baos, updateURL, TrustedUpdate.HEADER_BYTES);
_get.addStatusListener(UpdateRunner.this);
_get.fetch(CONNECT_TIMEOUT);
} catch (Throwable t) {
}
_isPartial = false;
if (_newVersion == null)
continue;
}
// Now get the whole thing
try {
if (shouldProxy)
// 40 retries!!
_get = new EepGet(_context, proxyHost, proxyPort, 40, _updateFile, updateURL, false);
else if (isSSL)
_get = new SSLEepGet(_context, _updateFile, updateURL);
else
_get = new EepGet(_context, 1, _updateFile, updateURL, false);
_get.addStatusListener(UpdateRunner.this);
_get.fetch(CONNECT_TIMEOUT, -1, shouldProxy ? INACTIVITY_TIMEOUT : NOPROXY_INACTIVITY_TIMEOUT);
} catch (Throwable t) {
_log.error("Error updating", t);
}
if (this.done)
break;
}
(new File(_updateFile)).delete();
if (!this.done)
_mgr.notifyTaskFailed(this, "", null);
}
// EepGet Listeners below.
// We use the same for both the partial and the full EepGet,
// with a couple of adjustments depending on which mode.
public void attemptFailed(String url, long bytesTransferred, long bytesRemaining, int currentAttempt, int numRetries, Exception cause) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Attempt failed on " + url, cause);
// ignored
_mgr.notifyAttemptFailed(this, url, null);
}
/** subclasses should override */
public void bytesTransferred(long alreadyTransferred, int currentWrite, long bytesTransferred, long bytesRemaining, String url) {
if (_isPartial)
return;
long d = currentWrite + bytesTransferred;
String status = "<b>" + _("Updating") + "</b>";
_mgr.notifyProgress(this, status, d, d + bytesRemaining);
}
/** subclasses should override */
public void transferComplete(long alreadyTransferred, long bytesTransferred, long bytesRemaining, String url, String outputFile, boolean notModified) {
if (_isPartial) {
// Compare version with what we have now
String newVersion = TrustedUpdate.getVersionString(new ByteArrayInputStream(_baos.toByteArray()));
boolean newer = VersionComparator.comp(newVersion, _currentVersion) > 0;
if (newer) {
_newVersion = newVersion;
} else {
updateStatus("<b>" + _("No new version found at {0}", linkify(url)) + "</b>");
if (_log.shouldLog(Log.WARN))
_log.warn("Found old version \"" + newVersion + "\" at " + url);
}
return;
}
// FIXME if we didn't do a partial, we don't know
if (_newVersion == null)
_newVersion = "unknown";
File tmp = new File(_updateFile);
if (_mgr.notifyComplete(this, _newVersion, tmp))
this.done = true;
else
tmp.delete(); // corrupt
}
/** subclasses should override */
public void transferFailed(String url, long bytesTransferred, long bytesRemaining, int currentAttempt) {
// don't display bytesTransferred as it is meaningless
if (_log.shouldLog(Log.WARN))
_log.warn("Update from " + url + " did not download completely (" +
bytesRemaining + " remaining after " + currentAttempt + " tries)");
updateStatus("<b>" + _("Transfer failed from {0}", linkify(url)) + "</b>");
_mgr.notifyAttemptFailed(this, url, null);
// update() will call notifyTaskFailed() after last URL
}
public void headerReceived(String url, int attemptNum, String key, String val) {}
public void attempting(String url) {}
protected void updateStatus(String s) {
_mgr.notifyProgress(this, s);
}
protected static String linkify(String url) {
return ConsoleUpdateManager.linkify(url);
}
/** translate a string */
protected String _(String s) {
return _mgr._(s);
}
/**
* translate a string with a parameter
*/
protected String _(String s, Object o) {
return _mgr._(s, o);
}
@Override
public String toString() {
return getClass().getName() + ' ' + getType() + ' ' + getID() + ' ' + getMethod() + ' ' + getURI();
}
}
| |
/*
* 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.calcite.avatica.util;
import org.apache.calcite.avatica.AvaticaSite;
import org.apache.calcite.avatica.AvaticaUtils;
import org.apache.calcite.avatica.ColumnMetaData;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Struct;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
/**
* Base class for implementing a cursor.
*
* <p>Derived class needs to provide {@link Getter} and can override
* {@link org.apache.calcite.avatica.util.Cursor.Accessor} implementations if it
* wishes.</p>
*/
public abstract class AbstractCursor implements Cursor {
/**
* Slot into which each accessor should write whether the
* value returned was null.
*/
protected final boolean[] wasNull = {false};
protected AbstractCursor() {
}
public boolean wasNull() {
return wasNull[0];
}
public List<Accessor> createAccessors(List<ColumnMetaData> types,
Calendar localCalendar, ArrayImpl.Factory factory) {
List<Accessor> accessors = new ArrayList<>();
for (ColumnMetaData type : types) {
accessors.add(
createAccessor(type, accessors.size(), localCalendar, factory));
}
return accessors;
}
protected Accessor createAccessor(ColumnMetaData columnMetaData, int ordinal,
Calendar localCalendar, ArrayImpl.Factory factory) {
// Create an accessor appropriate to the underlying type; the accessor
// can convert to any type in the same family.
Getter getter = createGetter(ordinal);
return createAccessor(columnMetaData, getter, localCalendar, factory);
}
protected Accessor createAccessor(ColumnMetaData columnMetaData,
Getter getter, Calendar localCalendar, ArrayImpl.Factory factory) {
switch (columnMetaData.type.rep) {
case NUMBER:
switch (columnMetaData.type.id) {
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
case Types.REAL:
case Types.FLOAT:
case Types.DOUBLE:
case Types.NUMERIC:
case Types.DECIMAL:
return new NumberAccessor(getter, columnMetaData.scale);
}
}
switch (columnMetaData.type.id) {
case Types.TINYINT:
return new ByteAccessor(getter);
case Types.SMALLINT:
return new ShortAccessor(getter);
case Types.INTEGER:
return new IntAccessor(getter);
case Types.BIGINT:
return new LongAccessor(getter);
case Types.BOOLEAN:
return new BooleanAccessor(getter);
case Types.REAL:
return new FloatAccessor(getter);
case Types.FLOAT:
case Types.DOUBLE:
return new DoubleAccessor(getter);
case Types.DECIMAL:
return new BigDecimalAccessor(getter);
case Types.CHAR:
switch (columnMetaData.type.rep) {
case PRIMITIVE_CHAR:
case CHARACTER:
return new StringFromCharAccessor(getter, columnMetaData.displaySize);
default:
return new FixedStringAccessor(getter, columnMetaData.displaySize);
}
case Types.VARCHAR:
return new StringAccessor(getter);
case Types.BINARY:
case Types.VARBINARY:
switch (columnMetaData.type.rep) {
case STRING:
return new BinaryFromStringAccessor(getter);
default:
return new BinaryAccessor(getter);
}
case Types.DATE:
switch (columnMetaData.type.rep) {
case PRIMITIVE_INT:
case INTEGER:
case NUMBER:
return new DateFromNumberAccessor(getter, localCalendar);
case JAVA_SQL_DATE:
return new DateAccessor(getter);
default:
throw new AssertionError("bad " + columnMetaData.type.rep);
}
case Types.TIME:
switch (columnMetaData.type.rep) {
case PRIMITIVE_INT:
case INTEGER:
case NUMBER:
return new TimeFromNumberAccessor(getter, localCalendar);
case JAVA_SQL_TIME:
return new TimeAccessor(getter);
default:
throw new AssertionError("bad " + columnMetaData.type.rep);
}
case Types.TIMESTAMP:
switch (columnMetaData.type.rep) {
case PRIMITIVE_LONG:
case LONG:
case NUMBER:
return new TimestampFromNumberAccessor(getter, localCalendar);
case JAVA_SQL_TIMESTAMP:
return new TimestampAccessor(getter);
case JAVA_UTIL_DATE:
return new TimestampFromUtilDateAccessor(getter, localCalendar);
default:
throw new AssertionError("bad " + columnMetaData.type.rep);
}
case Types.ARRAY:
final ColumnMetaData.ArrayType arrayType =
(ColumnMetaData.ArrayType) columnMetaData.type;
final SlotGetter componentGetter = new SlotGetter();
final Accessor componentAccessor =
createAccessor(ColumnMetaData.dummy(arrayType.component, true),
componentGetter, localCalendar, factory);
return new ArrayAccessor(getter, arrayType.component, componentAccessor,
componentGetter, factory);
case Types.STRUCT:
switch (columnMetaData.type.rep) {
case OBJECT:
final ColumnMetaData.StructType structType =
(ColumnMetaData.StructType) columnMetaData.type;
List<Accessor> accessors = new ArrayList<>();
for (ColumnMetaData column : structType.columns) {
final Getter fieldGetter =
structType.columns.size() == 1
? getter
: new StructGetter(getter, column);
accessors.add(
createAccessor(column, fieldGetter, localCalendar, factory));
}
return new StructAccessor(getter, accessors);
default:
throw new AssertionError("bad " + columnMetaData.type.rep);
}
case Types.JAVA_OBJECT:
case Types.OTHER: // e.g. map
if (columnMetaData.type.name.startsWith("INTERVAL_")) {
int end = columnMetaData.type.name.indexOf("(");
if (end < 0) {
end = columnMetaData.type.name.length();
}
TimeUnitRange range =
TimeUnitRange.valueOf(
columnMetaData.type.name.substring("INTERVAL_".length(), end));
if (range.monthly()) {
return new IntervalYearMonthAccessor(getter, range);
} else {
return new IntervalDayTimeAccessor(getter, range,
columnMetaData.scale);
}
}
return new ObjectAccessor(getter);
default:
throw new RuntimeException("unknown type " + columnMetaData.type.id);
}
}
protected abstract Getter createGetter(int ordinal);
public abstract boolean next();
/** Accesses a timestamp value as a string.
* The timestamp is in SQL format (e.g. "2013-09-22 22:30:32"),
* not Java format ("2013-09-22 22:30:32.123"). */
private static String timestampAsString(long v, Calendar calendar) {
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return DateTimeUtils.unixTimestampToString(v);
}
/** Accesses a date value as a string, e.g. "2013-09-22". */
private static String dateAsString(int v, Calendar calendar) {
AvaticaUtils.discard(calendar); // time zone shift doesn't make sense
return DateTimeUtils.unixDateToString(v);
}
/** Accesses a time value as a string, e.g. "22:30:32". */
private static String timeAsString(int v, Calendar calendar) {
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return DateTimeUtils.unixTimeToString(v);
}
private static Date longToDate(long v, Calendar calendar) {
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return new Date(v);
}
static Time intToTime(int v, Calendar calendar) {
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return new Time(v);
}
static Timestamp longToTimestamp(long v, Calendar calendar) {
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return new Timestamp(v);
}
/** Implementation of {@link Cursor.Accessor}. */
static class AccessorImpl implements Accessor {
protected final Getter getter;
public AccessorImpl(Getter getter) {
assert getter != null;
this.getter = getter;
}
public boolean wasNull() {
return getter.wasNull();
}
public String getString() {
final Object o = getObject();
return o == null ? null : o.toString();
}
public boolean getBoolean() {
return getLong() != 0L;
}
public byte getByte() {
return (byte) getLong();
}
public short getShort() {
return (short) getLong();
}
public int getInt() {
return (int) getLong();
}
public long getLong() {
throw cannotConvert("long");
}
public float getFloat() {
return (float) getDouble();
}
public double getDouble() {
throw cannotConvert("double");
}
public BigDecimal getBigDecimal() {
throw cannotConvert("BigDecimal");
}
public BigDecimal getBigDecimal(int scale) {
throw cannotConvert("BigDecimal with scale");
}
public byte[] getBytes() {
throw cannotConvert("byte[]");
}
public InputStream getAsciiStream() {
throw cannotConvert("InputStream (ascii)");
}
public InputStream getUnicodeStream() {
throw cannotConvert("InputStream (unicode)");
}
public InputStream getBinaryStream() {
throw cannotConvert("InputStream (binary)");
}
public Object getObject() {
return getter.getObject();
}
public Reader getCharacterStream() {
throw cannotConvert("Reader");
}
private RuntimeException cannotConvert(String targetType) {
return new RuntimeException("cannot convert to " + targetType + " ("
+ this + ")");
}
public Object getObject(Map<String, Class<?>> map) {
throw cannotConvert("Object (with map)");
}
public Ref getRef() {
throw cannotConvert("Ref");
}
public Blob getBlob() {
throw cannotConvert("Blob");
}
public Clob getClob() {
throw cannotConvert("Clob");
}
public Array getArray() {
throw cannotConvert("Array");
}
public Struct getStruct() {
throw cannotConvert("Struct");
}
public Date getDate(Calendar calendar) {
throw cannotConvert("Date");
}
public Time getTime(Calendar calendar) {
throw cannotConvert("Time");
}
public Timestamp getTimestamp(Calendar calendar) {
throw cannotConvert("Timestamp");
}
public URL getURL() {
throw cannotConvert("URL");
}
public NClob getNClob() {
throw cannotConvert("NClob");
}
public SQLXML getSQLXML() {
throw cannotConvert("SQLXML");
}
public String getNString() {
throw cannotConvert("NString");
}
public Reader getNCharacterStream() {
throw cannotConvert("NCharacterStream");
}
public <T> T getObject(Class<T> type) {
throw cannotConvert("Object (with type)");
}
}
/**
* Accessor of exact numeric values. The subclass must implement the
* {@link #getLong()} method.
*/
private abstract static class ExactNumericAccessor extends AccessorImpl {
public ExactNumericAccessor(Getter getter) {
super(getter);
}
public BigDecimal getBigDecimal(int scale) {
final long v = getLong();
if (v == 0 && getter.wasNull()) {
return null;
}
return BigDecimal.valueOf(v).setScale(scale, RoundingMode.DOWN);
}
public BigDecimal getBigDecimal() {
final long val = getLong();
if (val == 0 && getter.wasNull()) {
return null;
}
return BigDecimal.valueOf(val);
}
public double getDouble() {
return getLong();
}
public float getFloat() {
return getLong();
}
public abstract long getLong();
}
/**
* Accessor that assumes that the underlying value is a {@link Boolean};
* corresponds to {@link java.sql.Types#BOOLEAN}.
*/
private static class BooleanAccessor extends ExactNumericAccessor {
public BooleanAccessor(Getter getter) {
super(getter);
}
public boolean getBoolean() {
Boolean o = (Boolean) getObject();
return o != null && o;
}
public long getLong() {
return getBoolean() ? 1 : 0;
}
}
/**
* Accessor that assumes that the underlying value is a {@link Byte};
* corresponds to {@link java.sql.Types#TINYINT}.
*/
private static class ByteAccessor extends ExactNumericAccessor {
public ByteAccessor(Getter getter) {
super(getter);
}
public byte getByte() {
Byte o = (Byte) getObject();
return o == null ? 0 : o;
}
public long getLong() {
return getByte();
}
}
/**
* Accessor that assumes that the underlying value is a {@link Short};
* corresponds to {@link java.sql.Types#SMALLINT}.
*/
private static class ShortAccessor extends ExactNumericAccessor {
public ShortAccessor(Getter getter) {
super(getter);
}
public short getShort() {
Short o = (Short) getObject();
return o == null ? 0 : o;
}
public long getLong() {
return getShort();
}
}
/**
* Accessor that assumes that the underlying value is an {@link Integer};
* corresponds to {@link java.sql.Types#INTEGER}.
*/
private static class IntAccessor extends ExactNumericAccessor {
public IntAccessor(Getter getter) {
super(getter);
}
public int getInt() {
Integer o = (Integer) super.getObject();
return o == null ? 0 : o;
}
public long getLong() {
return getInt();
}
}
/**
* Accessor that assumes that the underlying value is a {@link Long};
* corresponds to {@link java.sql.Types#BIGINT}.
*/
private static class LongAccessor extends ExactNumericAccessor {
public LongAccessor(Getter getter) {
super(getter);
}
public long getLong() {
Long o = (Long) super.getObject();
return o == null ? 0 : o;
}
}
/**
* Accessor of values that are {@link Double} or null.
*/
private abstract static class ApproximateNumericAccessor
extends AccessorImpl {
public ApproximateNumericAccessor(Getter getter) {
super(getter);
}
public BigDecimal getBigDecimal(int scale) {
final double v = getDouble();
if (v == 0d && getter.wasNull()) {
return null;
}
return BigDecimal.valueOf(v).setScale(scale, RoundingMode.DOWN);
}
public BigDecimal getBigDecimal() {
final double v = getDouble();
if (v == 0 && getter.wasNull()) {
return null;
}
return BigDecimal.valueOf(v);
}
public abstract double getDouble();
public long getLong() {
return (long) getDouble();
}
}
/**
* Accessor that assumes that the underlying value is a {@link Float};
* corresponds to {@link java.sql.Types#FLOAT}.
*/
private static class FloatAccessor extends ApproximateNumericAccessor {
public FloatAccessor(Getter getter) {
super(getter);
}
public float getFloat() {
Float o = (Float) getObject();
return o == null ? 0f : o;
}
public double getDouble() {
return getFloat();
}
}
/**
* Accessor that assumes that the underlying value is a {@link Double};
* corresponds to {@link java.sql.Types#DOUBLE}.
*/
private static class DoubleAccessor extends ApproximateNumericAccessor {
public DoubleAccessor(Getter getter) {
super(getter);
}
public double getDouble() {
Double o = (Double) getObject();
return o == null ? 0d : o;
}
}
/**
* Accessor of exact numeric values. The subclass must implement the
* {@link #getLong()} method.
*/
private abstract static class BigNumberAccessor extends AccessorImpl {
public BigNumberAccessor(Getter getter) {
super(getter);
}
protected abstract Number getNumber();
public double getDouble() {
Number number = getNumber();
return number == null ? 0d : number.doubleValue();
}
public float getFloat() {
Number number = getNumber();
return number == null ? 0f : number.floatValue();
}
public long getLong() {
Number number = getNumber();
return number == null ? 0L : number.longValue();
}
public int getInt() {
Number number = getNumber();
return number == null ? 0 : number.intValue();
}
public short getShort() {
Number number = getNumber();
return number == null ? 0 : number.shortValue();
}
public byte getByte() {
Number number = getNumber();
return number == null ? 0 : number.byteValue();
}
public boolean getBoolean() {
Number number = getNumber();
return number != null && number.doubleValue() != 0;
}
}
/**
* Accessor that assumes that the underlying value is a {@link BigDecimal};
* corresponds to {@link java.sql.Types#DECIMAL}.
*/
private static class BigDecimalAccessor extends BigNumberAccessor {
public BigDecimalAccessor(Getter getter) {
super(getter);
}
protected Number getNumber() {
return (Number) getObject();
}
public BigDecimal getBigDecimal(int scale) {
return (BigDecimal) getObject();
}
public BigDecimal getBigDecimal() {
return (BigDecimal) getObject();
}
}
/**
* Accessor that assumes that the underlying value is a {@link Number};
* corresponds to {@link java.sql.Types#NUMERIC}.
*
* <p>This is useful when numbers have been translated over JSON. JSON
* converts a 0L (0 long) value to the string "0" and back to 0 (0 int).
* So you cannot be sure that the source and target type are the same.
*/
static class NumberAccessor extends BigNumberAccessor {
private final int scale;
public NumberAccessor(Getter getter, int scale) {
super(getter);
this.scale = scale;
}
protected Number getNumber() {
return (Number) super.getObject();
}
public BigDecimal getBigDecimal(int scale) {
Number n = getNumber();
if (n == null) {
return null;
}
BigDecimal decimal = AvaticaSite.toBigDecimal(n);
if (0 != scale) {
return decimal.setScale(scale, BigDecimal.ROUND_UNNECESSARY);
}
return decimal;
}
public BigDecimal getBigDecimal() {
return getBigDecimal(scale);
}
}
/**
* Accessor that assumes that the underlying value is a {@link String};
* corresponds to {@link java.sql.Types#CHAR}
* and {@link java.sql.Types#VARCHAR}.
*/
private static class StringAccessor extends AccessorImpl {
public StringAccessor(Getter getter) {
super(getter);
}
public String getString() {
return (String) getObject();
}
@Override public byte[] getBytes() {
return super.getBytes();
}
}
/**
* Accessor that assumes that the underlying value is a {@link String};
* corresponds to {@link java.sql.Types#CHAR}.
*/
private static class FixedStringAccessor extends StringAccessor {
protected final Spacer spacer;
public FixedStringAccessor(Getter getter, int length) {
super(getter);
this.spacer = new Spacer(length);
}
public String getString() {
String s = super.getString();
if (s == null) {
return null;
}
return spacer.padRight(s);
}
}
/**
* Accessor that assumes that the underlying value is a {@link String};
* corresponds to {@link java.sql.Types#CHAR}.
*/
private static class StringFromCharAccessor extends FixedStringAccessor {
public StringFromCharAccessor(Getter getter, int length) {
super(getter, length);
}
public String getString() {
Character s = (Character) super.getObject();
if (s == null) {
return null;
}
return spacer.padRight(s.toString());
}
}
/**
* Accessor that assumes that the underlying value is an array of
* {@link org.apache.calcite.avatica.util.ByteString} values;
* corresponds to {@link java.sql.Types#BINARY}
* and {@link java.sql.Types#VARBINARY}.
*/
private static class BinaryAccessor extends AccessorImpl {
public BinaryAccessor(Getter getter) {
super(getter);
}
//FIXME: Protobuf gets byte[]
@Override public byte[] getBytes() {
Object obj = getObject();
try {
final ByteString o = (ByteString) obj;
return o == null ? null : o.getBytes();
} catch (Exception ex) {
return obj == null ? null : (byte[]) obj;
}
}
@Override public String getString() {
Object o = getObject();
if (null == o) {
return null;
}
if (o instanceof byte[]) {
return new String((byte[]) o, StandardCharsets.UTF_8);
} else if (o instanceof ByteString) {
return ((ByteString) o).toString();
}
throw new IllegalStateException("Unhandled value type: " + o.getClass());
}
}
/**
* Accessor that assumes that the underlying value is a {@link String},
* encoding {@link java.sql.Types#BINARY}
* and {@link java.sql.Types#VARBINARY} values in Base64 format.
*/
private static class BinaryFromStringAccessor extends StringAccessor {
public BinaryFromStringAccessor(Getter getter) {
super(getter);
}
@Override public Object getObject() {
return super.getObject();
}
@Override public byte[] getBytes() {
// JSON sends this as a base64-enc string, protobuf can do binary.
Object obj = getObject();
if (obj instanceof byte[]) {
// If we already have bytes, just send them back.
return (byte[]) obj;
}
return getBase64Decoded();
}
private byte[] getBase64Decoded() {
final String string = super.getString();
if (null == string) {
return null;
}
// Need to base64 decode the string.
return ByteString.parseBase64(string);
}
@Override public String getString() {
final byte[] bytes = getBase64Decoded();
if (null == bytes) {
return null;
}
// Need to base64 decode the string.
return new String(bytes, StandardCharsets.UTF_8);
}
}
/**
* Accessor that assumes that the underlying value is a DATE,
* in its default representation {@code int};
* corresponds to {@link java.sql.Types#DATE}.
*/
private static class DateFromNumberAccessor extends NumberAccessor {
private final Calendar localCalendar;
public DateFromNumberAccessor(Getter getter, Calendar localCalendar) {
super(getter, 0);
this.localCalendar = localCalendar;
}
@Override public Object getObject() {
return getDate(localCalendar);
}
@Override public Date getDate(Calendar calendar) {
final Number v = getNumber();
if (v == null) {
return null;
}
return longToDate(v.longValue() * DateTimeUtils.MILLIS_PER_DAY, calendar);
}
@Override public Timestamp getTimestamp(Calendar calendar) {
final Number v = getNumber();
if (v == null) {
return null;
}
return longToTimestamp(v.longValue() * DateTimeUtils.MILLIS_PER_DAY,
calendar);
}
@Override public String getString() {
final Number v = getNumber();
if (v == null) {
return null;
}
return dateAsString(v.intValue(), null);
}
}
/**
* Accessor that assumes that the underlying value is a Time,
* in its default representation {@code int};
* corresponds to {@link java.sql.Types#TIME}.
*/
private static class TimeFromNumberAccessor extends NumberAccessor {
private final Calendar localCalendar;
public TimeFromNumberAccessor(Getter getter, Calendar localCalendar) {
super(getter, 0);
this.localCalendar = localCalendar;
}
@Override public Object getObject() {
return getTime(localCalendar);
}
@Override public Time getTime(Calendar calendar) {
final Number v = getNumber();
if (v == null) {
return null;
}
return intToTime(v.intValue(), calendar);
}
@Override public Timestamp getTimestamp(Calendar calendar) {
final Number v = getNumber();
if (v == null) {
return null;
}
return longToTimestamp(v.longValue(), calendar);
}
@Override public String getString() {
final Number v = getNumber();
if (v == null) {
return null;
}
return timeAsString(v.intValue(), null);
}
}
/**
* Accessor that assumes that the underlying value is a TIMESTAMP,
* in its default representation {@code long};
* corresponds to {@link java.sql.Types#TIMESTAMP}.
*/
private static class TimestampFromNumberAccessor extends NumberAccessor {
private final Calendar localCalendar;
public TimestampFromNumberAccessor(Getter getter, Calendar localCalendar) {
super(getter, 0);
this.localCalendar = localCalendar;
}
@Override public Object getObject() {
return getTimestamp(localCalendar);
}
@Override public Timestamp getTimestamp(Calendar calendar) {
final Number v = getNumber();
if (v == null) {
return null;
}
return longToTimestamp(v.longValue(), calendar);
}
@Override public Date getDate(Calendar calendar) {
final Timestamp timestamp = getTimestamp(calendar);
if (timestamp == null) {
return null;
}
return new Date(timestamp.getTime());
}
@Override public Time getTime(Calendar calendar) {
final Timestamp timestamp = getTimestamp(calendar);
if (timestamp == null) {
return null;
}
return new Time(
DateTimeUtils.floorMod(timestamp.getTime(),
DateTimeUtils.MILLIS_PER_DAY));
}
@Override public String getString() {
final Number v = getNumber();
if (v == null) {
return null;
}
return timestampAsString(v.longValue(), null);
}
}
/**
* Accessor that assumes that the underlying value is a DATE,
* represented as a java.sql.Date;
* corresponds to {@link java.sql.Types#DATE}.
*/
private static class DateAccessor extends ObjectAccessor {
public DateAccessor(Getter getter) {
super(getter);
}
@Override public Date getDate(Calendar calendar) {
java.sql.Date date = (Date) getObject();
if (date == null) {
return null;
}
if (calendar != null) {
long v = date.getTime();
v -= calendar.getTimeZone().getOffset(v);
date = new Date(v);
}
return date;
}
@Override public String getString() {
final int v = getInt();
if (v == 0 && wasNull()) {
return null;
}
return dateAsString(v, null);
}
@Override public long getLong() {
Date date = getDate(null);
return date == null
? 0L
: (date.getTime() / DateTimeUtils.MILLIS_PER_DAY);
}
}
/**
* Accessor that assumes that the underlying value is a TIME,
* represented as a java.sql.Time;
* corresponds to {@link java.sql.Types#TIME}.
*/
private static class TimeAccessor extends ObjectAccessor {
public TimeAccessor(Getter getter) {
super(getter);
}
@Override public Time getTime(Calendar calendar) {
Time date = (Time) getObject();
if (date == null) {
return null;
}
if (calendar != null) {
long v = date.getTime();
v -= calendar.getTimeZone().getOffset(v);
date = new Time(v);
}
return date;
}
@Override public String getString() {
final int v = getInt();
if (v == 0 && wasNull()) {
return null;
}
return timeAsString(v, null);
}
@Override public long getLong() {
Time time = getTime(null);
return time == null ? 0L
: (time.getTime() % DateTimeUtils.MILLIS_PER_DAY);
}
}
/**
* Accessor that assumes that the underlying value is a TIMESTAMP,
* represented as a java.sql.Timestamp;
* corresponds to {@link java.sql.Types#TIMESTAMP}.
*/
private static class TimestampAccessor extends ObjectAccessor {
public TimestampAccessor(Getter getter) {
super(getter);
}
@Override public Timestamp getTimestamp(Calendar calendar) {
Timestamp timestamp = (Timestamp) getObject();
if (timestamp == null) {
return null;
}
if (calendar != null) {
long v = timestamp.getTime();
v -= calendar.getTimeZone().getOffset(v);
timestamp = new Timestamp(v);
}
return timestamp;
}
@Override public Date getDate(Calendar calendar) {
final Timestamp timestamp = getTimestamp(calendar);
if (timestamp == null) {
return null;
}
return new Date(timestamp.getTime());
}
@Override public Time getTime(Calendar calendar) {
final Timestamp timestamp = getTimestamp(calendar);
if (timestamp == null) {
return null;
}
return new Time(
DateTimeUtils.floorMod(timestamp.getTime(),
DateTimeUtils.MILLIS_PER_DAY));
}
@Override public String getString() {
final long v = getLong();
if (v == 0 && wasNull()) {
return null;
}
return timestampAsString(v, null);
}
@Override public long getLong() {
Timestamp timestamp = getTimestamp(null);
return timestamp == null ? 0 : timestamp.getTime();
}
}
/**
* Accessor that assumes that the underlying value is a TIMESTAMP,
* represented as a java.util.Date;
* corresponds to {@link java.sql.Types#TIMESTAMP}.
*/
private static class TimestampFromUtilDateAccessor extends ObjectAccessor {
private final Calendar localCalendar;
public TimestampFromUtilDateAccessor(Getter getter,
Calendar localCalendar) {
super(getter);
this.localCalendar = localCalendar;
}
@Override public Timestamp getTimestamp(Calendar calendar) {
java.util.Date date = (java.util.Date) getObject();
if (date == null) {
return null;
}
long v = date.getTime();
if (calendar != null) {
v -= calendar.getTimeZone().getOffset(v);
}
return new Timestamp(v);
}
@Override public Date getDate(Calendar calendar) {
final Timestamp timestamp = getTimestamp(calendar);
if (timestamp == null) {
return null;
}
return new Date(timestamp.getTime());
}
@Override public Time getTime(Calendar calendar) {
final Timestamp timestamp = getTimestamp(calendar);
if (timestamp == null) {
return null;
}
return new Time(
DateTimeUtils.floorMod(timestamp.getTime(),
DateTimeUtils.MILLIS_PER_DAY));
}
@Override public String getString() {
java.util.Date date = (java.util.Date) getObject();
if (date == null) {
return null;
}
return timestampAsString(date.getTime(), null);
}
@Override public long getLong() {
Timestamp timestamp = getTimestamp(localCalendar);
return timestamp == null ? 0 : timestamp.getTime();
}
}
/**
* Accessor that assumes that the underlying value is a {@code int};
* corresponds to {@link java.sql.Types#OTHER}.
*/
private static class IntervalYearMonthAccessor extends IntAccessor {
private final TimeUnitRange range;
public IntervalYearMonthAccessor(Getter getter, TimeUnitRange range) {
super(getter);
this.range = range;
}
@Override public String getString() {
final int v = getInt();
if (v == 0 && wasNull()) {
return null;
}
return DateTimeUtils.intervalYearMonthToString(v, range);
}
}
/**
* Accessor that assumes that the underlying value is a {@code long};
* corresponds to {@link java.sql.Types#OTHER}.
*/
private static class IntervalDayTimeAccessor extends LongAccessor {
private final TimeUnitRange range;
private final int scale;
public IntervalDayTimeAccessor(Getter getter, TimeUnitRange range,
int scale) {
super(getter);
this.range = range;
this.scale = scale;
}
@Override public String getString() {
final long v = getLong();
if (v == 0 && wasNull()) {
return null;
}
return DateTimeUtils.intervalDayTimeToString(v, range, scale);
}
}
/**
* Accessor that assumes that the underlying value is an ARRAY;
* corresponds to {@link java.sql.Types#ARRAY}.
*/
static class ArrayAccessor extends AccessorImpl {
final ColumnMetaData.AvaticaType componentType;
final Accessor componentAccessor;
final SlotGetter componentSlotGetter;
final ArrayImpl.Factory factory;
public ArrayAccessor(Getter getter,
ColumnMetaData.AvaticaType componentType, Accessor componentAccessor,
SlotGetter componentSlotGetter, ArrayImpl.Factory factory) {
super(getter);
this.componentType = componentType;
this.componentAccessor = componentAccessor;
this.componentSlotGetter = componentSlotGetter;
this.factory = factory;
}
@Override public Object getObject() {
final Object object = super.getObject();
if (object == null || object instanceof List) {
return object;
}
// The object can be java array in case of user-provided class for row
// storage.
return AvaticaUtils.primitiveList(object);
}
@Override public Array getArray() {
final List list = (List) getObject();
if (list == null) {
return null;
}
return new ArrayImpl(list, this);
}
@Override public String getString() {
final Array array = getArray();
return array == null ? null : array.toString();
}
}
/**
* Accessor that assumes that the underlying value is a STRUCT;
* corresponds to {@link java.sql.Types#STRUCT}.
*/
private static class StructAccessor extends AccessorImpl {
private final List<Accessor> fieldAccessors;
public StructAccessor(Getter getter, List<Accessor> fieldAccessors) {
super(getter);
this.fieldAccessors = fieldAccessors;
}
@Override public Object getObject() {
return getStruct();
}
@Override public Struct getStruct() {
final Object o = super.getObject();
if (o == null) {
return null;
} else if (o instanceof List) {
return new StructImpl((List) o);
} else {
final List<Object> list = new ArrayList<>();
for (Accessor fieldAccessor : fieldAccessors) {
try {
list.add(fieldAccessor.getObject());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return new StructImpl(list);
}
}
}
/**
* Accessor that assumes that the underlying value is an OBJECT;
* corresponds to {@link java.sql.Types#JAVA_OBJECT}.
*/
private static class ObjectAccessor extends AccessorImpl {
public ObjectAccessor(Getter getter) {
super(getter);
}
}
/** Gets a value from a particular field of the current record of this
* cursor. */
protected interface Getter {
Object getObject();
boolean wasNull();
}
/** Abstract implementation of {@link Getter}. */
protected abstract class AbstractGetter implements Getter {
public boolean wasNull() {
return wasNull[0];
}
}
/** Implementation of {@link Getter} that returns the current contents of
* a mutable slot. */
public class SlotGetter implements Getter {
public Object slot;
public Object getObject() {
return slot;
}
public boolean wasNull() {
return slot == null;
}
}
/** Implementation of {@link Getter} that returns the value of a given field
* of the current contents of another getter. */
public class StructGetter implements Getter {
public final Getter getter;
private final ColumnMetaData columnMetaData;
public StructGetter(Getter getter, ColumnMetaData columnMetaData) {
this.getter = getter;
this.columnMetaData = columnMetaData;
}
public Object getObject() {
final Object o = getter.getObject();
if (o instanceof Object[]) {
Object[] objects = (Object[]) o;
return objects[columnMetaData.ordinal];
}
try {
final Field field = o.getClass().getField(columnMetaData.label);
return field.get(getter.getObject());
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
public boolean wasNull() {
return getObject() == null;
}
}
}
// End AbstractCursor.java
| |
/*
* Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.sql;
import com.google.j2objc.annotations.ReflectionSupport;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.NoSuchElementException;
import sun.misc.Unsafe;
/**
* <P>An exception that provides information on a database access
* error or other errors.
*
* <P>Each <code>SQLException</code> provides several kinds of information:
* <UL>
* <LI> a string describing the error. This is used as the Java Exception
* message, available via the method <code>getMesasge</code>.
* <LI> a "SQLstate" string, which follows either the XOPEN SQLstate conventions
* or the SQL:2003 conventions.
* The values of the SQLState string are described in the appropriate spec.
* The <code>DatabaseMetaData</code> method <code>getSQLStateType</code>
* can be used to discover whether the driver returns the XOPEN type or
* the SQL:2003 type.
* <LI> an integer error code that is specific to each vendor. Normally this will
* be the actual error code returned by the underlying database.
* <LI> a chain to a next Exception. This can be used to provide additional
* error information.
* <LI> the causal relationship, if any for this <code>SQLException</code>.
* </UL>
*/
@ReflectionSupport(value = ReflectionSupport.Level.FULL)
public class SQLException extends java.lang.Exception
implements Iterable<Throwable> {
/**
* Constructs a <code>SQLException</code> object with a given
* <code>reason</code>, <code>SQLState</code> and
* <code>vendorCode</code>.
*
* The <code>cause</code> is not initialized, and may subsequently be
* initialized by a call to the
* {@link Throwable#initCause(java.lang.Throwable)} method.
* <p>
* @param reason a description of the exception
* @param SQLState an XOPEN or SQL:2003 code identifying the exception
* @param vendorCode a database vendor-specific exception code
*/
public SQLException(String reason, String SQLState, int vendorCode) {
super(reason);
this.SQLState = SQLState;
this.vendorCode = vendorCode;
if (!(this instanceof SQLWarning)) {
if (DriverManager.getLogWriter() != null) {
DriverManager.println("SQLState(" + SQLState +
") vendor code(" + vendorCode + ")");
printStackTrace(DriverManager.getLogWriter());
}
}
}
/**
* Constructs a <code>SQLException</code> object with a given
* <code>reason</code> and <code>SQLState</code>.
*
* The <code>cause</code> is not initialized, and may subsequently be
* initialized by a call to the
* {@link Throwable#initCause(java.lang.Throwable)} method. The vendor code
* is initialized to 0.
* <p>
* @param reason a description of the exception
* @param SQLState an XOPEN or SQL:2003 code identifying the exception
*/
public SQLException(String reason, String SQLState) {
super(reason);
this.SQLState = SQLState;
this.vendorCode = 0;
if (!(this instanceof SQLWarning)) {
if (DriverManager.getLogWriter() != null) {
printStackTrace(DriverManager.getLogWriter());
DriverManager.println("SQLException: SQLState(" + SQLState + ")");
}
}
}
/**
* Constructs a <code>SQLException</code> object with a given
* <code>reason</code>. The <code>SQLState</code> is initialized to
* <code>null</code> and the vender code is initialized to 0.
*
* The <code>cause</code> is not initialized, and may subsequently be
* initialized by a call to the
* {@link Throwable#initCause(java.lang.Throwable)} method.
* <p>
* @param reason a description of the exception
*/
public SQLException(String reason) {
super(reason);
this.SQLState = null;
this.vendorCode = 0;
if (!(this instanceof SQLWarning)) {
if (DriverManager.getLogWriter() != null) {
printStackTrace(DriverManager.getLogWriter());
}
}
}
/**
* Constructs a <code>SQLException</code> object.
* The <code>reason</code>, <code>SQLState</code> are initialized
* to <code>null</code> and the vendor code is initialized to 0.
*
* The <code>cause</code> is not initialized, and may subsequently be
* initialized by a call to the
* {@link Throwable#initCause(java.lang.Throwable)} method.
* <p>
*/
public SQLException() {
super();
this.SQLState = null;
this.vendorCode = 0;
if (!(this instanceof SQLWarning)) {
if (DriverManager.getLogWriter() != null) {
printStackTrace(DriverManager.getLogWriter());
}
}
}
/**
* Constructs a <code>SQLException</code> object with a given
* <code>cause</code>.
* The <code>SQLState</code> is initialized
* to <code>null</code> and the vendor code is initialized to 0.
* The <code>reason</code> is initialized to <code>null</code> if
* <code>cause==null</code> or to <code>cause.toString()</code> if
* <code>cause!=null</code>.
* <p>
* @param cause the underlying reason for this <code>SQLException</code>
* (which is saved for later retrieval by the <code>getCause()</code> method);
* may be null indicating the cause is non-existent or unknown.
* @since 1.6
*/
public SQLException(Throwable cause) {
super(cause);
if (!(this instanceof SQLWarning)) {
if (DriverManager.getLogWriter() != null) {
printStackTrace(DriverManager.getLogWriter());
}
}
}
/**
* Constructs a <code>SQLException</code> object with a given
* <code>reason</code> and <code>cause</code>.
* The <code>SQLState</code> is initialized to <code>null</code>
* and the vendor code is initialized to 0.
* <p>
* @param reason a description of the exception.
* @param cause the underlying reason for this <code>SQLException</code>
* (which is saved for later retrieval by the <code>getCause()</code> method);
* may be null indicating the cause is non-existent or unknown.
* @since 1.6
*/
public SQLException(String reason, Throwable cause) {
super(reason,cause);
if (!(this instanceof SQLWarning)) {
if (DriverManager.getLogWriter() != null) {
printStackTrace(DriverManager.getLogWriter());
}
}
}
/**
* Constructs a <code>SQLException</code> object with a given
* <code>reason</code>, <code>SQLState</code> and <code>cause</code>.
* The vendor code is initialized to 0.
* <p>
* @param reason a description of the exception.
* @param sqlState an XOPEN or SQL:2003 code identifying the exception
* @param cause the underlying reason for this <code>SQLException</code>
* (which is saved for later retrieval by the
* <code>getCause()</code> method); may be null indicating
* the cause is non-existent or unknown.
* @since 1.6
*/
public SQLException(String reason, String sqlState, Throwable cause) {
super(reason,cause);
this.SQLState = sqlState;
this.vendorCode = 0;
if (!(this instanceof SQLWarning)) {
if (DriverManager.getLogWriter() != null) {
printStackTrace(DriverManager.getLogWriter());
DriverManager.println("SQLState(" + SQLState + ")");
}
}
}
/**
* Constructs a <code>SQLException</code> object with a given
* <code>reason</code>, <code>SQLState</code>, <code>vendorCode</code>
* and <code>cause</code>.
* <p>
* @param reason a description of the exception
* @param sqlState an XOPEN or SQL:2003 code identifying the exception
* @param vendorCode a database vendor-specific exception code
* @param cause the underlying reason for this <code>SQLException</code>
* (which is saved for later retrieval by the <code>getCause()</code> method);
* may be null indicating the cause is non-existent or unknown.
* @since 1.6
*/
public SQLException(String reason, String sqlState, int vendorCode, Throwable cause) {
super(reason,cause);
this.SQLState = sqlState;
this.vendorCode = vendorCode;
if (!(this instanceof SQLWarning)) {
if (DriverManager.getLogWriter() != null) {
DriverManager.println("SQLState(" + SQLState +
") vendor code(" + vendorCode + ")");
printStackTrace(DriverManager.getLogWriter());
}
}
}
/**
* Retrieves the SQLState for this <code>SQLException</code> object.
*
* @return the SQLState value
*/
public String getSQLState() {
return (SQLState);
}
/**
* Retrieves the vendor-specific exception code
* for this <code>SQLException</code> object.
*
* @return the vendor's error code
*/
public int getErrorCode() {
return (vendorCode);
}
/**
* Retrieves the exception chained to this
* <code>SQLException</code> object by setNextException(SQLException ex).
*
* @return the next <code>SQLException</code> object in the chain;
* <code>null</code> if there are none
* @see #setNextException
*/
public SQLException getNextException() {
return (next);
}
/**
* Adds an <code>SQLException</code> object to the end of the chain.
*
* @param ex the new exception that will be added to the end of
* the <code>SQLException</code> chain
* @see #getNextException
*/
public void setNextException(SQLException ex) {
SQLException current = this;
for(;;) {
SQLException next=current.next;
if (next != null) {
current = next;
continue;
}
if (nextUpdater.compareAndSet(current,null,ex)) {
return;
}
current=current.next;
}
}
/**
* Returns an iterator over the chained SQLExceptions. The iterator will
* be used to iterate over each SQLException and its underlying cause
* (if any).
*
* @return an iterator over the chained SQLExceptions and causes in the proper
* order
*
* @since 1.6
*/
public Iterator<Throwable> iterator() {
return new Iterator<Throwable>() {
SQLException firstException = SQLException.this;
SQLException nextException = firstException.getNextException();
Throwable cause = firstException.getCause();
public boolean hasNext() {
if(firstException != null || nextException != null || cause != null)
return true;
return false;
}
public Throwable next() {
Throwable throwable = null;
if(firstException != null){
throwable = firstException;
firstException = null;
}
else if(cause != null){
throwable = cause;
cause = cause.getCause();
}
else if(nextException != null){
throwable = nextException;
cause = nextException.getCause();
nextException = nextException.getNextException();
}
else
throw new NoSuchElementException();
return throwable;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
// J2ObjC-specific: remove dependency on atomic operation to reduce link dependencies.
static class NextExceptionUpdater {
private final Unsafe unsafe = Unsafe.getUnsafe();
private final Field nextExceptionField = getNextExceptionField();
private final long offset = unsafe.objectFieldOffset(nextExceptionField);
public boolean compareAndSet(SQLException obj, SQLException expect, SQLException update) {
return unsafe.compareAndSwapObject(obj, offset, expect, update);
}
private static Field getNextExceptionField() {
try {
return Class.forName("java.sql.SQLException").getDeclaredField("next");
} catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
// Should never happen, since both references are in this unit.
throw new AssertionError();
}
}
}
private static final NextExceptionUpdater nextUpdater = new NextExceptionUpdater();
/**
* @serial
*/
private String SQLState;
/**
* @serial
*/
private int vendorCode;
/**
* @serial
*/
private volatile SQLException next;
private static final long serialVersionUID = 2135244094396331484L;
}
| |
/* 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.flowable.engine.impl.agenda;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.flowable.bpmn.model.Activity;
import org.flowable.bpmn.model.BoundaryEvent;
import org.flowable.bpmn.model.CallActivity;
import org.flowable.bpmn.model.CompensateEventDefinition;
import org.flowable.bpmn.model.EndEvent;
import org.flowable.bpmn.model.EventSubProcess;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.StartEvent;
import org.flowable.bpmn.model.SubProcess;
import org.flowable.bpmn.model.Transaction;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.common.engine.impl.util.CollectionUtil;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.delegate.event.impl.FlowableEventBuilder;
import org.flowable.engine.impl.bpmn.behavior.MultiInstanceActivityBehavior;
import org.flowable.engine.impl.bpmn.helper.ScopeUtil;
import org.flowable.engine.impl.delegate.ActivityBehavior;
import org.flowable.engine.impl.delegate.SubProcessActivityBehavior;
import org.flowable.engine.impl.jobexecutor.AsyncCompleteCallActivityJobHandler;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.ProcessDefinitionUtil;
import org.flowable.job.service.JobService;
import org.flowable.job.service.impl.persistence.entity.JobEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This operations ends an execution and follows the typical BPMN rules to continue the process (if possible).
*
* This operations is typically not scheduled from an {@link ActivityBehavior}, but rather from another operation.
* This happens when the conditions are so that the process can't continue via the
* regular ways and an execution cleanup needs to happen, potentially opening up new ways of continuing the process instance.
*
* @author Joram Barrez
*/
public class EndExecutionOperation extends AbstractOperation {
private static final Logger LOGGER = LoggerFactory.getLogger(EndExecutionOperation.class);
protected boolean forceSynchronous;
public EndExecutionOperation(CommandContext commandContext, ExecutionEntity execution) {
super(commandContext, execution);
}
public EndExecutionOperation(CommandContext commandContext, ExecutionEntity execution, boolean forceSynchronous) {
this(commandContext, execution);
this.forceSynchronous = forceSynchronous;
}
@Override
public void run() {
if (execution.isProcessInstanceType()) {
handleProcessInstanceExecution(execution);
} else {
handleRegularExecution();
}
}
protected void handleProcessInstanceExecution(ExecutionEntity processInstanceExecution) {
ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
String processInstanceId = processInstanceExecution.getId(); // No parent execution == process instance id
LOGGER.debug("No parent execution found. Verifying if process instance {} can be stopped.", processInstanceId);
ExecutionEntity superExecution = processInstanceExecution.getSuperExecution();
if (!forceSynchronous && isAsyncCompleteCallActivity(superExecution)) {
scheduleAsyncCompleteCallActivity(superExecution, processInstanceExecution);
return;
}
// copy variables before destroying the ended sub process instance (call activity)
SubProcessActivityBehavior subProcessActivityBehavior = null;
if (superExecution != null) {
FlowNode superExecutionElement = (FlowNode) superExecution.getCurrentFlowElement();
subProcessActivityBehavior = (SubProcessActivityBehavior) superExecutionElement.getBehavior();
try {
subProcessActivityBehavior.completing(superExecution, processInstanceExecution);
} catch (RuntimeException e) {
LOGGER.error("Error while completing sub process of execution {}", processInstanceExecution, e);
throw e;
} catch (Exception e) {
LOGGER.error("Error while completing sub process of execution {}", processInstanceExecution, e);
throw new FlowableException("Error while completing sub process of execution " + processInstanceExecution, e);
}
}
int activeExecutions = getNumberOfActiveChildExecutionsForProcessInstance(executionEntityManager, processInstanceId);
if (activeExecutions == 0) {
LOGGER.debug("No active executions found. Ending process instance {}", processInstanceId);
// note the use of execution here vs processinstance execution for getting the flow element
executionEntityManager.deleteProcessInstanceExecutionEntity(processInstanceId,
execution.getCurrentFlowElement() != null ? execution.getCurrentFlowElement().getId() : null, null, false, false, true);
} else {
LOGGER.debug("Active executions found. Process instance {} will not be ended.", processInstanceId);
}
Process process = ProcessDefinitionUtil.getProcess(processInstanceExecution.getProcessDefinitionId());
// Execute execution listeners for process end.
if (CollectionUtil.isNotEmpty(process.getExecutionListeners())) {
executeExecutionListeners(process, processInstanceExecution, ExecutionListener.EVENTNAME_END);
}
// and trigger execution afterwards if doing a call activity
if (superExecution != null) {
superExecution.setSubProcessInstance(null);
try {
subProcessActivityBehavior.completed(superExecution);
} catch (RuntimeException e) {
LOGGER.error("Error while completing sub process of execution {}", processInstanceExecution, e);
throw e;
} catch (Exception e) {
LOGGER.error("Error while completing sub process of execution {}", processInstanceExecution, e);
throw new FlowableException("Error while completing sub process of execution " + processInstanceExecution, e);
}
}
}
protected boolean isAsyncCompleteCallActivity(ExecutionEntity superExecution) {
if (superExecution != null) {
FlowNode superExecutionFlowNode = (FlowNode) superExecution.getCurrentFlowElement();
if (superExecutionFlowNode instanceof CallActivity) {
CallActivity callActivity = (CallActivity) superExecutionFlowNode;
return callActivity.isCompleteAsync();
}
}
return false;
}
protected void scheduleAsyncCompleteCallActivity(ExecutionEntity superExecutionEntity, ExecutionEntity childProcessInstanceExecutionEntity) {
JobService jobService = CommandContextUtil.getJobService(commandContext);
JobEntity job = jobService.createJob();
// Needs to be the parent process instance, as the parent needs to be locked to avoid concurrency when multiple call activities are ended
job.setExecutionId(superExecutionEntity.getId());
// Child execution of subprocess is passed as configuration
job.setJobHandlerConfiguration(childProcessInstanceExecutionEntity.getId());
String processInstanceId = superExecutionEntity.getProcessInstanceId() != null ? superExecutionEntity.getProcessInstanceId() : superExecutionEntity.getId();
job.setProcessInstanceId(processInstanceId);
job.setProcessDefinitionId(childProcessInstanceExecutionEntity.getProcessDefinitionId());
job.setTenantId(childProcessInstanceExecutionEntity.getTenantId());
job.setJobHandlerType(AsyncCompleteCallActivityJobHandler.TYPE);
superExecutionEntity.getJobs().add(job);
jobService.createAsyncJob(job, true); // Always exclusive to avoid concurrency problems
jobService.scheduleAsyncJob(job);
}
protected void handleRegularExecution() {
ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
// There will be a parent execution (or else we would be in the process instance handling method)
ExecutionEntity parentExecution = executionEntityManager.findById(execution.getParentId());
// If the execution is a scope, all the child executions must be deleted first.
if (execution.isScope()) {
executionEntityManager.deleteChildExecutions(execution, null, false);
}
// Delete current execution
LOGGER.debug("Ending execution {}", execution.getId());
executionEntityManager.deleteExecutionAndRelatedData(execution, null);
LOGGER.debug("Parent execution found. Continuing process using execution {}", parentExecution.getId());
// When ending an execution in a multi instance subprocess , special care is needed
if (isEndEventInMultiInstanceSubprocess(execution)) {
handleMultiInstanceSubProcess(executionEntityManager, parentExecution);
return;
}
SubProcess subProcess = execution.getCurrentFlowElement().getSubProcess();
if (subProcess instanceof EventSubProcess) {
EventSubProcess eventSubProcess = (EventSubProcess) subProcess;
boolean hasNonInterruptingStartEvent = false;
for (FlowElement eventSubElement : eventSubProcess.getFlowElements()) {
if (eventSubElement instanceof StartEvent) {
StartEvent subStartEvent = (StartEvent) eventSubElement;
if (!subStartEvent.isInterrupting()) {
hasNonInterruptingStartEvent = true;
break;
}
}
}
if (hasNonInterruptingStartEvent) {
executionEntityManager.deleteChildExecutions(parentExecution, null, false);
executionEntityManager.deleteExecutionAndRelatedData(parentExecution, null);
CommandContextUtil.getEventDispatcher(commandContext).dispatchEvent(
FlowableEventBuilder.createActivityEvent(FlowableEngineEventType.ACTIVITY_COMPLETED, subProcess.getId(), subProcess.getName(),
parentExecution.getId(), parentExecution.getProcessInstanceId(), parentExecution.getProcessDefinitionId(), subProcess));
ExecutionEntity subProcessParentExecution = parentExecution.getParent();
if (getNumberOfActiveChildExecutionsForExecution(executionEntityManager, subProcessParentExecution.getId()) == 0) {
if (subProcessParentExecution.getCurrentFlowElement() instanceof SubProcess) {
SubProcess parentSubProcess = (SubProcess) subProcessParentExecution.getCurrentFlowElement();
if (parentSubProcess.getOutgoingFlows().size() > 0) {
ExecutionEntity executionToContinue = handleSubProcessEnd(executionEntityManager, subProcessParentExecution, parentSubProcess);
agenda.planTakeOutgoingSequenceFlowsOperation(executionToContinue, true);
return;
}
}
agenda.planEndExecutionOperation(subProcessParentExecution);
}
return;
}
}
// If there are no more active child executions, the process can be continued
// If not (eg an embedded subprocess still has active elements, we cannot continue)
List<ExecutionEntity> eventScopeExecutions = getEventScopeExecutions(executionEntityManager, parentExecution);
// Event scoped executions need to be deleted when there are no active siblings anymore,
// unless instances of the event subprocess itself. If there are no active siblings anymore,
// the current scope had ended and the event subprocess start event should stop listening to any trigger.
if (!eventScopeExecutions.isEmpty()) {
List<? extends ExecutionEntity> childExecutions = parentExecution.getExecutions();
boolean activeSiblings = false;
for (ExecutionEntity childExecutionEntity : childExecutions) {
if (!isInEventSubProcess(childExecutionEntity) && childExecutionEntity.isActive() && !childExecutionEntity.isEnded()) {
activeSiblings = true;
}
}
if (!activeSiblings) {
for (ExecutionEntity eventScopeExecution : eventScopeExecutions) {
executionEntityManager.deleteExecutionAndRelatedData(eventScopeExecution, null);
}
}
}
if (getNumberOfActiveChildExecutionsForExecution(executionEntityManager, parentExecution.getId()) == 0) {
ExecutionEntity executionToContinue = null;
if (subProcess != null) {
// In case of ending a subprocess: go up in the scopes and continue via the parent scope
// unless its a compensation, then we don't need to do anything and can just end it
if (subProcess.isForCompensation()) {
agenda.planEndExecutionOperation(parentExecution);
} else {
executionToContinue = handleSubProcessEnd(executionEntityManager, parentExecution, subProcess);
}
} else {
// In the 'regular' case (not being in a subprocess), we use the parent execution to
// continue process instance execution
executionToContinue = handleRegularExecutionEnd(executionEntityManager, parentExecution);
}
if (executionToContinue != null) {
// only continue with outgoing sequence flows if the execution is
// not the process instance root execution (otherwise the process instance is finished)
if (executionToContinue.isProcessInstanceType()) {
handleProcessInstanceExecution(executionToContinue);
} else {
agenda.planTakeOutgoingSequenceFlowsOperation(executionToContinue, true);
}
}
}
}
protected ExecutionEntity handleSubProcessEnd(ExecutionEntityManager executionEntityManager, ExecutionEntity parentExecution, SubProcess subProcess) {
ExecutionEntity executionToContinue = null;
// create a new execution to take the outgoing sequence flows
executionToContinue = executionEntityManager.createChildExecution(parentExecution.getParent());
executionToContinue.setCurrentFlowElement(subProcess);
executionToContinue.setActive(false);
boolean hasCompensation = false;
if (subProcess instanceof Transaction) {
hasCompensation = true;
} else {
for (FlowElement subElement : subProcess.getFlowElements()) {
if (subElement instanceof Activity) {
Activity subActivity = (Activity) subElement;
if (CollectionUtil.isNotEmpty(subActivity.getBoundaryEvents())) {
for (BoundaryEvent boundaryEvent : subActivity.getBoundaryEvents()) {
if (CollectionUtil.isNotEmpty(boundaryEvent.getEventDefinitions()) &&
boundaryEvent.getEventDefinitions().get(0) instanceof CompensateEventDefinition) {
hasCompensation = true;
break;
}
}
}
}
}
}
// All executions will be cleaned up afterwards. However, for compensation we need
// a copy of these executions so we can use them later on when the compensation is thrown.
// The following method does exactly that, and moves the executions beneath the process instance.
if (hasCompensation) {
ScopeUtil.createCopyOfSubProcessExecutionForCompensation(parentExecution);
}
executionEntityManager.deleteChildExecutions(parentExecution, null, false);
executionEntityManager.deleteExecutionAndRelatedData(parentExecution, null);
CommandContextUtil.getEventDispatcher(commandContext).dispatchEvent(
FlowableEventBuilder.createActivityEvent(FlowableEngineEventType.ACTIVITY_COMPLETED, subProcess.getId(), subProcess.getName(),
parentExecution.getId(), parentExecution.getProcessInstanceId(), parentExecution.getProcessDefinitionId(), subProcess));
return executionToContinue;
}
protected ExecutionEntity handleRegularExecutionEnd(ExecutionEntityManager executionEntityManager, ExecutionEntity parentExecution) {
ExecutionEntity executionToContinue = null;
if (!parentExecution.isProcessInstanceType()
&& !(parentExecution.getCurrentFlowElement() instanceof SubProcess)) {
parentExecution.setCurrentFlowElement(execution.getCurrentFlowElement());
}
if (execution.getCurrentFlowElement() instanceof SubProcess) {
SubProcess currentSubProcess = (SubProcess) execution.getCurrentFlowElement();
if (currentSubProcess.getOutgoingFlows().size() > 0) {
// create a new execution to take the outgoing sequence flows
executionToContinue = executionEntityManager.createChildExecution(parentExecution);
executionToContinue.setCurrentFlowElement(execution.getCurrentFlowElement());
} else {
if (!parentExecution.getId().equals(parentExecution.getProcessInstanceId())) {
// create a new execution to take the outgoing sequence flows
executionToContinue = executionEntityManager.createChildExecution(parentExecution.getParent());
executionToContinue.setCurrentFlowElement(parentExecution.getCurrentFlowElement());
executionEntityManager.deleteChildExecutions(parentExecution, null, false);
executionEntityManager.deleteExecutionAndRelatedData(parentExecution, null);
} else {
executionToContinue = parentExecution;
}
}
} else {
executionToContinue = parentExecution;
}
return executionToContinue;
}
protected void handleMultiInstanceSubProcess(ExecutionEntityManager executionEntityManager, ExecutionEntity parentExecution) {
List<ExecutionEntity> activeChildExecutions = getActiveChildExecutionsForExecution(executionEntityManager, parentExecution.getId());
boolean containsOtherChildExecutions = false;
for (ExecutionEntity activeExecution : activeChildExecutions) {
if (!activeExecution.getId().equals(execution.getId())) {
containsOtherChildExecutions = true;
}
}
if (!containsOtherChildExecutions) {
// Destroy the current scope (subprocess) and leave via the subprocess
ScopeUtil.createCopyOfSubProcessExecutionForCompensation(parentExecution);
agenda.planDestroyScopeOperation(parentExecution);
SubProcess subProcess = execution.getCurrentFlowElement().getSubProcess();
MultiInstanceActivityBehavior multiInstanceBehavior = (MultiInstanceActivityBehavior) subProcess.getBehavior();
parentExecution.setCurrentFlowElement(subProcess);
multiInstanceBehavior.leave(parentExecution);
}
}
protected boolean isEndEventInMultiInstanceSubprocess(ExecutionEntity executionEntity) {
if (executionEntity.getCurrentFlowElement() instanceof EndEvent) {
SubProcess subProcess = ((EndEvent) execution.getCurrentFlowElement()).getSubProcess();
return !executionEntity.getParent().isProcessInstanceType()
&& subProcess != null
&& subProcess.getLoopCharacteristics() != null
&& subProcess.getBehavior() instanceof MultiInstanceActivityBehavior;
}
return false;
}
protected int getNumberOfActiveChildExecutionsForProcessInstance(ExecutionEntityManager executionEntityManager, String processInstanceId) {
Collection<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByProcessInstanceId(processInstanceId);
int activeExecutions = 0;
for (ExecutionEntity execution : executions) {
if (execution.isActive() && !processInstanceId.equals(execution.getId())) {
activeExecutions++;
}
}
return activeExecutions;
}
protected int getNumberOfActiveChildExecutionsForExecution(ExecutionEntityManager executionEntityManager, String executionId) {
List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByParentExecutionId(executionId);
int activeExecutions = 0;
// Filter out the boundary events
for (ExecutionEntity activeExecution : executions) {
if (!(activeExecution.getCurrentFlowElement() instanceof BoundaryEvent)) {
activeExecutions++;
}
}
return activeExecutions;
}
protected List<ExecutionEntity> getActiveChildExecutionsForExecution(ExecutionEntityManager executionEntityManager, String executionId) {
List<ExecutionEntity> activeChildExecutions = new ArrayList<>();
List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByParentExecutionId(executionId);
for (ExecutionEntity activeExecution : executions) {
if (!(activeExecution.getCurrentFlowElement() instanceof BoundaryEvent)) {
activeChildExecutions.add(activeExecution);
}
}
return activeChildExecutions;
}
protected List<ExecutionEntity> getEventScopeExecutions(ExecutionEntityManager executionEntityManager, ExecutionEntity parentExecution) {
List<ExecutionEntity> eventScopeExecutions = new ArrayList<>(1);
List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByParentExecutionId(parentExecution.getId());
for (ExecutionEntity childExecution : executions) {
if (childExecution.isEventScope()) {
eventScopeExecutions.add(childExecution);
}
}
return eventScopeExecutions;
}
protected boolean allChildExecutionsEnded(ExecutionEntity parentExecutionEntity, ExecutionEntity executionEntityToIgnore) {
for (ExecutionEntity childExecutionEntity : parentExecutionEntity.getExecutions()) {
if (executionEntityToIgnore == null || !executionEntityToIgnore.getId().equals(childExecutionEntity.getId())) {
if (!childExecutionEntity.isEnded()) {
return false;
}
if (childExecutionEntity.getExecutions() != null && childExecutionEntity.getExecutions().size() > 0) {
if (!allChildExecutionsEnded(childExecutionEntity, executionEntityToIgnore)) {
return false;
}
}
}
}
return true;
}
protected boolean isInEventSubProcess(ExecutionEntity executionEntity) {
ExecutionEntity currentExecutionEntity = executionEntity;
while (currentExecutionEntity != null) {
if (currentExecutionEntity.getCurrentFlowElement() instanceof EventSubProcess) {
return true;
}
currentExecutionEntity = currentExecutionEntity.getParent();
}
return false;
}
}
| |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.util.io;
import alluxio.AlluxioURI;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.InvalidPathException;
import alluxio.util.OSUtils;
import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import org.apache.commons.io.FilenameUtils;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.concurrent.ThreadSafe;
/**
* Utilities related to both Alluxio paths like {@link AlluxioURI} and local file paths.
*/
@ThreadSafe
public final class PathUtils {
private static final String TEMPORARY_SUFFIX_FORMAT = ".alluxio.0x%016X.tmp";
private static final int TEMPORARY_SUFFIX_LENGTH =
String.format(TEMPORARY_SUFFIX_FORMAT, 0).length();
/**
* Checks and normalizes the given path.
*
* @param path The path to clean up
* @return a normalized version of the path, with single separators between path components and
* dot components resolved
* @throws InvalidPathException if the path is invalid
*/
public static String cleanPath(String path) throws InvalidPathException {
validatePath(path);
return FilenameUtils.separatorsToUnix(FilenameUtils.normalizeNoEndSeparator(path));
}
/**
* Joins each element in paths in order, separated by {@link AlluxioURI#SEPARATOR}.
* <p>
* For example,
*
* <pre>
* {@code
* concatPath("/myroot/", "dir", 1L, "filename").equals("/myroot/dir/1/filename");
* concatPath("alluxio://myroot", "dir", "filename").equals("alluxio://myroot/dir/filename");
* concatPath("myroot/", "/dir/", "filename").equals("myroot/dir/filename");
* concatPath("/", "dir", "filename").equals("/dir/filename");
* }
* </pre>
*
* Note that empty element in base or paths is ignored.
*
* @param base base path
* @param paths paths to concatenate
* @return joined path
* @throws IllegalArgumentException if base or paths is null
*/
public static String concatPath(Object base, Object... paths) throws IllegalArgumentException {
Preconditions.checkArgument(base != null, "Failed to concatPath: base is null");
Preconditions.checkArgument(paths != null, "Failed to concatPath: a null set of paths");
List<String> trimmedPathList = new ArrayList<>();
String trimmedBase =
CharMatcher.is(AlluxioURI.SEPARATOR.charAt(0)).trimTrailingFrom(base.toString().trim());
trimmedPathList.add(trimmedBase);
for (Object path : paths) {
if (path == null) {
continue;
}
String trimmedPath =
CharMatcher.is(AlluxioURI.SEPARATOR.charAt(0)).trimFrom(path.toString().trim());
if (!trimmedPath.isEmpty()) {
trimmedPathList.add(trimmedPath);
}
}
if (trimmedPathList.size() == 1 && trimmedBase.isEmpty()) {
// base must be "[/]+"
return AlluxioURI.SEPARATOR;
}
return Joiner.on(AlluxioURI.SEPARATOR).join(trimmedPathList);
}
/**
* Gets the parent of the file at a path.
*
* @param path The path
* @return the parent path of the file; this is "/" if the given path is the root
* @throws InvalidPathException if the path is invalid
*/
public static String getParent(String path) throws InvalidPathException {
String cleanedPath = cleanPath(path);
String name = FilenameUtils.getName(cleanedPath);
String parent = cleanedPath.substring(0, cleanedPath.length() - name.length() - 1);
if (parent.isEmpty()) {
// The parent is the root path
return AlluxioURI.SEPARATOR;
}
return parent;
}
/**
* Gets the path components of the given path. The first component will be an empty string.
*
* "/a/b/c" => {"", "a", "b", "c"}
* "/" => {""}
*
* @param path The path to split
* @return the path split into components
* @throws InvalidPathException if the path is invalid
*/
public static String[] getPathComponents(String path) throws InvalidPathException {
path = cleanPath(path);
if (isRoot(path)) {
return new String[]{""};
}
return path.split(AlluxioURI.SEPARATOR);
}
/**
* Removes the prefix from the path, yielding a relative path from the second path to the first.
*
* If the paths are the same, this method returns the empty string.
*
* @param path the full path
* @param prefix the prefix to remove
* @return the path with the prefix removed
* @throws InvalidPathException if either of the arguments are not valid paths
*/
public static String subtractPaths(String path, String prefix) throws InvalidPathException {
String cleanedPath = cleanPath(path);
String cleanedPrefix = cleanPath(prefix);
if (cleanedPath.equals(cleanedPrefix)) {
return "";
}
if (!hasPrefix(cleanedPath, cleanedPrefix)) {
throw new RuntimeException(
String.format("Cannot subtract %s from %s because it is not a prefix", prefix, path));
}
// The only clean path which ends in '/' is the root.
int prefixLen = cleanedPrefix.length();
int charsToDrop = PathUtils.isRoot(cleanedPrefix) ? prefixLen : prefixLen + 1;
return cleanedPath.substring(charsToDrop, cleanedPath.length());
}
/**
* Checks whether the given path contains the given prefix. The comparison happens at a component
* granularity; for example, {@code hasPrefix(/dir/file, /dir)} should evaluate to true, while
* {@code hasPrefix(/dir/file, /d)} should evaluate to false.
*
* @param path a path
* @param prefix a prefix
* @return whether the given path has the given prefix
* @throws InvalidPathException when the path or prefix is invalid
*/
public static boolean hasPrefix(String path, String prefix) throws InvalidPathException {
String[] pathComponents = getPathComponents(path);
String[] prefixComponents = getPathComponents(prefix);
if (pathComponents.length < prefixComponents.length) {
return false;
}
for (int i = 0; i < prefixComponents.length; i++) {
if (!pathComponents[i].equals(prefixComponents[i])) {
return false;
}
}
return true;
}
/**
* Checks if the given path is the root.
*
* @param path The path to check
* @return true if the path is the root
* @throws InvalidPathException if the path is invalid
*/
public static boolean isRoot(String path) throws InvalidPathException {
return AlluxioURI.SEPARATOR.equals(cleanPath(path));
}
/**
* Checks if the given path is properly formed.
*
* @param path The path to check
* @throws InvalidPathException If the path is not properly formed
*/
public static void validatePath(String path) throws InvalidPathException {
boolean invalid = (path == null || path.isEmpty() || path.contains(" "));
if (!OSUtils.isWindows()) {
invalid = (invalid || !path.startsWith(AlluxioURI.SEPARATOR));
}
if (invalid) {
throw new InvalidPathException(ExceptionMessage.PATH_INVALID.getMessage(path));
}
}
/**
* Generates a deterministic temporary file name for the a path and a file id and a nonce.
*
* @param nonce a nonce token
* @param path a file path
* @return a deterministic temporary file name
*/
public static String temporaryFileName(long nonce, String path) {
return path + String.format(TEMPORARY_SUFFIX_FORMAT, nonce);
}
/**
* @param path the path of the file, possibly temporary
* @return the permanent path of the file if it was temporary, or the original path if it was not
*/
public static String getPermanentFileName(String path) {
if (isTemporaryFileName(path)) {
return path.substring(0, path.length() - TEMPORARY_SUFFIX_LENGTH);
}
return path;
}
/**
* Determines whether the given path is a temporary file name generated by Alluxio.
*
* @param path the path to check
* @return whether the given path is a temporary file name generated by Alluxio
*/
public static boolean isTemporaryFileName(String path) {
return path.matches("^.*\\.alluxio\\.0x[0-9A-F]{16}\\.tmp$");
}
/**
* Creates a unique path based off the caller.
*
* @return unique path based off the caller
*/
public static String uniqPath() {
StackTraceElement caller = new Throwable().getStackTrace()[1];
long time = System.nanoTime();
return "/" + caller.getClassName() + "/" + caller.getMethodName() + "/" + time;
}
/**
* Adds a trailing separator if it does not exist in path.
*
* @param path the file name
* @param separator trailing separator to add
* @return updated path with trailing separator
*/
public static String normalizePath(String path, String separator) {
return path.endsWith(separator) ? path : path + separator;
}
private PathUtils() {} // prevent instantiation
}
| |
package com.phonemetra.turbo.launcher;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDiskIOException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import com.phonemetra.turbo.launcher.R;
abstract class SoftReferenceThreadLocal<T> {
private ThreadLocal<SoftReference<T>> mThreadLocal;
public SoftReferenceThreadLocal() {
mThreadLocal = new ThreadLocal<SoftReference<T>>();
}
abstract T initialValue();
public void set(T t) {
mThreadLocal.set(new SoftReference<T>(t));
}
public T get() {
SoftReference<T> reference = mThreadLocal.get();
T obj;
if (reference == null) {
obj = initialValue();
mThreadLocal.set(new SoftReference<T>(obj));
return obj;
} else {
obj = reference.get();
if (obj == null) {
obj = initialValue();
mThreadLocal.set(new SoftReference<T>(obj));
}
return obj;
}
}
}
class CanvasCache extends SoftReferenceThreadLocal<Canvas> {
@Override
protected Canvas initialValue() {
return new Canvas();
}
}
class PaintCache extends SoftReferenceThreadLocal<Paint> {
@Override
protected Paint initialValue() {
return null;
}
}
class BitmapCache extends SoftReferenceThreadLocal<Bitmap> {
@Override
protected Bitmap initialValue() {
return null;
}
}
class RectCache extends SoftReferenceThreadLocal<Rect> {
@Override
protected Rect initialValue() {
return new Rect();
}
}
class BitmapFactoryOptionsCache extends SoftReferenceThreadLocal<BitmapFactory.Options> {
@Override
protected BitmapFactory.Options initialValue() {
return new BitmapFactory.Options();
}
}
public class WidgetPreviewLoader {
static final String TAG = "WidgetPreviewLoader";
static final String ANDROID_INCREMENTAL_VERSION_NAME_KEY = "android.incremental.version";
private int mPreviewBitmapWidth;
private int mPreviewBitmapHeight;
private String mSize;
private Context mContext;
private PackageManager mPackageManager;
private PagedViewCellLayout mWidgetSpacingLayout;
// Used for drawing shortcut previews
private BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
private PaintCache mCachedShortcutPreviewPaint = new PaintCache();
private CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
// Used for drawing widget previews
private CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
private RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
private RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
private PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
private String mCachedSelectQuery;
private BitmapFactoryOptionsCache mCachedBitmapFactoryOptions = new BitmapFactoryOptionsCache();
private int mAppIconSize;
private IconCache mIconCache;
private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
private CacheDb mDb;
private HashMap<String, WeakReference<Bitmap>> mLoadedPreviews;
private ArrayList<SoftReference<Bitmap>> mUnusedBitmaps;
private static HashSet<String> sInvalidPackages;
static {
sInvalidPackages = new HashSet<String>();
}
public WidgetPreviewLoader(Context context) {
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
mContext = context;
mPackageManager = mContext.getPackageManager();
mAppIconSize = grid.iconSizePx;
mIconCache = app.getIconCache();
mDb = app.getWidgetPreviewCacheDb();
mLoadedPreviews = new HashMap<String, WeakReference<Bitmap>>();
mUnusedBitmaps = new ArrayList<SoftReference<Bitmap>>();
SharedPreferences sp = context.getSharedPreferences(
LauncherAppState.getSharedPreferencesKey(), Context.MODE_PRIVATE);
final String lastVersionName = sp.getString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, null);
final String versionName = android.os.Build.VERSION.INCREMENTAL;
if (!versionName.equals(lastVersionName)) {
// clear all the previews whenever the system version changes, to ensure that previews
// are up-to-date for any apps that might have been updated with the system
clearDb();
SharedPreferences.Editor editor = sp.edit();
editor.putString(ANDROID_INCREMENTAL_VERSION_NAME_KEY, versionName);
editor.commit();
}
}
public void recreateDb() {
LauncherAppState app = LauncherAppState.getInstance();
app.recreateWidgetPreviewDb();
mDb = app.getWidgetPreviewCacheDb();
}
public void setPreviewSize(int previewWidth, int previewHeight,
PagedViewCellLayout widgetSpacingLayout) {
mPreviewBitmapWidth = previewWidth;
mPreviewBitmapHeight = previewHeight;
mSize = previewWidth + "x" + previewHeight;
mWidgetSpacingLayout = widgetSpacingLayout;
}
public Bitmap getPreview(final Object o) {
final String name = getObjectName(o);
final String packageName = getObjectPackage(o);
// check if the package is valid
boolean packageValid = true;
synchronized(sInvalidPackages) {
packageValid = !sInvalidPackages.contains(packageName);
}
if (!packageValid) {
return null;
}
if (packageValid) {
synchronized(mLoadedPreviews) {
// check if it exists in our existing cache
if (mLoadedPreviews.containsKey(name) && mLoadedPreviews.get(name).get() != null) {
return mLoadedPreviews.get(name).get();
}
}
}
Bitmap unusedBitmap = null;
synchronized(mUnusedBitmaps) {
// not in cache; we need to load it from the db
while ((unusedBitmap == null || !unusedBitmap.isMutable() ||
unusedBitmap.getWidth() != mPreviewBitmapWidth ||
unusedBitmap.getHeight() != mPreviewBitmapHeight)
&& mUnusedBitmaps.size() > 0) {
unusedBitmap = mUnusedBitmaps.remove(0).get();
}
if (unusedBitmap != null) {
final Canvas c = mCachedAppWidgetPreviewCanvas.get();
c.setBitmap(unusedBitmap);
c.drawColor(0, PorterDuff.Mode.CLEAR);
c.setBitmap(null);
}
}
if (unusedBitmap == null) {
unusedBitmap = Bitmap.createBitmap(mPreviewBitmapWidth, mPreviewBitmapHeight,
Bitmap.Config.ARGB_8888);
}
Bitmap preview = null;
if (packageValid) {
preview = readFromDb(name, unusedBitmap);
}
if (preview != null) {
synchronized(mLoadedPreviews) {
mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
}
return preview;
} else {
// it's not in the db... we need to generate it
final Bitmap generatedPreview = generatePreview(o, unusedBitmap);
preview = generatedPreview;
if (preview != unusedBitmap) {
throw new RuntimeException("generatePreview is not recycling the bitmap " + o);
}
synchronized(mLoadedPreviews) {
mLoadedPreviews.put(name, new WeakReference<Bitmap>(preview));
}
// write to db on a thread pool... this can be done lazily and improves the performance
// of the first time widget previews are loaded
new AsyncTask<Void, Void, Void>() {
public Void doInBackground(Void ... args) {
writeToDb(o, generatedPreview);
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
return preview;
}
}
public void recycleBitmap(Object o, Bitmap bitmapToRecycle) {
String name = getObjectName(o);
synchronized (mLoadedPreviews) {
if (mLoadedPreviews.containsKey(name)) {
Bitmap b = mLoadedPreviews.get(name).get();
if (b == bitmapToRecycle) {
mLoadedPreviews.remove(name);
if (bitmapToRecycle.isMutable()) {
synchronized (mUnusedBitmaps) {
mUnusedBitmaps.add(new SoftReference<Bitmap>(b));
}
}
} else {
throw new RuntimeException("Bitmap passed in doesn't match up");
}
}
}
}
static class CacheDb extends SQLiteOpenHelper {
final static int DB_VERSION = 2;
final static String DB_NAME = "widgetpreviews.db";
final static String TABLE_NAME = "shortcut_and_widget_previews";
final static String COLUMN_NAME = "name";
final static String COLUMN_SIZE = "size";
final static String COLUMN_PREVIEW_BITMAP = "preview_bitmap";
Context mContext;
public CacheDb(Context context) {
super(context, new File(context.getCacheDir(), DB_NAME).getPath(), null, DB_VERSION);
// Store the context for later use
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
COLUMN_NAME + " TEXT NOT NULL, " +
COLUMN_SIZE + " TEXT NOT NULL, " +
COLUMN_PREVIEW_BITMAP + " BLOB NOT NULL, " +
"PRIMARY KEY (" + COLUMN_NAME + ", " + COLUMN_SIZE + ") " +
");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
// Delete all the records; they'll be repopulated as this is a cache
db.execSQL("DELETE FROM " + TABLE_NAME);
}
}
}
private static final String WIDGET_PREFIX = "Widget:";
private static final String SHORTCUT_PREFIX = "Shortcut:";
private static String getObjectName(Object o) {
// should cache the string builder
StringBuilder sb = new StringBuilder();
String output;
if (o instanceof AppWidgetProviderInfo) {
sb.append(WIDGET_PREFIX);
sb.append(((AppWidgetProviderInfo) o).provider.flattenToString());
output = sb.toString();
sb.setLength(0);
} else {
sb.append(SHORTCUT_PREFIX);
ResolveInfo info = (ResolveInfo) o;
sb.append(new ComponentName(info.activityInfo.packageName,
info.activityInfo.name).flattenToString());
output = sb.toString();
sb.setLength(0);
}
return output;
}
private String getObjectPackage(Object o) {
if (o instanceof AppWidgetProviderInfo) {
return ((AppWidgetProviderInfo) o).provider.getPackageName();
} else {
ResolveInfo info = (ResolveInfo) o;
return info.activityInfo.packageName;
}
}
private void writeToDb(Object o, Bitmap preview) {
String name = getObjectName(o);
SQLiteDatabase db = mDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CacheDb.COLUMN_NAME, name);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
values.put(CacheDb.COLUMN_SIZE, mSize);
try {
db.insert(CacheDb.TABLE_NAME, null, values);
} catch (SQLiteDiskIOException e) {
recreateDb();
}
}
private void clearDb() {
SQLiteDatabase db = mDb.getWritableDatabase();
// Delete everything
try {
db.delete(CacheDb.TABLE_NAME, null, null);
} catch (SQLiteDiskIOException e) {
}
}
public static void removePackageFromDb(final CacheDb cacheDb, final String packageName) {
synchronized(sInvalidPackages) {
sInvalidPackages.add(packageName);
}
new AsyncTask<Void, Void, Void>() {
public Void doInBackground(Void ... args) {
SQLiteDatabase db = cacheDb.getWritableDatabase();
try {
db.delete(CacheDb.TABLE_NAME,
CacheDb.COLUMN_NAME + " LIKE ? OR " +
CacheDb.COLUMN_NAME + " LIKE ?", // SELECT query
new String[] {
WIDGET_PREFIX + packageName + "/%",
SHORTCUT_PREFIX + packageName + "/%"
} // args to SELECT query
);
} catch (SQLiteDiskIOException e) {
}
synchronized(sInvalidPackages) {
sInvalidPackages.remove(packageName);
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
}
public static void removeItemFromDb(final CacheDb cacheDb, final String objectName) {
new AsyncTask<Void, Void, Void>() {
public Void doInBackground(Void ... args) {
SQLiteDatabase db = cacheDb.getWritableDatabase();
try {
db.delete(CacheDb.TABLE_NAME,
CacheDb.COLUMN_NAME + " = ? ", // SELECT query
new String[] { objectName }); // args to SELECT query
} catch (SQLiteDiskIOException e) {
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
}
private Bitmap readFromDb(String name, Bitmap b) {
if (mCachedSelectQuery == null) {
mCachedSelectQuery = CacheDb.COLUMN_NAME + " = ? AND " +
CacheDb.COLUMN_SIZE + " = ?";
}
SQLiteDatabase db = mDb.getReadableDatabase();
Cursor result;
try {
result = db.query(CacheDb.TABLE_NAME,
new String[] { CacheDb.COLUMN_PREVIEW_BITMAP }, // cols to return
mCachedSelectQuery, // select query
new String[] { name, mSize }, // args to select query
null,
null,
null,
null);
} catch (SQLiteDiskIOException e) {
recreateDb();
return null;
}
if (result.getCount() > 0) {
result.moveToFirst();
byte[] blob = result.getBlob(0);
result.close();
final BitmapFactory.Options opts = mCachedBitmapFactoryOptions.get();
opts.inBitmap = b;
opts.inSampleSize = 1;
try {
return BitmapFactory.decodeByteArray(blob, 0, blob.length, opts);
} catch (IllegalArgumentException e) {
removeItemFromDb(mDb, name);
return null;
}
} else {
result.close();
return null;
}
}
public Bitmap generatePreview(Object info, Bitmap preview) {
if (preview != null &&
(preview.getWidth() != mPreviewBitmapWidth ||
preview.getHeight() != mPreviewBitmapHeight)) {
throw new RuntimeException("Improperly sized bitmap passed as argument");
}
if (info instanceof AppWidgetProviderInfo) {
return generateWidgetPreview((AppWidgetProviderInfo) info, preview);
} else {
return generateShortcutPreview(
(ResolveInfo) info, mPreviewBitmapWidth, mPreviewBitmapHeight, preview);
}
}
public Bitmap generateWidgetPreview(AppWidgetProviderInfo info, Bitmap preview) {
int[] cellSpans = Launcher.getSpanForWidget(mContext, info);
int maxWidth = maxWidthForWidgetPreview(cellSpans[0]);
int maxHeight = maxHeightForWidgetPreview(cellSpans[1]);
return generateWidgetPreview(info.provider, info.previewImage, info.icon,
cellSpans[0], cellSpans[1], maxWidth, maxHeight, preview, null);
}
public int maxWidthForWidgetPreview(int spanX) {
return Math.min(mPreviewBitmapWidth,
mWidgetSpacingLayout.estimateCellWidth(spanX));
}
public int maxHeightForWidgetPreview(int spanY) {
return Math.min(mPreviewBitmapHeight,
mWidgetSpacingLayout.estimateCellHeight(spanY));
}
public Bitmap generateWidgetPreview(ComponentName provider, int previewImage,
int iconId, int cellHSpan, int cellVSpan, int maxPreviewWidth, int maxPreviewHeight,
Bitmap preview, int[] preScaledWidthOut) {
// Load the preview image if possible
String packageName = provider.getPackageName();
if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;
if (maxPreviewHeight < 0) maxPreviewHeight = Integer.MAX_VALUE;
Drawable drawable = null;
if (previewImage != 0) {
drawable = mPackageManager.getDrawable(packageName, previewImage, null);
if (drawable == null) {
Log.w(TAG, "Can't load widget preview drawable 0x" +
Integer.toHexString(previewImage) + " for provider: " + provider);
}
}
int previewWidth;
int previewHeight;
Bitmap defaultPreview = null;
boolean widgetPreviewExists = (drawable != null);
if (widgetPreviewExists) {
previewWidth = drawable.getIntrinsicWidth();
previewHeight = drawable.getIntrinsicHeight();
} else {
// Generate a preview image if we couldn't load one
if (cellHSpan < 1) cellHSpan = 1;
if (cellVSpan < 1) cellVSpan = 1;
BitmapDrawable previewDrawable = (BitmapDrawable) mContext.getResources()
.getDrawable(R.drawable.widget_tile);
final int previewDrawableWidth = previewDrawable
.getIntrinsicWidth();
final int previewDrawableHeight = previewDrawable
.getIntrinsicHeight();
previewWidth = previewDrawableWidth * cellHSpan;
previewHeight = previewDrawableHeight * cellVSpan;
defaultPreview = Bitmap.createBitmap(previewWidth, previewHeight,
Config.ARGB_8888);
final Canvas c = mCachedAppWidgetPreviewCanvas.get();
c.setBitmap(defaultPreview);
previewDrawable.setBounds(0, 0, previewWidth, previewHeight);
previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
Shader.TileMode.REPEAT);
previewDrawable.draw(c);
c.setBitmap(null);
// Draw the icon in the top left corner
int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
int smallestSide = Math.min(previewWidth, previewHeight);
float iconScale = Math.min((float) smallestSide
/ (mAppIconSize + 2 * minOffset), 1f);
try {
Drawable icon = null;
int hoffset =
(int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
int yoffset =
(int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
if (iconId > 0)
icon = mIconCache.getFullResIcon(packageName, iconId);
if (icon != null) {
renderDrawableToBitmap(icon, defaultPreview, hoffset,
yoffset, (int) (mAppIconSize * iconScale),
(int) (mAppIconSize * iconScale));
}
} catch (Resources.NotFoundException e) {
}
}
// Scale to fit width only - let the widget preview be clipped in the
// vertical dimension
float scale = 1f;
if (preScaledWidthOut != null) {
preScaledWidthOut[0] = previewWidth;
}
if (previewWidth > maxPreviewWidth) {
scale = maxPreviewWidth / (float) previewWidth;
}
if (scale != 1f) {
previewWidth = (int) (scale * previewWidth);
previewHeight = (int) (scale * previewHeight);
}
// If a bitmap is passed in, we use it; otherwise, we create a bitmap of the right size
if (preview == null) {
preview = Bitmap.createBitmap(previewWidth, previewHeight, Config.ARGB_8888);
}
// Draw the scaled preview into the final bitmap
int x = (preview.getWidth() - previewWidth) / 2;
if (widgetPreviewExists) {
renderDrawableToBitmap(drawable, preview, x, 0, previewWidth,
previewHeight);
} else {
final Canvas c = mCachedAppWidgetPreviewCanvas.get();
final Rect src = mCachedAppWidgetPreviewSrcRect.get();
final Rect dest = mCachedAppWidgetPreviewDestRect.get();
c.setBitmap(preview);
src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
dest.set(x, 0, x + previewWidth, previewHeight);
Paint p = mCachedAppWidgetPreviewPaint.get();
if (p == null) {
p = new Paint();
p.setFilterBitmap(true);
mCachedAppWidgetPreviewPaint.set(p);
}
c.drawBitmap(defaultPreview, src, dest, p);
c.setBitmap(null);
}
return preview;
}
private Bitmap generateShortcutPreview(
ResolveInfo info, int maxWidth, int maxHeight, Bitmap preview) {
Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
final Canvas c = mCachedShortcutPreviewCanvas.get();
if (tempBitmap == null ||
tempBitmap.getWidth() != maxWidth ||
tempBitmap.getHeight() != maxHeight) {
tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
mCachedShortcutPreviewBitmap.set(tempBitmap);
} else {
c.setBitmap(tempBitmap);
c.drawColor(0, PorterDuff.Mode.CLEAR);
c.setBitmap(null);
}
// Render the icon
Drawable icon = mIconCache.getFullResIcon(info);
int paddingTop = mContext.
getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
int paddingLeft = mContext.
getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
int paddingRight = mContext.
getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
renderDrawableToBitmap(
icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
if (preview != null &&
(preview.getWidth() != maxWidth || preview.getHeight() != maxHeight)) {
throw new RuntimeException("Improperly sized bitmap passed as argument");
} else if (preview == null) {
preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
}
c.setBitmap(preview);
// Draw a desaturated/scaled version of the icon in the background as a watermark
Paint p = mCachedShortcutPreviewPaint.get();
if (p == null) {
p = new Paint();
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);
p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
p.setAlpha((int) (255 * 0.06f));
mCachedShortcutPreviewPaint.set(p);
}
c.drawBitmap(tempBitmap, 0, 0, p);
c.setBitmap(null);
renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
return preview;
}
public static void renderDrawableToBitmap(
Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
}
private static void renderDrawableToBitmap(
Drawable d, Bitmap bitmap, int x, int y, int w, int h,
float scale) {
if (bitmap != null) {
Canvas c = new Canvas(bitmap);
c.scale(scale, scale);
Rect oldBounds = d.copyBounds();
d.setBounds(x, y, x + w, y + h);
d.draw(c);
d.setBounds(oldBounds); // Restore the bounds
c.setBitmap(null);
}
}
}
| |
// Copyright (C) 2014 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.gerrit.server;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchLineComment;
import com.google.gerrit.reviewdb.client.PatchLineComment.Status;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.RevId;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.config.AllUsersNameProvider;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.notedb.ChangeUpdate;
import com.google.gerrit.server.notedb.DraftCommentNotes;
import com.google.gerrit.server.notedb.NotesMigration;
import com.google.gerrit.server.patch.PatchList;
import com.google.gerrit.server.patch.PatchListCache;
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.RefDatabase;
import org.eclipse.jgit.lib.Repository;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Utility functions to manipulate PatchLineComments.
* <p>
* These methods either query for and update PatchLineComments in the NoteDb or
* ReviewDb, depending on the state of the NotesMigration.
*/
@Singleton
public class PatchLineCommentsUtil {
private final GitRepositoryManager repoManager;
private final AllUsersName allUsers;
private final DraftCommentNotes.Factory draftFactory;
private final NotesMigration migration;
@VisibleForTesting
@Inject
public PatchLineCommentsUtil(GitRepositoryManager repoManager,
AllUsersNameProvider allUsersProvider,
DraftCommentNotes.Factory draftFactory,
NotesMigration migration) {
this.repoManager = repoManager;
this.allUsers = allUsersProvider.get();
this.draftFactory = draftFactory;
this.migration = migration;
}
public Optional<PatchLineComment> get(ReviewDb db, ChangeNotes notes,
PatchLineComment.Key key) throws OrmException {
if (!migration.readComments()) {
return Optional.fromNullable(db.patchComments().get(key));
}
for (PatchLineComment c : publishedByChange(db, notes)) {
if (key.equals(c.getKey())) {
return Optional.of(c);
}
}
for (PatchLineComment c : draftByChange(db, notes)) {
if (key.equals(c.getKey())) {
return Optional.of(c);
}
}
return Optional.absent();
}
public List<PatchLineComment> publishedByChange(ReviewDb db,
ChangeNotes notes) throws OrmException {
if (!migration.readComments()) {
return sort(byCommentStatus(
db.patchComments().byChange(notes.getChangeId()), Status.PUBLISHED));
}
notes.load();
List<PatchLineComment> comments = Lists.newArrayList();
comments.addAll(notes.getBaseComments().values());
comments.addAll(notes.getPatchSetComments().values());
return sort(comments);
}
public List<PatchLineComment> draftByChange(ReviewDb db,
ChangeNotes notes) throws OrmException {
if (!migration.readComments()) {
return sort(byCommentStatus(
db.patchComments().byChange(notes.getChangeId()), Status.DRAFT));
}
List<PatchLineComment> comments = Lists.newArrayList();
Iterable<String> filtered = getDraftRefs(notes.getChangeId());
for (String refName : filtered) {
Account.Id account = Account.Id.fromRefPart(refName);
if (account != null) {
comments.addAll(draftByChangeAuthor(db, notes, account));
}
}
return sort(comments);
}
private static List<PatchLineComment> byCommentStatus(
ResultSet<PatchLineComment> comments,
final PatchLineComment.Status status) {
return Lists.newArrayList(
Iterables.filter(comments, new Predicate<PatchLineComment>() {
@Override
public boolean apply(PatchLineComment input) {
return (input.getStatus() == status);
}
})
);
}
public List<PatchLineComment> byPatchSet(ReviewDb db,
ChangeNotes notes, PatchSet.Id psId) throws OrmException {
if (!migration.readComments()) {
return sort(db.patchComments().byPatchSet(psId).toList());
}
List<PatchLineComment> comments = Lists.newArrayList();
comments.addAll(publishedByPatchSet(db, notes, psId));
Iterable<String> filtered = getDraftRefs(notes.getChangeId());
for (String refName : filtered) {
Account.Id account = Account.Id.fromRefPart(refName);
if (account != null) {
comments.addAll(draftByPatchSetAuthor(db, psId, account, notes));
}
}
return sort(comments);
}
public List<PatchLineComment> publishedByChangeFile(ReviewDb db,
ChangeNotes notes, Change.Id changeId, String file) throws OrmException {
if (!migration.readComments()) {
return sort(
db.patchComments().publishedByChangeFile(changeId, file).toList());
}
notes.load();
List<PatchLineComment> comments = Lists.newArrayList();
addCommentsOnFile(comments, notes.getBaseComments().values(), file);
addCommentsOnFile(comments, notes.getPatchSetComments().values(),
file);
return sort(comments);
}
public List<PatchLineComment> publishedByPatchSet(ReviewDb db,
ChangeNotes notes, PatchSet.Id psId) throws OrmException {
if (!migration.readComments()) {
return sort(
db.patchComments().publishedByPatchSet(psId).toList());
}
notes.load();
List<PatchLineComment> comments = new ArrayList<PatchLineComment>();
comments.addAll(notes.getPatchSetComments().get(psId));
comments.addAll(notes.getBaseComments().get(psId));
return sort(comments);
}
public List<PatchLineComment> draftByPatchSetAuthor(ReviewDb db,
PatchSet.Id psId, Account.Id author, ChangeNotes notes)
throws OrmException {
if (!migration.readComments()) {
return sort(
db.patchComments().draftByPatchSetAuthor(psId, author).toList());
}
List<PatchLineComment> comments = Lists.newArrayList();
comments.addAll(notes.getDraftBaseComments(author).row(psId).values());
comments.addAll(notes.getDraftPsComments(author).row(psId).values());
return sort(comments);
}
public List<PatchLineComment> draftByChangeFileAuthor(ReviewDb db,
ChangeNotes notes, String file, Account.Id author)
throws OrmException {
if (!migration.readComments()) {
return sort(
db.patchComments()
.draftByChangeFileAuthor(notes.getChangeId(), file, author)
.toList());
}
List<PatchLineComment> comments = Lists.newArrayList();
addCommentsOnFile(comments, notes.getDraftBaseComments(author).values(),
file);
addCommentsOnFile(comments, notes.getDraftPsComments(author).values(),
file);
return sort(comments);
}
public List<PatchLineComment> draftByChangeAuthor(ReviewDb db,
ChangeNotes notes, Account.Id author)
throws OrmException {
if (!migration.readComments()) {
return sort(db.patchComments().byChange(notes.getChangeId()).toList());
}
List<PatchLineComment> comments = Lists.newArrayList();
comments.addAll(notes.getDraftBaseComments(author).values());
comments.addAll(notes.getDraftPsComments(author).values());
return sort(comments);
}
public List<PatchLineComment> draftByAuthor(ReviewDb db,
Account.Id author) throws OrmException {
if (!migration.readComments()) {
return sort(db.patchComments().draftByAuthor(author).toList());
}
Set<String> refNames =
getRefNamesAllUsers(RefNames.REFS_DRAFT_COMMENTS);
List<PatchLineComment> comments = Lists.newArrayList();
for (String refName : refNames) {
Account.Id id = Account.Id.fromRefPart(refName);
if (!author.equals(id)) {
continue;
}
Change.Id changeId = Change.Id.parse(refName);
DraftCommentNotes draftNotes =
draftFactory.create(changeId, author).load();
comments.addAll(draftNotes.getDraftBaseComments().values());
comments.addAll(draftNotes.getDraftPsComments().values());
}
return sort(comments);
}
public void insertComments(ReviewDb db, ChangeUpdate update,
Iterable<PatchLineComment> comments) throws OrmException {
for (PatchLineComment c : comments) {
update.insertComment(c);
}
db.patchComments().insert(comments);
}
public void upsertComments(ReviewDb db, ChangeUpdate update,
Iterable<PatchLineComment> comments) throws OrmException {
for (PatchLineComment c : comments) {
update.upsertComment(c);
}
db.patchComments().upsert(comments);
}
public void updateComments(ReviewDb db, ChangeUpdate update,
Iterable<PatchLineComment> comments) throws OrmException {
for (PatchLineComment c : comments) {
update.updateComment(c);
}
db.patchComments().update(comments);
}
public void deleteComments(ReviewDb db, ChangeUpdate update,
Iterable<PatchLineComment> comments) throws OrmException {
for (PatchLineComment c : comments) {
update.deleteComment(c);
}
db.patchComments().delete(comments);
}
private static Collection<PatchLineComment> addCommentsOnFile(
Collection<PatchLineComment> commentsOnFile,
Collection<PatchLineComment> allComments,
String file) {
for (PatchLineComment c : allComments) {
String currentFilename = c.getKey().getParentKey().getFileName();
if (currentFilename.equals(file)) {
commentsOnFile.add(c);
}
}
return commentsOnFile;
}
public static void setCommentRevId(PatchLineComment c,
PatchListCache cache, Change change, PatchSet ps) throws OrmException {
if (c.getRevId() != null) {
return;
}
PatchList patchList;
try {
patchList = cache.get(change, ps);
} catch (PatchListNotAvailableException e) {
throw new OrmException(e);
}
c.setRevId((c.getSide() == (short) 0)
? new RevId(ObjectId.toString(patchList.getOldId()))
: new RevId(ObjectId.toString(patchList.getNewId())));
}
private Set<String> getRefNamesAllUsers(String prefix) throws OrmException {
Repository repo;
try {
repo = repoManager.openRepository(allUsers);
} catch (IOException e) {
throw new OrmException(e);
}
try {
RefDatabase refDb = repo.getRefDatabase();
return refDb.getRefs(prefix).keySet();
} catch (IOException e) {
throw new OrmException(e);
} finally {
repo.close();
}
}
private Iterable<String> getDraftRefs(final Change.Id changeId)
throws OrmException {
Set<String> refNames = getRefNamesAllUsers(RefNames.REFS_DRAFT_COMMENTS);
final String suffix = "-" + changeId.get();
return Iterables.filter(refNames, new Predicate<String>() {
@Override
public boolean apply(String input) {
return input.endsWith(suffix);
}
});
}
private static List<PatchLineComment> sort(List<PatchLineComment> comments) {
Collections.sort(comments, ChangeNotes.PatchLineCommentComparator);
return comments;
}
}
| |
/*
* 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.jena.sparql.engine.main ;
import java.util.ArrayList ;
import java.util.Iterator ;
import java.util.List ;
import java.util.Set ;
import org.apache.jena.atlas.iterator.Iter ;
import org.apache.jena.atlas.logging.Log ;
import org.apache.jena.graph.Node ;
import org.apache.jena.query.ARQ ;
import org.apache.jena.query.QueryExecException ;
import org.apache.jena.sparql.ARQNotImplemented ;
import org.apache.jena.sparql.algebra.Op ;
import org.apache.jena.sparql.algebra.OpVars ;
import org.apache.jena.sparql.algebra.op.* ;
import org.apache.jena.sparql.core.BasicPattern ;
import org.apache.jena.sparql.core.Quad ;
import org.apache.jena.sparql.core.Var ;
import org.apache.jena.sparql.engine.ExecutionContext ;
import org.apache.jena.sparql.engine.QueryIterator ;
import org.apache.jena.sparql.engine.binding.Binding ;
import org.apache.jena.sparql.engine.iterator.* ;
import org.apache.jena.sparql.engine.join.Join ;
import org.apache.jena.sparql.engine.main.iterator.* ;
import org.apache.jena.sparql.expr.Expr ;
import org.apache.jena.sparql.expr.ExprList ;
import org.apache.jena.sparql.procedure.ProcEval ;
import org.apache.jena.sparql.procedure.Procedure ;
/**
* Turn an Op expression into an execution of QueryIterators.
*
* Does not consider optimizing the algebra expression (that should happen
* elsewhere). BGPs are still subject to StageBuilding during iterator
* execution.
*
* During execution, when a substitution into an algebra expression
* happens (in other words, a streaming operation, index-join-like), there is a
* call into the executor each time so it does not just happen once before a
* query starts.
*/
public class OpExecutor
{
public static final OpExecutorFactory stdFactory = new OpExecutorFactory() {
@Override
public OpExecutor create(ExecutionContext execCxt) {
return new OpExecutor(execCxt) ;
}
} ;
private static OpExecutor createOpExecutor(ExecutionContext execCxt) {
OpExecutorFactory factory = execCxt.getExecutor() ;
if (factory == null)
factory = stdFactory ;
if (factory == null)
return new OpExecutor(execCxt) ;
return factory.create(execCxt) ;
}
// -------
static QueryIterator execute(Op op, ExecutionContext execCxt) {
return execute(op, createRootQueryIterator(execCxt), execCxt) ;
}
/** Public interface is via QC.execute. **/
static QueryIterator execute(Op op, QueryIterator qIter, ExecutionContext execCxt) {
OpExecutor exec = createOpExecutor(execCxt) ;
QueryIterator q = exec.exec(op, qIter) ;
return q ;
}
// -------- The object starts here --------
protected ExecutionContext execCxt ;
protected ExecutionDispatch dispatcher = null ;
protected static final int TOP_LEVEL = 0 ;
protected int level = TOP_LEVEL - 1 ;
private final boolean hideBNodeVars ;
protected final StageGenerator stageGenerator ;
protected OpExecutor(ExecutionContext execCxt)
{
this.execCxt = execCxt ;
this.dispatcher = new ExecutionDispatch(this) ;
this.hideBNodeVars = execCxt.getContext().isTrue(ARQ.hideNonDistiguishedVariables) ;
this.stageGenerator = StageBuilder.chooseStageGenerator(execCxt.getContext()) ;
}
// Public interface
public QueryIterator executeOp(Op op, QueryIterator input) {
return exec(op, input) ;
}
// ---- The recursive step.
protected QueryIterator exec(Op op, QueryIterator input) {
level++ ;
QueryIterator qIter = dispatcher.exec(op, input) ;
// Intentionally not try/finally so exceptions leave some evidence
// around.
level-- ;
return qIter ;
}
// ---- All the cases
protected QueryIterator execute(OpBGP opBGP, QueryIterator input) {
BasicPattern pattern = opBGP.getPattern() ;
QueryIterator qIter = stageGenerator.execute(pattern, input, execCxt) ;
if (hideBNodeVars)
qIter = new QueryIterDistinguishedVars(qIter, execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpTriple opTriple, QueryIterator input) {
return execute(opTriple.asBGP(), input) ;
}
protected QueryIterator execute(OpGraph opGraph, QueryIterator input) {
QueryIterator qIter = specialcase(opGraph.getNode(), opGraph.getSubOp(), input) ;
if (qIter != null)
return qIter ;
return new QueryIterGraph(input, opGraph, execCxt) ;
}
private QueryIterator specialcase(Node gn, Op subOp, QueryIterator input) {
// This is a placeholder for code to specially handle explicitly named
// default graph and union graph.
if (Quad.isDefaultGraph(gn)) {
ExecutionContext cxt2 = new ExecutionContext(execCxt, execCxt.getDataset().getDefaultGraph()) ;
return execute(subOp, input, cxt2) ;
}
if ( Quad.isUnionGraph(gn) )
Log.warn(this, "Not implemented yet: union default graph in general OpExecutor") ;
// Bad news -- if ( Lib.equals(gn, Quad.tripleInQuad) ) {}
return null ;
}
protected QueryIterator execute(OpQuad opQuad, QueryIterator input) {
return execute(opQuad.asQuadPattern(), input) ;
}
protected QueryIterator execute(OpQuadPattern quadPattern, QueryIterator input) {
// Convert to BGP forms to execute in this graph-centric engine.
if (quadPattern.isDefaultGraph() && execCxt.getActiveGraph() == execCxt.getDataset().getDefaultGraph()) {
// Note we tested that the containing graph was the dataset's
// default graph.
// Easy case.
OpBGP opBGP = new OpBGP(quadPattern.getBasicPattern()) ;
return execute(opBGP, input) ;
}
// Not default graph - (graph .... )
OpBGP opBGP = new OpBGP(quadPattern.getBasicPattern()) ;
OpGraph op = new OpGraph(quadPattern.getGraphNode(), opBGP) ;
return execute(op, input) ;
}
protected QueryIterator execute(OpQuadBlock quadBlock, QueryIterator input) {
Op op = quadBlock.convertOp() ;
return exec(op, input) ;
}
protected QueryIterator execute(OpPath opPath, QueryIterator input) {
return new QueryIterPath(opPath.getTriplePath(), input, execCxt) ;
}
protected QueryIterator execute(OpProcedure opProc, QueryIterator input) {
Procedure procedure = ProcEval.build(opProc, execCxt) ;
QueryIterator qIter = exec(opProc.getSubOp(), input) ;
// Delay until query starts executing.
return new QueryIterProcedure(qIter, procedure, execCxt) ;
}
protected QueryIterator execute(OpPropFunc opPropFunc, QueryIterator input) {
Procedure procedure = ProcEval.build(opPropFunc.getProperty(), opPropFunc.getSubjectArgs(),
opPropFunc.getObjectArgs(), execCxt) ;
QueryIterator qIter = exec(opPropFunc.getSubOp(), input) ;
return new QueryIterProcedure(qIter, procedure, execCxt) ;
}
protected QueryIterator execute(OpJoin opJoin, QueryIterator input) {
// Need to clone input into left and right.
// Do by evaling for each input case, the left and right and concat'ing
// the results.
if (false) {
// If needed, applies to OpDiff and OpLeftJoin as well.
List<Binding> a = all(input) ;
QueryIterator qIter1 = new QueryIterPlainWrapper(a.iterator(), execCxt) ;
QueryIterator qIter2 = new QueryIterPlainWrapper(a.iterator(), execCxt) ;
QueryIterator left = exec(opJoin.getLeft(), qIter1) ;
QueryIterator right = exec(opJoin.getRight(), qIter2) ;
QueryIterator qIter = Join.join(left, right, execCxt) ;
return qIter ;
}
QueryIterator left = exec(opJoin.getLeft(), input) ;
QueryIterator right = exec(opJoin.getRight(), root()) ;
// Join key.
QueryIterator qIter = Join.join(left, right, execCxt) ;
return qIter ;
}
// Pass iterator from one step directly into the next.
protected QueryIterator execute(OpSequence opSequence, QueryIterator input) {
QueryIterator qIter = input ;
for (Iterator<Op> iter = opSequence.iterator(); iter.hasNext();) {
Op sub = iter.next() ;
qIter = exec(sub, qIter) ;
}
return qIter ;
}
protected QueryIterator execute(OpLeftJoin opLeftJoin, QueryIterator input) {
QueryIterator left = exec(opLeftJoin.getLeft(), input) ;
QueryIterator right = exec(opLeftJoin.getRight(), root()) ;
QueryIterator qIter = Join.leftJoin(left, right, opLeftJoin.getExprs(), execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpConditional opCondition, QueryIterator input) {
QueryIterator left = exec(opCondition.getLeft(), input) ;
QueryIterator qIter = new QueryIterOptionalIndex(left, opCondition.getRight(), execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpDiff opDiff, QueryIterator input) {
QueryIterator left = exec(opDiff.getLeft(), input) ;
QueryIterator right = exec(opDiff.getRight(), root()) ;
return new QueryIterDiff(left, right, execCxt) ;
}
protected QueryIterator execute(OpMinus opMinus, QueryIterator input) {
Op lhsOp = opMinus.getLeft() ;
Op rhsOp = opMinus.getRight() ;
QueryIterator left = exec(lhsOp, input) ;
QueryIterator right = exec(rhsOp, root()) ;
Set<Var> commonVars = OpVars.visibleVars(lhsOp) ;
commonVars.retainAll(OpVars.visibleVars(rhsOp)) ;
return new QueryIterMinus(left, right, commonVars, execCxt) ;
}
protected QueryIterator execute(OpDisjunction opDisjunction, QueryIterator input) {
QueryIterator cIter = new QueryIterUnion(input, opDisjunction.getElements(), execCxt) ;
return cIter ;
}
protected QueryIterator execute(OpUnion opUnion, QueryIterator input) {
List<Op> x = flattenUnion(opUnion) ;
QueryIterator cIter = new QueryIterUnion(input, x, execCxt) ;
return cIter ;
}
// Based on code from Olaf Hartig.
protected List<Op> flattenUnion(OpUnion opUnion) {
List<Op> x = new ArrayList<>() ;
flattenUnion(x, opUnion) ;
return x ;
}
protected void flattenUnion(List<Op> acc, OpUnion opUnion) {
if (opUnion.getLeft() instanceof OpUnion)
flattenUnion(acc, (OpUnion)opUnion.getLeft()) ;
else
acc.add(opUnion.getLeft()) ;
if (opUnion.getRight() instanceof OpUnion)
flattenUnion(acc, (OpUnion)opUnion.getRight()) ;
else
acc.add(opUnion.getRight()) ;
}
protected QueryIterator execute(OpFilter opFilter, QueryIterator input) {
ExprList exprs = opFilter.getExprs() ;
Op base = opFilter.getSubOp() ;
QueryIterator qIter = exec(base, input) ;
for (Expr expr : exprs)
qIter = new QueryIterFilterExpr(qIter, expr, execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpService opService, QueryIterator input) {
return new QueryIterService(input, opService, execCxt) ;
}
// Quad form, "GRAPH ?g {}" Flip back to OpGraph.
// Normally quad stores override this.
protected QueryIterator execute(OpDatasetNames dsNames, QueryIterator input) {
if (false) {
OpGraph op = new OpGraph(dsNames.getGraphNode(), new OpBGP()) ;
return execute(op, input) ;
}
throw new ARQNotImplemented("execute/OpDatasetNames") ;
}
protected QueryIterator execute(OpTable opTable, QueryIterator input) {
if (opTable.isJoinIdentity())
return input ;
if (input instanceof QueryIterRoot) {
input.close() ;
return opTable.getTable().iterator(execCxt) ;
}
QueryIterator qIterT = opTable.getTable().iterator(execCxt) ;
QueryIterator qIter = Join.join(input, qIterT, execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpExt opExt, QueryIterator input) {
try {
QueryIterator qIter = opExt.eval(input, execCxt) ;
if (qIter != null)
return qIter ;
} catch (UnsupportedOperationException ex) {}
// null or UnsupportedOperationException
throw new QueryExecException("Encountered unsupported OpExt: " + opExt.getName()) ;
}
protected QueryIterator execute(OpLabel opLabel, QueryIterator input) {
if (!opLabel.hasSubOp())
return input ;
return exec(opLabel.getSubOp(), input) ;
}
protected QueryIterator execute(OpNull opNull, QueryIterator input) {
// Loose the input.
input.close() ;
return QueryIterNullIterator.create(execCxt) ;
}
protected QueryIterator execute(OpList opList, QueryIterator input) {
return exec(opList.getSubOp(), input) ;
}
protected QueryIterator execute(OpOrder opOrder, QueryIterator input) {
QueryIterator qIter = exec(opOrder.getSubOp(), input) ;
qIter = new QueryIterSort(qIter, opOrder.getConditions(), execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpTopN opTop, QueryIterator input) {
QueryIterator qIter = null ;
// We could also do (reduced) here as well.
// but it's detected in TransformTopN and turned into (distinct)
// there so that code catches that already.
// We leave this to do the strict case of (top (distinct ...))
if (opTop.getSubOp() instanceof OpDistinct) {
OpDistinct opDistinct = (OpDistinct)opTop.getSubOp() ;
qIter = exec(opDistinct.getSubOp(), input) ;
qIter = new QueryIterTopN(qIter, opTop.getConditions(), opTop.getLimit(), true, execCxt) ;
} else {
qIter = exec(opTop.getSubOp(), input) ;
qIter = new QueryIterTopN(qIter, opTop.getConditions(), opTop.getLimit(), false, execCxt) ;
}
return qIter ;
}
protected QueryIterator execute(OpProject opProject, QueryIterator input) {
// This may be under a (graph) in which case we need to operate
// on the active graph.
// More intelligent QueryIterProject needed.
if (input instanceof QueryIterRoot) {
QueryIterator qIter = exec(opProject.getSubOp(), input) ;
qIter = new QueryIterProject(qIter, opProject.getVars(), execCxt) ;
return qIter ;
}
// Nested projected : need to ensure the input is seen.
QueryIterator qIter = new QueryIterProjectMerge(opProject, input, this, execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpSlice opSlice, QueryIterator input) {
QueryIterator qIter = exec(opSlice.getSubOp(), input) ;
qIter = new QueryIterSlice(qIter, opSlice.getStart(), opSlice.getLength(), execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpGroup opGroup, QueryIterator input) {
QueryIterator qIter = exec(opGroup.getSubOp(), input) ;
qIter = new QueryIterGroup(qIter, opGroup.getGroupVars(), opGroup.getAggregators(), execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpDistinct opDistinct, QueryIterator input) {
QueryIterator qIter = exec(opDistinct.getSubOp(), input) ;
qIter = new QueryIterDistinct(qIter, execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpReduced opReduced, QueryIterator input) {
QueryIterator qIter = exec(opReduced.getSubOp(), input) ;
qIter = new QueryIterReduced(qIter, execCxt) ;
return qIter ;
}
protected QueryIterator execute(OpAssign opAssign, QueryIterator input) {
QueryIterator qIter = exec(opAssign.getSubOp(), input) ;
qIter = new QueryIterAssign(qIter, opAssign.getVarExprList(), execCxt, false) ;
return qIter ;
}
protected QueryIterator execute(OpExtend opExtend, QueryIterator input) {
// We know (parse time checking) the variable is unused so far in
// the query so we can use QueryIterAssign knowing that it behaves
// the same as extend. The boolean should only be a check.
QueryIterator qIter = exec(opExtend.getSubOp(), input) ;
qIter = new QueryIterAssign(qIter, opExtend.getVarExprList(), execCxt, true) ;
return qIter ;
}
public static QueryIterator createRootQueryIterator(ExecutionContext execCxt) {
return QueryIterRoot.create(execCxt) ;
}
protected QueryIterator root() {
return createRootQueryIterator(execCxt) ;
}
// Use this to debug evaluation
// Example:
// input = debug(input) ;
private QueryIterator debug(String marker, QueryIterator input) {
List<Binding> x = all(input) ;
for (Binding b : x) {
System.out.print(marker) ;
System.out.print(": ") ;
System.out.println(b) ;
}
return new QueryIterPlainWrapper(x.iterator(), execCxt) ;
}
private static List<Binding> all(QueryIterator input) {
return Iter.toList(input) ;
}
}
| |
/*
* 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.painless.action;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreMode;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
import org.apache.lucene.store.RAMDirectory;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.single.shard.SingleShardRequest;
import org.elasticsearch.action.support.single.shard.TransportSingleShardAction;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.routing.ShardsIterator;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.CheckedBiFunction;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;
import org.elasticsearch.script.FilterScript;
import org.elasticsearch.script.ScoreScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import static org.elasticsearch.action.ValidateActions.addValidationError;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
public class PainlessExecuteAction extends ActionType<PainlessExecuteAction.Response> {
public static final PainlessExecuteAction INSTANCE = new PainlessExecuteAction();
private static final String NAME = "cluster:admin/scripts/painless/execute";
private PainlessExecuteAction() {
super(NAME, Response::new);
}
public static class Request extends SingleShardRequest<Request> implements ToXContentObject {
private static final ParseField SCRIPT_FIELD = new ParseField("script");
private static final ParseField CONTEXT_FIELD = new ParseField("context");
private static final ParseField CONTEXT_SETUP_FIELD = new ParseField("context_setup");
private static final ConstructingObjectParser<Request, Void> PARSER = new ConstructingObjectParser<>(
"painless_execute_request", args -> new Request((Script) args[0], (String) args[1], (ContextSetup) args[2]));
static {
PARSER.declareObject(ConstructingObjectParser.constructorArg(), (p, c) -> Script.parse(p), SCRIPT_FIELD);
PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), CONTEXT_FIELD);
PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), ContextSetup::parse, CONTEXT_SETUP_FIELD);
}
static final Map<String, ScriptContext<?>> SUPPORTED_CONTEXTS = Map.of(
"painless_test", PainlessTestScript.CONTEXT,
"filter", FilterScript.CONTEXT,
"score", ScoreScript.CONTEXT);
static ScriptContext<?> fromScriptContextName(String name) {
ScriptContext<?> scriptContext = SUPPORTED_CONTEXTS.get(name);
if (scriptContext == null) {
throw new UnsupportedOperationException("unsupported script context name [" + name + "]");
}
return scriptContext;
}
static class ContextSetup implements Writeable, ToXContentObject {
private static final ParseField INDEX_FIELD = new ParseField("index");
private static final ParseField DOCUMENT_FIELD = new ParseField("document");
private static final ParseField QUERY_FIELD = new ParseField("query");
private static final ConstructingObjectParser<ContextSetup, Void> PARSER =
new ConstructingObjectParser<>("execute_script_context",
args -> new ContextSetup((String) args[0], (BytesReference) args[1], (QueryBuilder) args[2]));
static {
PARSER.declareString(ConstructingObjectParser.optionalConstructorArg(), INDEX_FIELD);
PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) -> {
try (XContentBuilder b = XContentBuilder.builder(p.contentType().xContent())) {
b.copyCurrentStructure(p);
return BytesReference.bytes(b);
}
}, DOCUMENT_FIELD);
PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(), (p, c) ->
AbstractQueryBuilder.parseInnerQueryBuilder(p), QUERY_FIELD);
}
private final String index;
private final BytesReference document;
private final QueryBuilder query;
private XContentType xContentType;
static ContextSetup parse(XContentParser parser, Void context) throws IOException {
ContextSetup contextSetup = PARSER.parse(parser, null);
contextSetup.setXContentType(parser.contentType());
return contextSetup;
}
ContextSetup(String index, BytesReference document, QueryBuilder query) {
this.index = index;
this.document = document;
this.query = query;
}
ContextSetup(StreamInput in) throws IOException {
index = in.readOptionalString();
document = in.readOptionalBytesReference();
String xContentType = in.readOptionalString();
if (xContentType != null) {
this.xContentType = XContentType.fromMediaType(xContentType);
}
query = in.readOptionalNamedWriteable(QueryBuilder.class);
}
public String getIndex() {
return index;
}
public BytesReference getDocument() {
return document;
}
public QueryBuilder getQuery() {
return query;
}
public XContentType getXContentType() {
return xContentType;
}
public void setXContentType(XContentType xContentType) {
this.xContentType = xContentType;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ContextSetup that = (ContextSetup) o;
return Objects.equals(index, that.index) &&
Objects.equals(document, that.document) &&
Objects.equals(query, that.query) &&
Objects.equals(xContentType, that.xContentType);
}
@Override
public int hashCode() {
return Objects.hash(index, document, query, xContentType);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeOptionalString(index);
out.writeOptionalBytesReference(document);
out.writeOptionalString(xContentType != null ? xContentType.mediaTypeWithoutParameters(): null);
out.writeOptionalNamedWriteable(query);
}
@Override
public String toString() {
return "ContextSetup{" +
", index='" + index + '\'' +
", document=" + document +
", query=" + query +
", xContentType=" + xContentType +
'}';
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
{
if (index != null) {
builder.field(INDEX_FIELD.getPreferredName(), index);
}
if (document != null) {
builder.field(DOCUMENT_FIELD.getPreferredName());
try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE, document, xContentType)) {
builder.generator().copyCurrentStructure(parser);
}
}
if (query != null) {
builder.field(QUERY_FIELD.getPreferredName(), query);
}
}
builder.endObject();
return builder;
}
}
private final Script script;
private final ScriptContext<?> context;
private final ContextSetup contextSetup;
static Request parse(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
Request(Script script, String scriptContextName, ContextSetup setup) {
this.script = Objects.requireNonNull(script);
this.context = scriptContextName != null ? fromScriptContextName(scriptContextName) : PainlessTestScript.CONTEXT;
if (setup != null) {
this.contextSetup = setup;
index(contextSetup.index);
} else {
contextSetup = null;
}
}
Request(StreamInput in) throws IOException {
super(in);
script = new Script(in);
context = fromScriptContextName(in.readString());
contextSetup = in.readOptionalWriteable(ContextSetup::new);
}
public Script getScript() {
return script;
}
public ScriptContext<?> getContext() {
return context;
}
public ContextSetup getContextSetup() {
return contextSetup;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (script.getType() != ScriptType.INLINE) {
validationException = addValidationError("only inline scripts are supported", validationException);
}
if (needDocumentAndIndex(context)) {
if (contextSetup.index == null) {
validationException = addValidationError("index is a required parameter for current context", validationException);
}
if (contextSetup.document == null) {
validationException = addValidationError("document is a required parameter for current context", validationException);
}
}
return validationException;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
script.writeTo(out);
out.writeString(context.name);
out.writeOptionalWriteable(contextSetup);
}
// For testing only:
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(SCRIPT_FIELD.getPreferredName(), script);
builder.field(CONTEXT_FIELD.getPreferredName(), context.name);
if (contextSetup != null) {
builder.field(CONTEXT_SETUP_FIELD.getPreferredName(), contextSetup);
}
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Request request = (Request) o;
return Objects.equals(script, request.script) &&
Objects.equals(context, request.context) &&
Objects.equals(contextSetup, request.contextSetup);
}
@Override
public int hashCode() {
return Objects.hash(script, context, contextSetup);
}
@Override
public String toString() {
return "Request{" +
"script=" + script +
"context=" + context +
", contextSetup=" + contextSetup +
'}';
}
static boolean needDocumentAndIndex(ScriptContext<?> scriptContext) {
return scriptContext == FilterScript.CONTEXT || scriptContext == ScoreScript.CONTEXT;
}
}
public static class Response extends ActionResponse implements ToXContentObject {
private Object result;
Response(Object result) {
this.result = result;
}
Response(StreamInput in) throws IOException {
super(in);
result = in.readGenericValue();
}
public Object getResult() {
return result;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeGenericValue(result);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("result", result);
return builder.endObject();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Response response = (Response) o;
return Objects.equals(result, response.result);
}
@Override
public int hashCode() {
return Objects.hash(result);
}
}
public abstract static class PainlessTestScript {
private final Map<String, Object> params;
public PainlessTestScript(Map<String, Object> params) {
this.params = params;
}
/** Return the parameters for this script. */
public Map<String, Object> getParams() {
return params;
}
public abstract Object execute();
public interface Factory {
PainlessTestScript newInstance(Map<String, Object> params);
}
public static final String[] PARAMETERS = {};
public static final ScriptContext<Factory> CONTEXT = new ScriptContext<>("painless_test", Factory.class);
}
public static class TransportAction extends TransportSingleShardAction<Request, Response> {
private final ScriptService scriptService;
private final IndicesService indicesServices;
@Inject
public TransportAction(ThreadPool threadPool, TransportService transportService,
ActionFilters actionFilters, IndexNameExpressionResolver indexNameExpressionResolver,
ScriptService scriptService, ClusterService clusterService, IndicesService indicesServices) {
super(NAME, threadPool, clusterService, transportService, actionFilters, indexNameExpressionResolver,
// Forking a thread here, because only light weight operations should happen on network thread and
// Creating a in-memory index is not light weight
// TODO: is MANAGEMENT TP the right TP? Right now this is an admin api (see action name).
Request::new, ThreadPool.Names.MANAGEMENT);
this.scriptService = scriptService;
this.indicesServices = indicesServices;
}
@Override
protected Writeable.Reader<Response> getResponseReader() {
return Response::new;
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, InternalRequest request) {
if (request.concreteIndex() != null) {
return super.checkRequestBlock(state, request);
}
return null;
}
@Override
protected boolean resolveIndex(Request request) {
return request.contextSetup != null && request.contextSetup.getIndex() != null;
}
@Override
protected ShardsIterator shards(ClusterState state, InternalRequest request) {
if (request.concreteIndex() == null) {
return null;
}
return state.routingTable().index(request.concreteIndex()).randomAllActiveShardsIt();
}
@Override
protected Response shardOperation(Request request, ShardId shardId) throws IOException {
IndexService indexService;
if (request.contextSetup != null && request.contextSetup.getIndex() != null) {
ClusterState clusterState = clusterService.state();
IndicesOptions indicesOptions = IndicesOptions.strictSingleIndexNoExpandForbidClosed();
String indexExpression = request.contextSetup.index;
Index[] concreteIndices =
indexNameExpressionResolver.concreteIndices(clusterState, indicesOptions, indexExpression);
if (concreteIndices.length != 1) {
throw new IllegalArgumentException("[" + indexExpression + "] does not resolve to a single index");
}
Index concreteIndex = concreteIndices[0];
indexService = indicesServices.indexServiceSafe(concreteIndex);
} else {
indexService = null;
}
return innerShardOperation(request, scriptService, indexService);
}
static Response innerShardOperation(Request request, ScriptService scriptService, IndexService indexService) throws IOException {
final ScriptContext<?> scriptContext = request.context;
if (scriptContext == PainlessTestScript.CONTEXT) {
PainlessTestScript.Factory factory = scriptService.compile(request.script, PainlessTestScript.CONTEXT);
PainlessTestScript painlessTestScript = factory.newInstance(request.script.getParams());
String result = Objects.toString(painlessTestScript.execute());
return new Response(result);
} else if (scriptContext == FilterScript.CONTEXT) {
return prepareRamIndex(request, (context, leafReaderContext) -> {
FilterScript.Factory factory = scriptService.compile(request.script, FilterScript.CONTEXT);
FilterScript.LeafFactory leafFactory =
factory.newFactory(request.getScript().getParams(), context.lookup());
FilterScript filterScript = leafFactory.newInstance(leafReaderContext);
filterScript.setDocument(0);
boolean result = filterScript.execute();
return new Response(result);
}, indexService);
} else if (scriptContext == ScoreScript.CONTEXT) {
return prepareRamIndex(request, (context, leafReaderContext) -> {
ScoreScript.Factory factory = scriptService.compile(request.script, ScoreScript.CONTEXT);
ScoreScript.LeafFactory leafFactory =
factory.newFactory(request.getScript().getParams(), context.lookup());
ScoreScript scoreScript = leafFactory.newInstance(leafReaderContext);
scoreScript.setDocument(0);
if (request.contextSetup.query != null) {
Query luceneQuery = request.contextSetup.query.rewrite(context).toQuery(context);
IndexSearcher indexSearcher = new IndexSearcher(leafReaderContext.reader());
luceneQuery = indexSearcher.rewrite(luceneQuery);
Weight weight = indexSearcher.createWeight(luceneQuery, ScoreMode.COMPLETE, 1f);
Scorer scorer = weight.scorer(indexSearcher.getIndexReader().leaves().get(0));
// Consume the first (and only) match.
int docID = scorer.iterator().nextDoc();
assert docID == scorer.docID();
scoreScript.setScorer(scorer);
}
double result = scoreScript.execute(null);
return new Response(result);
}, indexService);
} else {
throw new UnsupportedOperationException("unsupported context [" + scriptContext.name + "]");
}
}
private static Response prepareRamIndex(Request request,
CheckedBiFunction<QueryShardContext, LeafReaderContext, Response, IOException> handler,
IndexService indexService) throws IOException {
Analyzer defaultAnalyzer = indexService.getIndexAnalyzers().getDefaultIndexAnalyzer();
try (RAMDirectory ramDirectory = new RAMDirectory()) {
try (IndexWriter indexWriter = new IndexWriter(ramDirectory, new IndexWriterConfig(defaultAnalyzer))) {
String index = indexService.index().getName();
String type = indexService.mapperService().documentMapper().type();
BytesReference document = request.contextSetup.document;
XContentType xContentType = request.contextSetup.xContentType;
SourceToParse sourceToParse = new SourceToParse(index, type, "_id", document, xContentType);
ParsedDocument parsedDocument = indexService.mapperService().documentMapper().parse(sourceToParse);
indexWriter.addDocuments(parsedDocument.docs());
try (IndexReader indexReader = DirectoryReader.open(indexWriter)) {
final IndexSearcher searcher = new IndexSearcher(indexReader);
searcher.setQueryCache(null);
final long absoluteStartMillis = System.currentTimeMillis();
QueryShardContext context =
indexService.newQueryShardContext(0, searcher, () -> absoluteStartMillis, null);
return handler.apply(context, indexReader.leaves().get(0));
}
}
}
}
}
public static class RestAction extends BaseRestHandler {
public RestAction(RestController controller) {
controller.registerHandler(GET, "/_scripts/painless/_execute", this);
controller.registerHandler(POST, "/_scripts/painless/_execute", this);
}
@Override
public String getName() {
return "_scripts_painless_execute";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException {
final Request request = Request.parse(restRequest.contentOrSourceParamParser());
return channel -> client.executeLocally(INSTANCE, request, new RestToXContentListener<>(channel));
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.avro;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.generic.GenericData;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.avro.generated.AColumn;
import org.apache.hadoop.hbase.avro.generated.AColumnValue;
import org.apache.hadoop.hbase.avro.generated.AFamilyDescriptor;
import org.apache.hadoop.hbase.avro.generated.AGet;
import org.apache.hadoop.hbase.avro.generated.APut;
import org.apache.hadoop.hbase.avro.generated.ATableDescriptor;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Threads;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Unit testing for AvroServer.HBaseImpl, a part of the
* org.apache.hadoop.hbase.avro package.
*/
public class TestAvroServer {
private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
// Static names for tables, columns, rows, and values
// TODO(hammer): Better style to define these in test method?
private static ByteBuffer tableAname = ByteBuffer.wrap(Bytes.toBytes("tableA"));
private static ByteBuffer tableBname = ByteBuffer.wrap(Bytes.toBytes("tableB"));
private static ByteBuffer familyAname = ByteBuffer.wrap(Bytes.toBytes("FamilyA"));
private static ByteBuffer qualifierAname = ByteBuffer.wrap(Bytes.toBytes("QualifierA"));
private static ByteBuffer rowAname = ByteBuffer.wrap(Bytes.toBytes("RowA"));
private static ByteBuffer valueA = ByteBuffer.wrap(Bytes.toBytes("ValueA"));
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
TEST_UTIL.startMiniCluster(3);
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
TEST_UTIL.shutdownMiniCluster();
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
// Nothing to do.
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
// Nothing to do.
}
/**
* Tests for creating, enabling, disabling, modifying, and deleting tables.
*
* @throws Exception
*/
@Test (timeout=300000)
public void testTableAdminAndMetadata() throws Exception {
AvroServer.HBaseImpl impl =
new AvroServer.HBaseImpl(TEST_UTIL.getConfiguration());
assertEquals(impl.listTables().size(), 0);
ATableDescriptor tableA = new ATableDescriptor();
tableA.name = tableAname;
impl.createTable(tableA);
assertEquals(impl.listTables().size(), 1);
assertTrue(impl.isTableEnabled(tableAname));
assertTrue(impl.tableExists(tableAname));
ATableDescriptor tableB = new ATableDescriptor();
tableB.name = tableBname;
impl.createTable(tableB);
assertEquals(impl.listTables().size(), 2);
impl.disableTable(tableBname);
assertFalse(impl.isTableEnabled(tableBname));
impl.deleteTable(tableBname);
assertEquals(impl.listTables().size(), 1);
impl.disableTable(tableAname);
assertFalse(impl.isTableEnabled(tableAname));
tableA.maxFileSize = 123456L;
impl.modifyTable(tableAname, tableA);
// It can take a while for the change to take effect. Wait here a while.
while(impl.describeTable(tableAname).maxFileSize != 123456L) Threads.sleep(100);
assertEquals(123456L, (long) impl.describeTable(tableAname).maxFileSize);
/* DISABLED FOR NOW TILL WE HAVE BETTER DISABLE/ENABLE
impl.enableTable(tableAname);
assertTrue(impl.isTableEnabled(tableAname));
impl.disableTable(tableAname);
*/
impl.deleteTable(tableAname);
}
/**
* Tests for creating, modifying, and deleting column families.
*
* @throws Exception
*/
@Test
public void testFamilyAdminAndMetadata() throws Exception {
AvroServer.HBaseImpl impl =
new AvroServer.HBaseImpl(TEST_UTIL.getConfiguration());
ATableDescriptor tableA = new ATableDescriptor();
tableA.name = tableAname;
AFamilyDescriptor familyA = new AFamilyDescriptor();
familyA.name = familyAname;
Schema familyArraySchema = Schema.createArray(AFamilyDescriptor.SCHEMA$);
GenericArray<AFamilyDescriptor> families = new GenericData.Array<AFamilyDescriptor>(1, familyArraySchema);
families.add(familyA);
tableA.families = families;
impl.createTable(tableA);
assertEquals(impl.describeTable(tableAname).families.size(), 1);
impl.disableTable(tableAname);
assertFalse(impl.isTableEnabled(tableAname));
familyA.maxVersions = 123456;
impl.modifyFamily(tableAname, familyAname, familyA);
assertEquals((int) impl.describeFamily(tableAname, familyAname).maxVersions, 123456);
impl.deleteFamily(tableAname, familyAname);
assertEquals(impl.describeTable(tableAname).families.size(), 0);
impl.disableTable(tableAname);
impl.deleteTable(tableAname);
}
/**
* Tests for adding, reading, and deleting data.
*
* @throws Exception
*/
@Test
public void testDML() throws Exception {
AvroServer.HBaseImpl impl =
new AvroServer.HBaseImpl(TEST_UTIL.getConfiguration());
ATableDescriptor tableA = new ATableDescriptor();
tableA.name = tableAname;
AFamilyDescriptor familyA = new AFamilyDescriptor();
familyA.name = familyAname;
Schema familyArraySchema = Schema.createArray(AFamilyDescriptor.SCHEMA$);
GenericArray<AFamilyDescriptor> families = new GenericData.Array<AFamilyDescriptor>(1, familyArraySchema);
families.add(familyA);
tableA.families = families;
impl.createTable(tableA);
assertEquals(impl.describeTable(tableAname).families.size(), 1);
AGet getA = new AGet();
getA.row = rowAname;
Schema columnsSchema = Schema.createArray(AColumn.SCHEMA$);
GenericArray<AColumn> columns = new GenericData.Array<AColumn>(1, columnsSchema);
AColumn column = new AColumn();
column.family = familyAname;
column.qualifier = qualifierAname;
columns.add(column);
getA.columns = columns;
assertFalse(impl.exists(tableAname, getA));
APut putA = new APut();
putA.row = rowAname;
Schema columnValuesSchema = Schema.createArray(AColumnValue.SCHEMA$);
GenericArray<AColumnValue> columnValues = new GenericData.Array<AColumnValue>(1, columnValuesSchema);
AColumnValue acv = new AColumnValue();
acv.family = familyAname;
acv.qualifier = qualifierAname;
acv.value = valueA;
columnValues.add(acv);
putA.columnValues = columnValues;
impl.put(tableAname, putA);
assertTrue(impl.exists(tableAname, getA));
assertEquals(impl.get(tableAname, getA).entries.size(), 1);
impl.disableTable(tableAname);
impl.deleteTable(tableAname);
}
}
| |
package HTMLPages;
import Prices.CommodityPrices;
import Users.User;
import HTMLControls.*;
import Models.*;
import Utilities.*;
import com.teamdev.jxbrowser.chromium.JSONString;
import java.util.*;
public class DashboardPage
{
private Dashboard aDashboard;
private static User anUser;
public DashboardPage()
{
;
}
public void setUser(User anUser)
{
DashboardPage.anUser = anUser;
}
public JSONString createDashboardPage()
{
this.aDashboard = new Dashboard(anUser.getCode() + "");
MetroFluentMenu dashboardFluentMenu = new MetroFluentMenu("dashboardFluentMenu", "Main Menu", "createMainMenu();",
new ArrayList<>(Collections.singletonList("Prices")));
ArrayList<MetroFluentButton> buttons = new ArrayList<>();
buttons.add(new MetroFluentButton("BarChart Format", "chart-bars","createCommodityTiles('viewPricesInBarChartFormat');"));
buttons.add(new MetroFluentButton("LineChart Format", "chart-line","createCommodityTiles('viewPricesInLineChartFormat');"));
buttons.add(new MetroFluentButton("Tabular Format", "table", "createCommodityTiles('viewPricesInTabularFormat');"));
MetroFluentMenuPanelGroup aPricesGroup = new MetroFluentMenuPanelGroup("Prices", buttons);
buttons.clear();
buttons.add(new MetroFluentButton("Generate PDF File", "file-pdf", "generatePDFFileForCommodityPrices();"));
buttons.add(new MetroFluentButton("Email PDF File", "mail-read", "emailPDFFileForCommodityPrices();"));
buttons.add(new MetroFluentButton("Print PDF File", "printer", "printPDFFileForCommodityPrices();"));
MetroFluentMenuPanelGroup quickActionsGroup = new MetroFluentMenuPanelGroup("Quick Actions", buttons);
dashboardFluentMenu.addPanelGroups(new ArrayList<>(Arrays.asList(aPricesGroup, quickActionsGroup)));
MetroLayout dashboardLayout = new MetroLayout();
dashboardLayout.addRow(dashboardFluentMenu);
MetroAccordion preloaderAccordion = new MetroAccordion();
MetroPreloader aPreLoader = new MetroPreloader();
MetroLayout preloaderLayout = new MetroLayout();
preloaderLayout.addRow(aPreLoader, new ArrayList<>(Arrays.asList(5, 2, 5)));
preloaderAccordion.addFrame("Retrieving The Latest Commodity Prices", preloaderLayout, "loop2");
dashboardLayout.addRow(new MetroUpdatePanel("dashboardUpdatePanel", preloaderAccordion));
HashMap<String, String> parameters = new HashMap<>();
parameters.put("html", dashboardLayout.toString());
return Utilities.convertHashMapToJSON(parameters);
}
public JSONString createCommodityTiles(String onClickEvent)
{
if(aDashboard.getCommodityPrices().size() == 0)
aDashboard.addDashboard();
LinkedHashMap<String, CommodityPrices> commodityPrices = aDashboard.getCommodityPrices();
List<MetroComponent> commodityTiles = new ArrayList<>();
for(String aCommodityTitle: commodityPrices.keySet())
{
commodityTiles.add(new MetroTile(onClickEvent + "('" + aCommodityTitle + "');", "cyan", aCommodityTitle,
"florist", ""));
}
MetroLayout commoditiesLayout = new MetroLayout();
commoditiesLayout.addMultipleRows(commodityTiles, 3, 1, 3, 0, 2);
MetroAccordion commoditiesAccordion = new MetroAccordion();
commoditiesAccordion.addFrame("Commodities", commoditiesLayout, "florist");
HashMap<String, String> parameters = new HashMap<>();
parameters.put("html", commoditiesAccordion.toString());
return Utilities.convertHashMapToJSON(parameters);
}
public JSONString createMainMenu()
{
MetroLayout mainMenuLayout = new MetroLayout();
MetroTile mainMenuTile = new MetroTile("getPortalPage();", "cyan", "Main Menu", "menu", "");
MetroTile logOutTile = new MetroTile("loadHTML5Edition();", "cyan", "Log Out", "exit", "");
MetroTile exitTile = new MetroTile("exit();", "cyan", "Exit", "exit", "");
mainMenuLayout.addRow(new ArrayList<>(Arrays.asList(mainMenuTile, logOutTile, exitTile)), new ArrayList<>(Arrays.asList(1, 3, 0, 1, 3, 0, 1, 3, 0)));
MetroAccordion mainMenuAccordion = new MetroAccordion();
mainMenuAccordion.addFrame("Main Menu", mainMenuLayout, "menu");
HashMap<String, String> parameters = new HashMap<>();
parameters.put("html", mainMenuAccordion.toString());
return Utilities.convertHashMapToJSON(parameters);
}
public JSONString viewPricesInTabularFormat(String commodityIdentifier)
{
LinkedHashMap<String, CommodityPrices> commodityPrices = aDashboard.getCommodityPrices();
CommodityPrices currentCommodityPrices = commodityPrices.get(commodityIdentifier);
ArrayList<String> currentCommodityPricesHeadings = currentCommodityPrices.getHeadings();
currentCommodityPricesHeadings.add(0, "Code");
ArrayList<ArrayList<String>> tableRows = aDashboard.getListOfCommodityPricesForSelectedCommodity(currentCommodityPrices, true);
MetroDataTable currentCommodityDataTable = new MetroDataTable("currentCommodityDataTable", currentCommodityPrices.getHeadings(), tableRows,
new ArrayList<>());
MetroAccordion currentCommodityAccordion = new MetroAccordion();
currentCommodityAccordion.addFrame("Current Prices For " + currentCommodityPrices.getCommodityTitle(), currentCommodityDataTable, "eur");
HashMap<String, String> parameters = new HashMap<>();
parameters.put("html", currentCommodityAccordion.toString());
return Utilities.convertHashMapToJSON(parameters);
}
public JSONString viewPricesInBarChartFormat(String commodityTitle)
{
HashMap<String, String> parameters = new HashMap<>();
MetroAccordion viewPricesInBarChartFormatAccordion = new MetroAccordion();
MetroLayout barChartLayout = new MetroLayout();
LinkedHashMap<String, CommodityPrices> commodityPrices = aDashboard.getCommodityPrices();
CommodityPrices currentCommodityPrices = commodityPrices.get(commodityTitle);
List<String> chartTitles = aDashboard.getMonths(currentCommodityPrices);
List<Double> chartValues = aDashboard.getLastPrices(currentCommodityPrices);
LinkedHashMap<String, List<Double>> lastPrices = new LinkedHashMap<>();
lastPrices.put("Spot Prices", chartValues);
barChartLayout.addRow(new MetroChart("chart"));
viewPricesInBarChartFormatAccordion.addFrame("Bar Chart Format", barChartLayout, "chart-bars");
parameters.put("html", viewPricesInBarChartFormatAccordion.toString());
return Utilities.createChart(parameters, chartTitles, lastPrices);
}
public JSONString viewPricesInLineChartFormat(String commodityTitle)
{
HashMap<String, String> parameters = new HashMap<>();
MetroAccordion viewPricesInLineChartFormatAccordion = new MetroAccordion();
MetroLayout lineChartLayout = new MetroLayout();
LinkedHashMap<String, CommodityPrices> commodityPrices = aDashboard.getCommodityPrices();
CommodityPrices currentCommodityPrices = commodityPrices.get(commodityTitle);
List<String> chartTitles = aDashboard.getMonths(currentCommodityPrices);
List<Double> chartValues = aDashboard.getLastPrices(currentCommodityPrices);
LinkedHashMap<String, List<Double>> lastPrices = new LinkedHashMap<>();
lastPrices.put("Spot Prices", chartValues);
lineChartLayout.addRow(new MetroChart("chart"));
viewPricesInLineChartFormatAccordion.addFrame("Line Chart Format", lineChartLayout, "chart-line");
parameters.put("html", viewPricesInLineChartFormatAccordion.toString());
return Utilities.createChart(parameters, chartTitles, lastPrices);
}
public JSONString generatePDFFile()
{
HashMap<String, String> parameters = new HashMap<>();
if(aDashboard.getCommodityPrices().size() > 0)
{
String fileName = aDashboard.generatePDFFile();
MetroIFrame generatePDFFileIFrame = new MetroIFrame(fileName);
MetroAccordion generatePDFFileAccordion = new MetroAccordion();
generatePDFFileAccordion.addFrame("PDF Report Created For Commodity Prices", generatePDFFileIFrame, "file-pdf");
parameters.put("html", generatePDFFileAccordion.toString());
}
else
{
MetroAccordion errorAccordion = new MetroAccordion();
errorAccordion.addFrame("No Prices Are Currently Available", new MetroHeading("No Prices Are Currently Available", ""), "warning");
parameters.put("html", errorAccordion.toString());
}
return Utilities.convertHashMapToJSON(parameters);
}
public JSONString emailPDFFile()
{
HashMap<String, String> parameters = new HashMap<>();
if(aDashboard.getCommodityPrices().size() > 0)
{
String fileName = aDashboard.generatePDFFile();
aDashboard.printPDFFile();
MetroLayout emailPDFFileLayout = new MetroLayout();
emailPDFFileLayout.addRow(new MetroProgressBar(50, "cyan"));
emailPDFFileLayout.addEmptyRows(2);
emailPDFFileLayout.addRow(new MetroTextField("Please enter the email address of the recipient", "mail-read", "text",
"emailAddressTextBox"));
emailPDFFileLayout.addEmptyRows(2);
emailPDFFileLayout.addRow(new MetroCommandButton("Send", "Send Your Email", "checkmark",
"emailPDFFileInvokedForCommodityPrices();", "success"), new ArrayList<>(Arrays.asList(4, 4, 4)));
MetroAccordion emailPDFFileAccordion = new MetroAccordion();
emailPDFFileAccordion.addFrame("Email PDF Report", emailPDFFileLayout, "mail-read");
MetroUpdatePanel emailPDFFileUpdatePanel = new MetroUpdatePanel("emailPDFFileUpdatePanel", emailPDFFileAccordion);
MetroAccordion generatePDFFileAccordion = new MetroAccordion();
MetroIFrame generatePDFFileIFrame = new MetroIFrame(fileName);
generatePDFFileAccordion.addFrame("PDF Report Created For Commodity Prices", generatePDFFileIFrame, "file-pdf");
MetroLayout emailPDFFileMasterLayout = new MetroLayout();
emailPDFFileMasterLayout.addRow(emailPDFFileUpdatePanel);
emailPDFFileMasterLayout.addRow(generatePDFFileAccordion);
parameters.put("html", emailPDFFileMasterLayout.toString());
}
else
{
MetroAccordion errorAccordion = new MetroAccordion();
errorAccordion.addFrame("No Prices Are Currently Available", new MetroHeading("No Prices Are Currently Available", ""), "warning");
parameters.put("html", errorAccordion.toString());
}
return Utilities.convertHashMapToJSON(parameters);
}
public JSONString emailPDFFileInvoked(String emailAddress)
{
boolean emailPDFFile = aDashboard.emailPDFFile(emailAddress);
MetroLayout emailPDFFileLayout = new MetroLayout();
emailPDFFileLayout.addRow(new MetroProgressBar(100, "cyan"));
if(emailPDFFile)
emailPDFFileLayout.addRow(new MetroHeading("Your commodities report was successfully emailed to " + emailAddress, ""));
else
emailPDFFileLayout.addRow(new MetroHeading("Your commodities report was not emailed to " + emailAddress, ""));
MetroAccordion emailPDFFileAccordion = new MetroAccordion();
emailPDFFileAccordion.addFrame("Email PDF Report", emailPDFFileLayout, "mail-read");
HashMap<String, String> parameters = new HashMap<>();
parameters.put("html", emailPDFFileAccordion.toString());
return Utilities.convertHashMapToJSON(parameters);
}
public JSONString printPDFFile()
{
HashMap<String, String> parameters = new HashMap<>();
if(aDashboard.getCommodityPrices().size() > 0)
{
String fileLocation = aDashboard.generatePDFFile();
MetroAccordion printPDFFileAccordion = new MetroAccordion();
printPDFFileAccordion.addFrame("Print PDF Report", new MetroHeading("Your commodities report was successfully printed", ""), "printer");
MetroIFrame generatePDFFileIFrame = new MetroIFrame(fileLocation);
MetroAccordion generatePDFFileAccordion = new MetroAccordion();
generatePDFFileAccordion.addFrame("PDF Report Created For Commodity Prices", generatePDFFileIFrame, "file-pdf");
MetroLayout printPDFFileMasterLayout = new MetroLayout();
printPDFFileMasterLayout.addRow(printPDFFileAccordion);
printPDFFileMasterLayout.addRow(generatePDFFileAccordion);
parameters.put("html", printPDFFileMasterLayout.toString());
}
else
{
MetroAccordion errorAccordion = new MetroAccordion();
errorAccordion.addFrame("No Prices Are Currently Available", new MetroHeading("No Prices Are Currently Available", ""), "warning");
parameters.put("html", errorAccordion.toString());
}
return Utilities.convertHashMapToJSON(parameters);
}
}
| |
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* 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.handmark.pulltorefresh.library;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.handmark.pulltorefresh.library.internal.EmptyViewMethodAccessor;
import com.handmark.pulltorefresh.library.internal.LoadingLayout;
public class PullToRefreshListView extends PullToRefreshAdapterViewBase<ListView> {
private LoadingLayout mHeaderLoadingView;
private LoadingLayout mFooterLoadingView;
private FrameLayout mLvFooterLoadingFrame;
public PullToRefreshListView(Context context) {
super(context);
setDisableScrollingWhileRefreshing(false);
}
public PullToRefreshListView(Context context, AttributeSet attrs) {
super(context, attrs);
setDisableScrollingWhileRefreshing(false);
}
public PullToRefreshListView(Context context, Mode mode) {
super(context, mode);
setDisableScrollingWhileRefreshing(false);
}
@Override
public ContextMenuInfo getContextMenuInfo() {
return ((InternalListView) getRefreshableView()).getContextMenuInfo();
}
@Override
public void setLastUpdatedLabel(CharSequence label) {
super.setLastUpdatedLabel(label);
if (null != mHeaderLoadingView) {
mHeaderLoadingView.setSubHeaderText(label);
}
if (null != mFooterLoadingView) {
mFooterLoadingView.setSubHeaderText(label);
}
}
@Override
public void setLoadingDrawable(Drawable drawable, Mode mode) {
super.setLoadingDrawable(drawable, mode);
if (null != mHeaderLoadingView && mode.canPullDown()) {
mHeaderLoadingView.setLoadingDrawable(drawable);
}
if (null != mFooterLoadingView && mode.canPullUp()) {
mFooterLoadingView.setLoadingDrawable(drawable);
}
}
public void setPullLabel(CharSequence pullLabel, Mode mode) {
super.setPullLabel(pullLabel, mode);
if (null != mHeaderLoadingView && mode.canPullDown()) {
mHeaderLoadingView.setPullLabel(pullLabel);
}
if (null != mFooterLoadingView && mode.canPullUp()) {
mFooterLoadingView.setPullLabel(pullLabel);
}
}
public void setRefreshingLabel(CharSequence refreshingLabel, Mode mode) {
super.setRefreshingLabel(refreshingLabel, mode);
if (null != mHeaderLoadingView && mode.canPullDown()) {
mHeaderLoadingView.setRefreshingLabel(refreshingLabel);
}
if (null != mFooterLoadingView && mode.canPullUp()) {
mFooterLoadingView.setRefreshingLabel(refreshingLabel);
}
}
public void setReleaseLabel(CharSequence releaseLabel, Mode mode) {
super.setReleaseLabel(releaseLabel, mode);
if (null != mHeaderLoadingView && mode.canPullDown()) {
mHeaderLoadingView.setReleaseLabel(releaseLabel);
}
if (null != mFooterLoadingView && mode.canPullUp()) {
mFooterLoadingView.setReleaseLabel(releaseLabel);
}
}
protected ListView createListView(Context context, AttributeSet attrs) {
final ListView lv;
if (VERSION.SDK_INT >= VERSION_CODES.GINGERBREAD) {
lv = new InternalListViewSDK9(context, attrs);
} else {
lv = new InternalListView(context, attrs);
}
return lv;
}
@Override
protected final ListView createRefreshableView(Context context, AttributeSet attrs) {
ListView lv = createListView(context, attrs);
// Get Styles from attrs
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh);
// Create Loading Views ready for use later
FrameLayout frame = new FrameLayout(context);
mHeaderLoadingView = createLoadingLayout(context, Mode.PULL_DOWN_TO_REFRESH, a);
frame.addView(mHeaderLoadingView, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
mHeaderLoadingView.setVisibility(View.GONE);
lv.addHeaderView(frame, null, false);
mLvFooterLoadingFrame = new FrameLayout(context);
mFooterLoadingView = createLoadingLayout(context, Mode.PULL_UP_TO_REFRESH, a);
mLvFooterLoadingFrame.addView(mFooterLoadingView, FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
mFooterLoadingView.setVisibility(View.GONE);
a.recycle();
// Set it to this so it can be used in ListActivity/ListFragment
lv.setId(android.R.id.list);
return lv;
}
@Override
protected void resetHeader() {
// If we're not showing the Refreshing view, or the list is empty, then
// the header/footer views won't show so we use the
// normal method
ListAdapter adapter = mRefreshableView.getAdapter();
if (!getShowViewWhileRefreshing() || null == adapter || adapter.isEmpty()) {
super.resetHeader();
return;
}
LoadingLayout originalLoadingLayout, listViewLoadingLayout;
int scrollToHeight, selection;
boolean scrollLvToEdge;
switch (getCurrentMode()) {
case PULL_UP_TO_REFRESH:
originalLoadingLayout = getFooterLayout();
listViewLoadingLayout = mFooterLoadingView;
selection = mRefreshableView.getCount() - 1;
scrollToHeight = getFooterHeight();
scrollLvToEdge = Math.abs(mRefreshableView.getLastVisiblePosition() - selection) <= 1;
break;
case PULL_DOWN_TO_REFRESH:
default:
originalLoadingLayout = getHeaderLayout();
listViewLoadingLayout = mHeaderLoadingView;
scrollToHeight = -getHeaderHeight();
selection = 0;
scrollLvToEdge = Math.abs(mRefreshableView.getFirstVisiblePosition() - selection) <= 1;
break;
}
// Set our Original View to Visible
originalLoadingLayout.setVisibility(View.VISIBLE);
/**
* Scroll so the View is at the same Y as the ListView header/footer,
* but only scroll if: we've pulled to refresh, it's positioned
* correctly, and we're currently showing the ListViewLoadingLayout
*/
if (scrollLvToEdge && getState() != MANUAL_REFRESHING && listViewLoadingLayout.getVisibility() == View.VISIBLE) {
mRefreshableView.setSelection(selection);
setHeaderScroll(scrollToHeight);
}
// Hide the ListView Header/Footer
listViewLoadingLayout.setVisibility(View.GONE);
super.resetHeader();
}
@Override
protected void setRefreshingInternal(boolean doScroll) {
// If we're not showing the Refreshing view, or the list is empty, then
// the header/footer views won't show so we use the
// normal method
ListAdapter adapter = mRefreshableView.getAdapter();
if (!getShowViewWhileRefreshing() || null == adapter || adapter.isEmpty()) {
super.setRefreshingInternal(doScroll);
return;
}
super.setRefreshingInternal(false);
final LoadingLayout originalLoadingLayout, listViewLoadingLayout;
final int selection, scrollToY;
switch (getCurrentMode()) {
case PULL_UP_TO_REFRESH:
originalLoadingLayout = getFooterLayout();
listViewLoadingLayout = mFooterLoadingView;
selection = mRefreshableView.getCount() - 1;
scrollToY = getScrollY() - getHeaderHeight();
break;
case PULL_DOWN_TO_REFRESH:
default:
originalLoadingLayout = getHeaderLayout();
listViewLoadingLayout = mHeaderLoadingView;
selection = 0;
scrollToY = getScrollY() + getFooterHeight();
break;
}
if (doScroll) {
// We scroll slightly so that the ListView's header/footer is at the
// same Y position as our normal header/footer
setHeaderScroll(scrollToY);
}
// Hide our original Loading View
originalLoadingLayout.setVisibility(View.INVISIBLE);
// Show the ListView Loading View and set it to refresh
listViewLoadingLayout.setVisibility(View.VISIBLE);
listViewLoadingLayout.refreshing();
if (doScroll) {
// Make sure the ListView is scrolled to show the loading
// header/footer
mRefreshableView.setSelection(selection);
// Smooth scroll as normal
smoothScrollTo(0);
}
}
protected class InternalListView extends ListView implements EmptyViewMethodAccessor {
private boolean mAddedLvFooter = false;
public InternalListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void draw(Canvas canvas) {
/**
* This is a bit hacky, but ListView has got a bug in it when using
* Header/Footer Views and the list is empty. This masks the issue
* so that it doesn't cause an FC. See Issue #66.
*/
try {
super.draw(canvas);
} catch (Exception e) {
e.printStackTrace();
}
}
public ContextMenuInfo getContextMenuInfo() {
return super.getContextMenuInfo();
}
@Override
public void setAdapter(ListAdapter adapter) {
// Add the Footer View at the last possible moment
if (!mAddedLvFooter) {
addFooterView(mLvFooterLoadingFrame, null, false);
mAddedLvFooter = true;
}
super.setAdapter(adapter);
}
@Override
public void setEmptyView(View emptyView) {
PullToRefreshListView.this.setEmptyView(emptyView);
}
@Override
public void setEmptyViewInternal(View emptyView) {
super.setEmptyView(emptyView);
}
}
@TargetApi(9)
final class InternalListViewSDK9 extends InternalListView {
public InternalListViewSDK9(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX,
int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
final boolean returnValue = super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX,
scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
// Does all of the hard work...
OverscrollHelper.overScrollBy(PullToRefreshListView.this, deltaY, scrollY, isTouchEvent);
return returnValue;
}
}
}
| |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.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 org.pentaho.di.trans.steps.jsonoutput;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.apache.commons.vfs2.FileObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Converts input rows to one or more XML files.
*
* @author Matt
* @since 14-jan-2006
*/
public class JsonOutput extends BaseStep implements StepInterface {
private static Class<?> PKG = JsonOutput.class; // for i18n purposes, needed by Translator2!!
private JsonOutputMeta meta;
private JsonOutputData data;
private interface CompatibilityFactory {
public void execute( Object[] row ) throws KettleException;
}
@SuppressWarnings( "unchecked" )
private class CompatibilityMode implements CompatibilityFactory {
public void execute( Object[] row ) throws KettleException {
for ( int i = 0; i < data.nrFields; i++ ) {
JsonOutputField outputField = meta.getOutputFields()[i];
ValueMetaInterface v = data.inputRowMeta.getValueMeta( data.fieldIndexes[i] );
// Create a new object with specified fields
JSONObject jo = new JSONObject();
switch ( v.getType() ) {
case ValueMetaInterface.TYPE_BOOLEAN:
jo.put( outputField.getElementName(), data.inputRowMeta.getBoolean( row, data.fieldIndexes[i] ) );
break;
case ValueMetaInterface.TYPE_INTEGER:
jo.put( outputField.getElementName(), data.inputRowMeta.getInteger( row, data.fieldIndexes[i] ) );
break;
case ValueMetaInterface.TYPE_NUMBER:
jo.put( outputField.getElementName(), data.inputRowMeta.getNumber( row, data.fieldIndexes[i] ) );
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
jo.put( outputField.getElementName(), data.inputRowMeta.getBigNumber( row, data.fieldIndexes[i] ) );
break;
default:
jo.put( outputField.getElementName(), data.inputRowMeta.getString( row, data.fieldIndexes[i] ) );
break;
}
data.ja.add( jo );
}
data.nrRow++;
if ( data.nrRowsInBloc > 0 ) {
// System.out.println("data.nrRow%data.nrRowsInBloc = "+ data.nrRow%data.nrRowsInBloc);
if ( data.nrRow % data.nrRowsInBloc == 0 ) {
// We can now output an object
// System.out.println("outputting the row.");
outPutRow( row );
}
}
}
}
@SuppressWarnings( "unchecked" )
private class FixedMode implements CompatibilityFactory {
public void execute( Object[] row ) throws KettleException {
// Create a new object with specified fields
JSONObject jo = new JSONObject();
for ( int i = 0; i < data.nrFields; i++ ) {
JsonOutputField outputField = meta.getOutputFields()[i];
ValueMetaInterface v = data.inputRowMeta.getValueMeta( data.fieldIndexes[i] );
switch ( v.getType() ) {
case ValueMetaInterface.TYPE_BOOLEAN:
jo.put( outputField.getElementName(), data.inputRowMeta.getBoolean( row, data.fieldIndexes[i] ) );
break;
case ValueMetaInterface.TYPE_INTEGER:
jo.put( outputField.getElementName(), data.inputRowMeta.getInteger( row, data.fieldIndexes[i] ) );
break;
case ValueMetaInterface.TYPE_NUMBER:
jo.put( outputField.getElementName(), data.inputRowMeta.getNumber( row, data.fieldIndexes[i] ) );
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
jo.put( outputField.getElementName(), data.inputRowMeta.getBigNumber( row, data.fieldIndexes[i] ) );
break;
default:
jo.put( outputField.getElementName(), data.inputRowMeta.getString( row, data.fieldIndexes[i] ) );
break;
}
}
data.ja.add( jo );
data.nrRow++;
if ( data.nrRowsInBloc > 0 ) {
// System.out.println("data.nrRow%data.nrRowsInBloc = "+ data.nrRow%data.nrRowsInBloc);
if ( data.nrRow % data.nrRowsInBloc == 0 ) {
// We can now output an object
// System.out.println("outputting the row.");
outPutRow( row );
}
}
}
}
private CompatibilityFactory compatibilityFactory;
public JsonOutput( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
Trans trans ) {
super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
// Here we decide whether or not to build the structure in
// compatible mode or fixed mode
JsonOutputMeta jsonOutputMeta = (JsonOutputMeta) ( stepMeta.getStepMetaInterface() );
if ( jsonOutputMeta.isCompatibilityMode() ) {
compatibilityFactory = new CompatibilityMode();
} else {
compatibilityFactory = new FixedMode();
}
}
public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
meta = (JsonOutputMeta) smi;
data = (JsonOutputData) sdi;
Object[] r = getRow(); // This also waits for a row to be finished.
if ( r == null ) {
// no more input to be expected...
if ( !data.rowsAreSafe ) {
// Let's output the remaining unsafe data
outPutRow( r );
}
setOutputDone();
return false;
}
if ( first ) {
first = false;
data.inputRowMeta = getInputRowMeta();
data.inputRowMetaSize = data.inputRowMeta.size();
if ( data.outputValue ) {
data.outputRowMeta = data.inputRowMeta.clone();
meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore );
}
// Cache the field name indexes
//
data.nrFields = meta.getOutputFields().length;
data.fieldIndexes = new int[data.nrFields];
for ( int i = 0; i < data.nrFields; i++ ) {
data.fieldIndexes[i] = data.inputRowMeta.indexOfValue( meta.getOutputFields()[i].getFieldName() );
if ( data.fieldIndexes[i] < 0 ) {
throw new KettleException( BaseMessages.getString( PKG, "JsonOutput.Exception.FieldNotFound" ) );
}
JsonOutputField field = meta.getOutputFields()[i];
field.setElementName( environmentSubstitute( field.getElementName() ) );
}
}
data.rowsAreSafe = false;
compatibilityFactory.execute( r );
if ( data.writeToFile && !data.outputValue ) {
putRow( data.inputRowMeta, r ); // in case we want it go further...
incrementLinesOutput();
}
return true;
}
@SuppressWarnings( "unchecked" )
private void outPutRow( Object[] rowData ) throws KettleStepException {
// We can now output an object
data.jg = new JSONObject();
data.jg.put( data.realBlocName, data.ja );
String value = data.jg.toJSONString();
if ( data.outputValue && data.outputRowMeta != null ) {
Object[] outputRowData = RowDataUtil.addValueData( rowData, data.inputRowMetaSize, value );
incrementLinesOutput();
putRow( data.outputRowMeta, outputRowData );
}
if ( data.writeToFile ) {
// Open a file
if ( !openNewFile() ) {
throw new KettleStepException( BaseMessages.getString(
PKG, "JsonOutput.Error.OpenNewFile", buildFilename() ) );
}
// Write data to file
try {
data.writer.write( value );
} catch ( Exception e ) {
throw new KettleStepException( BaseMessages.getString( PKG, "JsonOutput.Error.Writing" ), e );
}
// Close file
closeFile();
}
// Data are safe
data.rowsAreSafe = true;
data.ja = new JSONArray();
}
public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (JsonOutputMeta) smi;
data = (JsonOutputData) sdi;
if ( super.init( smi, sdi ) ) {
data.writeToFile = ( meta.getOperationType() != JsonOutputMeta.OPERATION_TYPE_OUTPUT_VALUE );
data.outputValue = ( meta.getOperationType() != JsonOutputMeta.OPERATION_TYPE_WRITE_TO_FILE );
if ( data.outputValue ) {
// We need to have output field name
if ( Const.isEmpty( environmentSubstitute( meta.getOutputValue() ) ) ) {
logError( BaseMessages.getString( PKG, "JsonOutput.Error.MissingOutputFieldName" ) );
stopAll();
setErrors( 1 );
return false;
}
}
if ( data.writeToFile ) {
// We need to have output field name
if ( !meta.isServletOutput() && Const.isEmpty( meta.getFileName() ) ) {
logError( BaseMessages.getString( PKG, "JsonOutput.Error.MissingTargetFilename" ) );
stopAll();
setErrors( 1 );
return false;
}
if ( !meta.isDoNotOpenNewFileInit() ) {
if ( !openNewFile() ) {
logError( BaseMessages.getString( PKG, "JsonOutput.Error.OpenNewFile", buildFilename() ) );
stopAll();
setErrors( 1 );
return false;
}
}
}
data.realBlocName = Const.NVL( environmentSubstitute( meta.getJsonBloc() ), "" );
data.nrRowsInBloc = Const.toInt( environmentSubstitute( meta.getNrRowsInBloc() ), 0 );
return true;
}
return false;
}
public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
meta = (JsonOutputMeta) smi;
data = (JsonOutputData) sdi;
if ( data.ja != null ) {
data.ja = null;
}
if ( data.jg != null ) {
data.jg = null;
}
closeFile();
super.dispose( smi, sdi );
}
private void createParentFolder( String filename ) throws KettleStepException {
if ( !meta.isCreateParentFolder() ) {
return;
}
// Check for parent folder
FileObject parentfolder = null;
try {
// Get parent folder
parentfolder = KettleVFS.getFileObject( filename, getTransMeta() ).getParent();
if ( !parentfolder.exists() ) {
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "JsonOutput.Error.ParentFolderNotExist", parentfolder.getName() ) );
}
parentfolder.createFolder();
if ( log.isDebug() ) {
logDebug( BaseMessages.getString( PKG, "JsonOutput.Log.ParentFolderCreated" ) );
}
}
} catch ( Exception e ) {
throw new KettleStepException( BaseMessages.getString(
PKG, "JsonOutput.Error.ErrorCreatingParentFolder", parentfolder.getName() ) );
} finally {
if ( parentfolder != null ) {
try {
parentfolder.close();
} catch ( Exception ex ) { /* Ignore */
}
}
}
}
public boolean openNewFile() {
if ( data.writer != null ) {
return true;
}
boolean retval = false;
try {
if ( meta.isServletOutput() ) {
data.writer = getTrans().getServletPrintWriter();
} else {
String filename = buildFilename();
createParentFolder( filename );
if ( meta.AddToResult() ) {
// Add this to the result file names...
ResultFile resultFile =
new ResultFile(
ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject( filename, getTransMeta() ),
getTransMeta().getName(), getStepname() );
resultFile.setComment( BaseMessages.getString( PKG, "JsonOutput.ResultFilenames.Comment" ) );
addResultFile( resultFile );
}
OutputStream outputStream;
OutputStream fos = KettleVFS.getOutputStream( filename, getTransMeta(), meta.isFileAppended() );
outputStream = fos;
if ( !Const.isEmpty( meta.getEncoding() ) ) {
data.writer =
new OutputStreamWriter( new BufferedOutputStream( outputStream, 5000 ), environmentSubstitute( meta
.getEncoding() ) );
} else {
data.writer = new OutputStreamWriter( new BufferedOutputStream( outputStream, 5000 ) );
}
if ( log.isDetailed() ) {
logDetailed( BaseMessages.getString( PKG, "JsonOutput.FileOpened", filename ) );
}
data.splitnr++;
}
retval = true;
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "JsonOutput.Error.OpeningFile", e.toString() ) );
}
return retval;
}
public String buildFilename() {
return meta.buildFilename( environmentSubstitute( meta.getFileName() ), getCopy(), data.splitnr );
}
private boolean closeFile() {
if ( data.writer == null ) {
return true;
}
boolean retval = false;
try {
data.writer.close();
data.writer = null;
retval = true;
} catch ( Exception e ) {
logError( BaseMessages.getString( PKG, "JsonOutput.Error.ClosingFile", e.toString() ) );
setErrors( 1 );
retval = false;
}
return retval;
}
}
| |
/*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.of.group.impl;
import com.google.common.collect.Maps;
import org.onlab.util.ItemNotFoundException;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.core.GroupId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.driver.Driver;
import org.onosproject.net.driver.DriverService;
import org.onosproject.net.group.DefaultGroup;
import org.onosproject.net.group.Group;
import org.onosproject.net.group.GroupBucket;
import org.onosproject.net.group.GroupBuckets;
import org.onosproject.net.group.GroupDescription;
import org.onosproject.net.group.GroupOperation;
import org.onosproject.net.group.GroupOperation.GroupMsgErrorCode;
import org.onosproject.net.group.GroupOperations;
import org.onosproject.net.group.GroupProvider;
import org.onosproject.net.group.GroupProviderRegistry;
import org.onosproject.net.group.GroupProviderService;
import org.onosproject.net.group.GroupService;
import org.onosproject.net.group.StoredGroupBucketEntry;
import org.onosproject.net.provider.AbstractProvider;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.openflow.controller.Dpid;
import org.onosproject.openflow.controller.OpenFlowController;
import org.onosproject.openflow.controller.OpenFlowEventListener;
import org.onosproject.openflow.controller.OpenFlowSwitch;
import org.onosproject.openflow.controller.OpenFlowSwitchListener;
import org.onosproject.openflow.controller.RoleState;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Modified;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.projectfloodlight.openflow.protocol.OFBucketCounter;
import org.projectfloodlight.openflow.protocol.OFCapabilities;
import org.projectfloodlight.openflow.protocol.OFErrorMsg;
import org.projectfloodlight.openflow.protocol.OFErrorType;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupMod;
import org.projectfloodlight.openflow.protocol.OFGroupModFailedCode;
import org.projectfloodlight.openflow.protocol.OFGroupStatsEntry;
import org.projectfloodlight.openflow.protocol.OFGroupStatsReply;
import org.projectfloodlight.openflow.protocol.OFGroupType;
import org.projectfloodlight.openflow.protocol.OFMessage;
import org.projectfloodlight.openflow.protocol.OFPortDesc;
import org.projectfloodlight.openflow.protocol.OFPortStatus;
import org.projectfloodlight.openflow.protocol.OFStatsReply;
import org.projectfloodlight.openflow.protocol.OFStatsType;
import org.projectfloodlight.openflow.protocol.OFVersion;
import org.projectfloodlight.openflow.protocol.errormsg.OFGroupModFailedErrorMsg;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicLong;
import static org.onlab.util.Tools.getIntegerProperty;
import static org.onosproject.provider.of.group.impl.OsgiPropertyConstants.POLL_FREQUENCY;
import static org.onosproject.provider.of.group.impl.OsgiPropertyConstants.POLL_FREQUENCY_DEFAULT;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provider which uses an OpenFlow controller to handle Group.
*/
@Component(immediate = true,
property = {
POLL_FREQUENCY + ":Integer=" + POLL_FREQUENCY_DEFAULT,
})
public class OpenFlowGroupProvider extends AbstractProvider implements GroupProvider {
private final Logger log = getLogger(getClass());
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected OpenFlowController controller;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected GroupProviderRegistry providerRegistry;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected DriverService driverService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected DeviceService deviceService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected GroupService groupService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected ComponentConfigService cfgService;
private GroupProviderService providerService;
private static final String COMPONENT = "org.onosproject.provider.of.group.impl.OpenFlowGroupProvider";
/** Frequency (in seconds) for polling group statistics. */
private int groupPollInterval = POLL_FREQUENCY_DEFAULT;
private final InternalGroupProvider listener = new InternalGroupProvider();
private static final AtomicLong XID_COUNTER = new AtomicLong(1);
private final Map<Dpid, GroupStatsCollector> collectors = Maps.newHashMap();
private final Map<Long, OFStatsReply> groupStats = Maps.newConcurrentMap();
private final Map<GroupId, GroupOperation> pendingGroupOperations =
Maps.newConcurrentMap();
/* Map<Group ID, Transaction ID> */
private final Map<GroupId, Long> pendingXidMaps = Maps.newConcurrentMap();
/**
* Creates a OpenFlow group provider.
*/
public OpenFlowGroupProvider() {
super(new ProviderId("of", "org.onosproject.provider.group"));
}
@Activate
public void activate(ComponentContext context) {
cfgService.registerProperties(getClass());
providerService = providerRegistry.register(this);
controller.addListener(listener);
controller.addEventListener(listener);
modified(context);
for (OpenFlowSwitch sw : controller.getSwitches()) {
if (isGroupSupported(sw)) {
GroupStatsCollector gsc = new GroupStatsCollector(sw, groupPollInterval);
gsc.start();
collectors.put(new Dpid(sw.getId()), gsc);
}
}
log.info("Started");
}
@Deactivate
public void deactivate() {
cfgService.unregisterProperties(getClass(), false);
providerRegistry.unregister(this);
providerService = null;
collectors.values().forEach(GroupStatsCollector::stop);
collectors.clear();
log.info("Stopped");
}
@Modified
public void modified(ComponentContext context) {
Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
Integer newGroupPollInterval = getIntegerProperty(properties, POLL_FREQUENCY);
if (newGroupPollInterval != null && newGroupPollInterval > 0
&& newGroupPollInterval != groupPollInterval) {
groupPollInterval = newGroupPollInterval;
modifyPollInterval();
} else if (newGroupPollInterval != null && newGroupPollInterval <= 0) {
log.warn("groupPollInterval must be greater than 0");
//If the new value <= 0 reset property with old value.
cfgService.setProperty(COMPONENT, POLL_FREQUENCY, Integer.toString(groupPollInterval));
}
}
private void modifyPollInterval() {
collectors.values().forEach(gsc -> gsc.adjustRate(groupPollInterval));
}
@Override
public void performGroupOperation(DeviceId deviceId, GroupOperations groupOps) {
final Dpid dpid = Dpid.dpid(deviceId.uri());
OpenFlowSwitch sw = controller.getSwitch(dpid);
for (GroupOperation groupOperation: groupOps.operations()) {
if (sw == null) {
log.error("SW {} is not found", dpid);
return;
}
switch (groupOperation.groupType()) {
case SELECT:
case INDIRECT:
case ALL:
case FAILOVER:
break;
case CLONE:
default:
log.warn("Group type {} not supported, ignoring operation [{}]",
groupOperation.groupType(), groupOperation);
// Next groupOperation.
continue;
}
final Long groupModXid = XID_COUNTER.getAndIncrement();
GroupModBuilder builder = null;
if (driverService == null) {
builder = GroupModBuilder.builder(groupOperation.buckets(),
groupOperation.groupId(),
groupOperation.groupType(),
sw.factory(),
Optional.of(groupModXid));
} else {
builder = GroupModBuilder.builder(groupOperation.buckets(),
groupOperation.groupId(),
groupOperation.groupType(),
sw.factory(),
Optional.of(groupModXid),
Optional.of(driverService));
}
OFGroupMod groupMod = null;
switch (groupOperation.opType()) {
case ADD:
groupMod = builder.buildGroupAdd();
break;
case MODIFY:
groupMod = builder.buildGroupMod();
break;
case DELETE:
groupMod = builder.buildGroupDel();
break;
default:
log.error("Unsupported Group operation");
return;
}
sw.sendMsg(groupMod);
GroupId groudId = new GroupId(groupMod.getGroup().getGroupNumber());
pendingGroupOperations.put(groudId, groupOperation);
pendingXidMaps.put(groudId, groupModXid);
}
}
private void pushGroupMetrics(Dpid dpid, OFStatsReply statsReply) {
DeviceId deviceId = DeviceId.deviceId(Dpid.uri(dpid));
OpenFlowSwitch sw = controller.getSwitch(dpid);
boolean containsGroupStats = false;
if (sw != null && sw.features() != null) {
containsGroupStats = sw.features()
.getCapabilities()
.contains(OFCapabilities.GROUP_STATS);
}
OFGroupStatsReply groupStatsReply = null;
OFGroupDescStatsReply groupDescStatsReply = null;
if (containsGroupStats) {
synchronized (groupStats) {
if (statsReply.getStatsType() == OFStatsType.GROUP) {
OFStatsReply reply = groupStats.get(statsReply.getXid() + 1);
if (reply != null) {
groupStatsReply = (OFGroupStatsReply) statsReply;
groupDescStatsReply = (OFGroupDescStatsReply) reply;
groupStats.remove(statsReply.getXid() + 1);
} else {
groupStats.put(statsReply.getXid(), statsReply);
}
} else if (statsReply.getStatsType() == OFStatsType.GROUP_DESC) {
OFStatsReply reply = groupStats.get(statsReply.getXid() - 1);
if (reply != null) {
groupStatsReply = (OFGroupStatsReply) reply;
groupDescStatsReply = (OFGroupDescStatsReply) statsReply;
groupStats.remove(statsReply.getXid() - 1);
} else {
groupStats.put(statsReply.getXid(), statsReply);
}
}
}
} else if (statsReply.getStatsType() == OFStatsType.GROUP_DESC) {
// We are only requesting group desc stats; see GroupStatsCollector.java:sendGroupStatisticRequests()
groupDescStatsReply = (OFGroupDescStatsReply) statsReply;
}
if (providerService != null && groupDescStatsReply != null) {
Collection<Group> groups = buildGroupMetrics(deviceId,
groupStatsReply, groupDescStatsReply);
providerService.pushGroupMetrics(deviceId, groups);
for (Group group: groups) {
pendingGroupOperations.remove(group.id());
pendingXidMaps.remove(group.id());
}
}
}
private Collection<Group> buildGroupMetrics(DeviceId deviceId,
OFGroupStatsReply groupStatsReply,
OFGroupDescStatsReply groupDescStatsReply) {
Map<Integer, Group> groups = Maps.newHashMap();
Dpid dpid = Dpid.dpid(deviceId.uri());
for (OFGroupDescStatsEntry entry: groupDescStatsReply.getEntries()) {
int id = entry.getGroup().getGroupNumber();
GroupId groupId = new GroupId(id);
GroupDescription.Type type = getGroupType(entry.getGroupType());
GroupBuckets buckets = new GroupBucketEntryBuilder(dpid, entry.getBuckets(),
entry.getGroupType(), driverService).build();
DefaultGroup group = new DefaultGroup(groupId, deviceId, type, buckets);
groups.put(id, group);
}
if (groupStatsReply == null) {
return groups.values();
}
for (OFGroupStatsEntry entry: groupStatsReply.getEntries()) {
int groupId = entry.getGroup().getGroupNumber();
DefaultGroup group = (DefaultGroup) groups.get(groupId);
if (group != null) {
group.setBytes(entry.getByteCount().getValue());
group.setLife(entry.getDurationSec());
group.setPackets(entry.getPacketCount().getValue());
group.setReferenceCount(entry.getRefCount());
int bucketIndex = 0;
for (OFBucketCounter bucketStats:entry.getBucketStats()) {
((StoredGroupBucketEntry) group.buckets().buckets()
.get(bucketIndex))
.setPackets(bucketStats
.getPacketCount().getValue());
((StoredGroupBucketEntry) group.buckets().buckets()
.get(bucketIndex))
.setBytes(entry.getBucketStats()
.get(bucketIndex)
.getByteCount().getValue());
bucketIndex++;
}
}
}
return groups.values();
}
private GroupDescription.Type getGroupType(OFGroupType type) {
switch (type) {
case ALL:
return GroupDescription.Type.ALL;
case INDIRECT:
return GroupDescription.Type.INDIRECT;
case SELECT:
return GroupDescription.Type.SELECT;
case FF:
return GroupDescription.Type.FAILOVER;
default:
log.error("Unsupported OF group type : {}", type);
break;
}
return null;
}
/**
* Returns a transaction ID for entire group operations and increases
* the counter by the number given.
*
* @param increase the amount to increase the counter by
* @return a transaction ID
*/
public static long getXidAndAdd(int increase) {
return XID_COUNTER.getAndAdd(increase);
}
private boolean isGroupSupported(OpenFlowSwitch sw) {
if (sw.factory().getVersion() == OFVersion.OF_10 ||
sw.factory().getVersion() == OFVersion.OF_11 ||
sw.factory().getVersion() == OFVersion.OF_12 ||
!isGroupCapable(sw)) {
return false;
}
return true;
}
/**
* Determine whether the given switch is group-capable.
*
* @param sw switch
* @return the boolean value of groupCapable property, or true if it is not configured.
*/
private boolean isGroupCapable(OpenFlowSwitch sw) {
Driver driver;
try {
driver = driverService.getDriver(DeviceId.deviceId(Dpid.uri(sw.getDpid())));
} catch (ItemNotFoundException e) {
driver = driverService.getDriver(sw.manufacturerDescription(),
sw.hardwareDescription(),
sw.softwareDescription());
}
if (driver == null) {
return true;
}
String isGroupCapable = driver.getProperty(GROUP_CAPABLE);
return isGroupCapable == null || Boolean.parseBoolean(isGroupCapable);
}
private class InternalGroupProvider
implements OpenFlowSwitchListener, OpenFlowEventListener {
@Override
public void handleMessage(Dpid dpid, OFMessage msg) {
switch (msg.getType()) {
case STATS_REPLY:
pushGroupMetrics(dpid, (OFStatsReply) msg);
break;
case ERROR:
OFErrorMsg errorMsg = (OFErrorMsg) msg;
if (errorMsg.getErrType() == OFErrorType.GROUP_MOD_FAILED) {
GroupId pendingGroupId = null;
for (Map.Entry<GroupId, Long> entry: pendingXidMaps.entrySet()) {
if (entry.getValue() == errorMsg.getXid()) {
pendingGroupId = entry.getKey();
break;
}
}
if (pendingGroupId == null) {
log.warn("Error for unknown group operation: {}",
errorMsg.getXid());
} else {
GroupOperation operation =
pendingGroupOperations.get(pendingGroupId);
DeviceId deviceId = DeviceId.deviceId(Dpid.uri(dpid));
if (operation != null) {
OFGroupModFailedCode code =
((OFGroupModFailedErrorMsg) errorMsg).getCode();
GroupMsgErrorCode failureCode =
GroupMsgErrorCode.values()[(code.ordinal())];
GroupOperation failedOperation = GroupOperation
.createFailedGroupOperation(operation, failureCode);
log.warn("Received a group mod error {}", msg);
providerService.groupOperationFailed(deviceId,
failedOperation);
pendingGroupOperations.remove(pendingGroupId);
pendingXidMaps.remove(pendingGroupId);
} else {
log.error("Cannot find pending group operation with group ID: {}",
pendingGroupId);
}
}
break;
}
default:
break;
}
}
@Override
public void switchAdded(Dpid dpid) {
OpenFlowSwitch sw = controller.getSwitch(dpid);
if (sw == null) {
return;
}
if (isGroupSupported(sw)) {
GroupStatsCollector gsc = new GroupStatsCollector(sw, groupPollInterval);
stopCollectorIfNeeded(collectors.put(dpid, gsc));
gsc.start();
}
//figure out race condition
if (controller.getSwitch(dpid) == null) {
switchRemoved(dpid);
}
}
@Override
public void switchRemoved(Dpid dpid) {
stopCollectorIfNeeded(collectors.remove(dpid));
}
private void stopCollectorIfNeeded(GroupStatsCollector collector) {
if (collector != null) {
collector.stop();
}
}
@Override
public void switchChanged(Dpid dpid) {
}
@Override
public void portChanged(Dpid dpid, OFPortStatus status) {
providerService.notifyOfFailovers(checkFailoverGroups(dpid, status));
}
@Override
public void receivedRoleReply(Dpid dpid, RoleState requested, RoleState response) {
}
}
/**
* Builds a list of failover Groups whose primary live bucket failed over
* (i.e. bucket in use has changed).
*
* @param dpid DPID of switch whose port's status changed
* @param status new status of port
* @return list of groups whose primary live bucket failed over
*/
private List<Group> checkFailoverGroups(Dpid dpid, OFPortStatus status) {
List<Group> groupList = new ArrayList<>();
OFPortDesc desc = status.getDesc();
PortNumber portNumber = PortNumber.portNumber(desc.getPortNo().getPortNumber());
DeviceId id = DeviceId.deviceId(Dpid.uri(dpid));
if (desc.isEnabled()) {
return groupList;
}
Iterator<Group> iterator = groupService.getGroups(id).iterator();
while (iterator.hasNext()) {
Group group = iterator.next();
if (group.type() == GroupDescription.Type.FAILOVER &&
checkFailoverGroup(group, id, portNumber)) {
groupList.add(group);
}
}
return groupList;
}
/**
* Checks whether the first live port in the failover group's bucket
* has failed over.
*
* @param group failover group to be checked for failover
* @param id device ID of switch whose port's status changed
* @param portNumber port number of port that was disabled
* @return whether the failover group experienced failover
*/
private boolean checkFailoverGroup(Group group, DeviceId id,
PortNumber portNumber) {
boolean portReached = false;
boolean portEnabled = false;
Iterator<GroupBucket> bIterator = group.buckets().buckets().iterator();
GroupBucket bucket;
while (bIterator.hasNext() && !portReached) {
bucket = bIterator.next();
if (deviceService.getPort(id, bucket.watchPort()).isEnabled()) {
portEnabled = true;
}
if (bucket.watchPort().equals(portNumber)) {
portReached = true;
}
}
return portReached && !portEnabled;
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.chimesdkmeetings.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/chime-sdk-meetings-2021-07-15/CreateMeetingWithAttendees"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateMeetingWithAttendeesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* The meeting information, including the meeting ID and <code>MediaPlacement</code>.
* </p>
*/
private Meeting meeting;
/**
* <p>
* The attendee information, including attendees' IDs and join tokens.
* </p>
*/
private java.util.List<Attendee> attendees;
/**
* <p>
* If the action fails for one or more of the attendees in the request, a list of the attendees is returned, along
* with error codes and error messages.
* </p>
*/
private java.util.List<CreateAttendeeError> errors;
/**
* <p>
* The meeting information, including the meeting ID and <code>MediaPlacement</code>.
* </p>
*
* @param meeting
* The meeting information, including the meeting ID and <code>MediaPlacement</code>.
*/
public void setMeeting(Meeting meeting) {
this.meeting = meeting;
}
/**
* <p>
* The meeting information, including the meeting ID and <code>MediaPlacement</code>.
* </p>
*
* @return The meeting information, including the meeting ID and <code>MediaPlacement</code>.
*/
public Meeting getMeeting() {
return this.meeting;
}
/**
* <p>
* The meeting information, including the meeting ID and <code>MediaPlacement</code>.
* </p>
*
* @param meeting
* The meeting information, including the meeting ID and <code>MediaPlacement</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateMeetingWithAttendeesResult withMeeting(Meeting meeting) {
setMeeting(meeting);
return this;
}
/**
* <p>
* The attendee information, including attendees' IDs and join tokens.
* </p>
*
* @return The attendee information, including attendees' IDs and join tokens.
*/
public java.util.List<Attendee> getAttendees() {
return attendees;
}
/**
* <p>
* The attendee information, including attendees' IDs and join tokens.
* </p>
*
* @param attendees
* The attendee information, including attendees' IDs and join tokens.
*/
public void setAttendees(java.util.Collection<Attendee> attendees) {
if (attendees == null) {
this.attendees = null;
return;
}
this.attendees = new java.util.ArrayList<Attendee>(attendees);
}
/**
* <p>
* The attendee information, including attendees' IDs and join tokens.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setAttendees(java.util.Collection)} or {@link #withAttendees(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param attendees
* The attendee information, including attendees' IDs and join tokens.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateMeetingWithAttendeesResult withAttendees(Attendee... attendees) {
if (this.attendees == null) {
setAttendees(new java.util.ArrayList<Attendee>(attendees.length));
}
for (Attendee ele : attendees) {
this.attendees.add(ele);
}
return this;
}
/**
* <p>
* The attendee information, including attendees' IDs and join tokens.
* </p>
*
* @param attendees
* The attendee information, including attendees' IDs and join tokens.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateMeetingWithAttendeesResult withAttendees(java.util.Collection<Attendee> attendees) {
setAttendees(attendees);
return this;
}
/**
* <p>
* If the action fails for one or more of the attendees in the request, a list of the attendees is returned, along
* with error codes and error messages.
* </p>
*
* @return If the action fails for one or more of the attendees in the request, a list of the attendees is returned,
* along with error codes and error messages.
*/
public java.util.List<CreateAttendeeError> getErrors() {
return errors;
}
/**
* <p>
* If the action fails for one or more of the attendees in the request, a list of the attendees is returned, along
* with error codes and error messages.
* </p>
*
* @param errors
* If the action fails for one or more of the attendees in the request, a list of the attendees is returned,
* along with error codes and error messages.
*/
public void setErrors(java.util.Collection<CreateAttendeeError> errors) {
if (errors == null) {
this.errors = null;
return;
}
this.errors = new java.util.ArrayList<CreateAttendeeError>(errors);
}
/**
* <p>
* If the action fails for one or more of the attendees in the request, a list of the attendees is returned, along
* with error codes and error messages.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setErrors(java.util.Collection)} or {@link #withErrors(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param errors
* If the action fails for one or more of the attendees in the request, a list of the attendees is returned,
* along with error codes and error messages.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateMeetingWithAttendeesResult withErrors(CreateAttendeeError... errors) {
if (this.errors == null) {
setErrors(new java.util.ArrayList<CreateAttendeeError>(errors.length));
}
for (CreateAttendeeError ele : errors) {
this.errors.add(ele);
}
return this;
}
/**
* <p>
* If the action fails for one or more of the attendees in the request, a list of the attendees is returned, along
* with error codes and error messages.
* </p>
*
* @param errors
* If the action fails for one or more of the attendees in the request, a list of the attendees is returned,
* along with error codes and error messages.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateMeetingWithAttendeesResult withErrors(java.util.Collection<CreateAttendeeError> errors) {
setErrors(errors);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getMeeting() != null)
sb.append("Meeting: ").append(getMeeting()).append(",");
if (getAttendees() != null)
sb.append("Attendees: ").append(getAttendees()).append(",");
if (getErrors() != null)
sb.append("Errors: ").append(getErrors());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateMeetingWithAttendeesResult == false)
return false;
CreateMeetingWithAttendeesResult other = (CreateMeetingWithAttendeesResult) obj;
if (other.getMeeting() == null ^ this.getMeeting() == null)
return false;
if (other.getMeeting() != null && other.getMeeting().equals(this.getMeeting()) == false)
return false;
if (other.getAttendees() == null ^ this.getAttendees() == null)
return false;
if (other.getAttendees() != null && other.getAttendees().equals(this.getAttendees()) == false)
return false;
if (other.getErrors() == null ^ this.getErrors() == null)
return false;
if (other.getErrors() != null && other.getErrors().equals(this.getErrors()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getMeeting() == null) ? 0 : getMeeting().hashCode());
hashCode = prime * hashCode + ((getAttendees() == null) ? 0 : getAttendees().hashCode());
hashCode = prime * hashCode + ((getErrors() == null) ? 0 : getErrors().hashCode());
return hashCode;
}
@Override
public CreateMeetingWithAttendeesResult clone() {
try {
return (CreateMeetingWithAttendeesResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/*
* 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.ignite.internal.processors.cache.eviction;
import org.apache.ignite.*;
import org.apache.ignite.cache.*;
import org.apache.ignite.cache.eviction.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.spi.discovery.tcp.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.*;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*;
import org.apache.ignite.testframework.junits.common.*;
import org.apache.ignite.transactions.*;
import org.jetbrains.annotations.*;
import javax.cache.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static org.apache.ignite.cache.CacheAtomicityMode.*;
import static org.apache.ignite.cache.CacheMode.*;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.*;
import static org.apache.ignite.events.EventType.*;
import static org.apache.ignite.transactions.TransactionConcurrency.*;
import static org.apache.ignite.transactions.TransactionIsolation.*;
/**
* Base class for eviction tests.
*/
public abstract class GridCacheEvictionAbstractTest<T extends EvictionPolicy<?, ?>>
extends GridCommonAbstractTest {
/** IP finder. */
protected static final TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true);
/** Replicated cache. */
protected CacheMode mode = REPLICATED;
/** Near enabled flag. */
protected boolean nearEnabled;
/** Evict backup sync. */
protected boolean evictSync;
/** Evict near sync. */
protected boolean evictNearSync = true;
/** Policy max. */
protected int plcMax = 10;
/** Near policy max. */
protected int nearMax = 3;
/** Synchronous commit. */
protected boolean syncCommit;
/** */
protected int gridCnt = 2;
/** */
protected EvictionFilter<?, ?> filter;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
IgniteConfiguration c = super.getConfiguration(gridName);
CacheConfiguration cc = defaultCacheConfiguration();
cc.setCacheMode(mode);
cc.setEvictionPolicy(createPolicy(plcMax));
cc.setEvictSynchronized(evictSync);
cc.setSwapEnabled(false);
cc.setWriteSynchronizationMode(syncCommit ? FULL_SYNC : FULL_ASYNC);
cc.setStartSize(plcMax);
cc.setAtomicityMode(TRANSACTIONAL);
if (nearEnabled) {
NearCacheConfiguration nearCfg = new NearCacheConfiguration();
nearCfg.setNearEvictionPolicy(createNearPolicy(nearMax));
cc.setNearConfiguration(nearCfg);
}
else
cc.setNearConfiguration(null);
if (mode == PARTITIONED)
cc.setBackups(1);
if (filter != null)
cc.setEvictionFilter(filter);
c.setCacheConfiguration(cc);
TcpDiscoverySpi disco = new TcpDiscoverySpi();
disco.setIpFinder(ipFinder);
c.setDiscoverySpi(disco);
c.setIncludeEventTypes(EVT_TASK_FAILED, EVT_TASK_FINISHED, EVT_JOB_MAPPED);
c.setIncludeProperties();
return c;
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
filter = null;
super.afterTestsStopped();
}
/**
* @param arr Array.
* @param idx Index.
* @return Entry at the index.
*/
protected MockEntry entry(MockEntry[] arr, int idx) {
MockEntry e = arr[idx];
if (e.isEvicted())
e = arr[idx] = new MockEntry(e.getKey());
return e;
}
/**
* @param prefix Prefix.
* @param p Policy.
*/
protected void info(String prefix, EvictionPolicy<?, ?> p) {
info(prefix + ": " + p.toString());
}
/** @param p Policy. */
protected void info(EvictionPolicy<?, ?> p) {
info(p.toString());
}
/**
* @param c1 Policy collection.
* @param c2 Expected list.
*/
protected void check(Collection<EvictableEntry<String, String>> c1, MockEntry... c2) {
check(c1, F.asList(c2));
}
/** @return Policy. */
@SuppressWarnings({"unchecked"})
protected T policy() {
return (T)grid().cache(null).getConfiguration(CacheConfiguration.class).getEvictionPolicy();
}
/**
* @param i Grid index.
* @return Policy.
*/
@SuppressWarnings({"unchecked"})
protected T policy(int i) {
return (T)grid(i).cache(null).getConfiguration(CacheConfiguration.class).getEvictionPolicy();
}
/**
* @param i Grid index.
* @return Policy.
*/
@SuppressWarnings({"unchecked"})
protected T nearPolicy(int i) {
CacheConfiguration cfg = grid(i).cache(null).getConfiguration(CacheConfiguration.class);
NearCacheConfiguration nearCfg = cfg.getNearConfiguration();
return (T)(nearCfg == null ? null : nearCfg.getNearEvictionPolicy());
}
/**
* @param c1 Policy collection.
* @param c2 Expected list.
*/
protected void check(Collection<EvictableEntry<String, String>> c1, List<MockEntry> c2) {
assert c1.size() == c2.size() : "Mismatch [actual=" + string(c1) + ", expected=" + string(c2) + ']';
assert c1.containsAll(c2) : "Mismatch [actual=" + string(c1) + ", expected=" + string(c2) + ']';
int i = 0;
// Check order.
for (Cache.Entry<String, String> e : c1)
assertEquals(e, c2.get(i++));
}
/**
* @param c Collection.
* @return String.
*/
@SuppressWarnings("unchecked")
protected String string(Iterable<? extends Cache.Entry> c) {
return "[" +
F.fold(
c,
"",
new C2<Cache.Entry, String, String>() {
@Override public String apply(Cache.Entry e, String b) {
return b.isEmpty() ? e.getKey().toString() : b + ", " + e.getKey();
}
}) +
"]]";
}
/** @throws Exception If failed. */
public void testPartitionedNearDisabled() throws Exception {
mode = PARTITIONED;
nearEnabled = false;
plcMax = 10;
syncCommit = true;
gridCnt = 2;
checkPartitioned(plcMax, plcMax, false);
}
/** @throws Exception If failed. */
public void testPartitionedNearEnabled() throws Exception {
mode = PARTITIONED;
nearEnabled = true;
nearMax = 3;
plcMax = 10;
evictNearSync = true;
syncCommit = true;
gridCnt = 2;
checkPartitioned(0, 0, true); // Near size is 0 because of backups present.
}
/** @throws Exception If failed. */
public void testPartitionedNearDisabledMultiThreaded() throws Exception {
mode = PARTITIONED;
nearEnabled = false;
plcMax = 100;
evictSync = false;
gridCnt = 2;
checkPartitionedMultiThreaded(gridCnt);
}
/** @throws Exception If failed. */
public void testPartitionedNearDisabledBackupSyncMultiThreaded() throws Exception {
mode = PARTITIONED;
nearEnabled = false;
plcMax = 100;
evictSync = true;
gridCnt = 2;
checkPartitionedMultiThreaded(gridCnt);
}
/** @throws Exception If failed. */
public void testPartitionedNearEnabledMultiThreaded() throws Exception {
mode = PARTITIONED;
nearEnabled = true;
plcMax = 10;
evictSync = false;
gridCnt = 2;
checkPartitionedMultiThreaded(gridCnt);
}
/** @throws Exception If failed. */
public void testPartitionedNearEnabledBackupSyncMultiThreaded() throws Exception {
mode = PARTITIONED;
nearEnabled = true;
plcMax = 10;
evictSync = true;
gridCnt = 2;
checkPartitionedMultiThreaded(gridCnt);
}
/**
* @param endSize Final near size.
* @param endPlcSize Final near policy size.
* @throws Exception If failed.
*/
private void checkPartitioned(int endSize, int endPlcSize, boolean near) throws Exception {
startGridsMultiThreaded(gridCnt);
try {
Random rand = new Random();
int cnt = 500;
for (int i = 0; i < cnt; i++) {
IgniteCache<Integer, String> cache = grid(rand.nextInt(2)).cache(null);
int key = rand.nextInt(100);
String val = Integer.toString(key);
cache.put(key, val);
if (i % 100 == 0)
info("Stored cache object for key [key=" + key + ", idx=" + i + ']');
}
if (near) {
for (int i = 0; i < gridCnt; i++)
assertEquals(endSize, near(i).nearSize());
if (endPlcSize >= 0)
checkNearPolicies(endPlcSize);
}
else {
for (int i = 0; i < gridCnt; i++) {
int actual = colocated(i).size();
assertTrue("Cache size is greater then policy size [expected=" + endSize + ", actual=" + actual + ']',
actual <= endSize);
}
checkPolicies(endPlcSize);
}
}
finally {
stopAllGrids();
}
}
/**
* @param gridCnt Grid count.
* @throws Exception If failed.
*/
protected void checkPartitionedMultiThreaded(int gridCnt) throws Exception {
try {
startGridsMultiThreaded(gridCnt);
final Random rand = new Random();
final AtomicInteger cntr = new AtomicInteger();
multithreaded(new Callable() {
@Nullable @Override public Object call() throws Exception {
int cnt = 100;
for (int i = 0; i < cnt && !Thread.currentThread().isInterrupted(); i++) {
IgniteEx grid = grid(rand.nextInt(2));
IgniteCache<Integer, String> cache = grid.cache(null);
int key = rand.nextInt(1000);
String val = Integer.toString(key);
try (Transaction tx = grid.transactions().txStart(PESSIMISTIC, REPEATABLE_READ)) {
String v = cache.get(key);
assert v == null || v.equals(Integer.toString(key)) : "Invalid value for key [key=" + key +
", val=" + v + ']';
cache.put(key, val);
tx.commit();
}
if (cntr.incrementAndGet() % 100 == 0)
info("Stored cache object for key [key=" + key + ", idx=" + i + ']');
}
return null;
}
}, 10);
}
finally {
stopAllGrids();
}
}
/**
* @param plcMax Policy max.
* @return Policy.
*/
protected abstract T createPolicy(int plcMax);
/**
* @param nearMax Near max.
* @return Policy.
*/
protected abstract T createNearPolicy(int nearMax);
/**
* Performs after-test near policy check.
*
* @param nearMax Near max.
*/
protected abstract void checkNearPolicies(int nearMax);
/**
* Performs after-test policy check.
*
* @param plcMax Maximum allowed size of ploicy.
*/
protected abstract void checkPolicies(int plcMax);
/**
*
*/
@SuppressWarnings({"PublicConstructorInNonPublicClass"})
protected static class MockEntry extends GridCacheMockEntry<String, String> {
/** */
private IgniteCache<String, String> parent;
/** Entry value. */
private String val;
/** @param key Key. */
public MockEntry(String key) {
super(key);
}
/**
* @param key Key.
* @param val Value.
*/
public MockEntry(String key, String val) {
super(key);
this.val = val;
}
/**
* @param key Key.
* @param parent Parent.
*/
public MockEntry(String key, @Nullable IgniteCache<String, String> parent) {
super(key);
this.parent = parent;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public <T> T unwrap(Class<T> clazz) {
if (clazz.isAssignableFrom(IgniteCache.class))
return (T)parent;
return super.unwrap(clazz);
}
/** {@inheritDoc} */
@Override public String getValue() throws IllegalStateException {
return val;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(MockEntry.class, this, super.toString());
}
}
}
| |
/*******************************************************************************
* * Copyright 2013 Impetus Infotech.
* *
* * 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.impetus.client.es;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import junit.framework.Assert;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.impetus.client.es.PersonES.Day;
import com.impetus.kundera.PersistenceProperties;
/**
* The Class PersonESTest.
*
* @author vivek.mishra junit to demonstrate ESQuery implementation.
*/
public class PersonESTest
{
/** The emf. */
private EntityManagerFactory emf;
/** The em. */
private EntityManager em;
/** The node. */
private static Node node = null;
/** The person1. */
private PersonES person1, person2, person3, person4;
/**
* Sets the up before class.
*
* @throws Exception
* the exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
if (!checkIfServerRunning())
{
Builder builder = Settings.settingsBuilder();
builder.put("path.home", "target/data");
node = new NodeBuilder().settings(builder).node();
}
}
/**
* Check if server running.
*
* @return true, if successful
*/
private static boolean checkIfServerRunning()
{
try
{
Socket socket = new Socket("127.0.0.1", 9300);
return socket.getInetAddress() != null;
}
catch (UnknownHostException e)
{
return false;
}
catch (IOException e)
{
return false;
}
}
/**
* Setup.
*/
@Before
public void setup()
{
emf = Persistence.createEntityManagerFactory("es-pu");
em = emf.createEntityManager();
init();
}
/**
* Test with batch.
*
* @throws NoSuchFieldException
* the no such field exception
* @throws SecurityException
* the security exception
* @throws IllegalArgumentException
* the illegal argument exception
* @throws IllegalAccessException
* the illegal access exception
* @throws InterruptedException
* the interrupted exception
*/
@Test
public void testWithBatch() throws NoSuchFieldException, SecurityException, IllegalArgumentException,
IllegalAccessException, InterruptedException
{
Map<String, Object> props = new HashMap<String, Object>();
props.put(PersistenceProperties.KUNDERA_NODES, "localhost");
props.put(PersistenceProperties.KUNDERA_PORT, "9300");
props.put(PersistenceProperties.KUNDERA_BATCH_SIZE, 10);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("es-pu", props);
EntityManager em = emf.createEntityManager();
// purge();
PersonES person = new PersonES();
for (int i = 1; i <= 25; i++)
{
person.setAge(i);
person.setDay(Day.FRIDAY);
person.setPersonId(i + "");
person.setPersonName("vivek" + i);
em.persist(person);
if (i % 10 == 0)
{
em.clear();
for (int i1 = 1; i1 <= 10; i1++)
{
PersonES p = em.find(PersonES.class, i1 + "");
Assert.assertNotNull(p);
Assert.assertEquals("vivek" + i1, p.getPersonName());
}
}
}
em.flush();
em.clear();
em.close();
emf.close();
// A scenario to mix and match with
// 5 inserts, 5 updates and 5 deletes
props.put(PersistenceProperties.KUNDERA_BATCH_SIZE, 50);
emf = Persistence.createEntityManagerFactory("es-pu", props);
em = emf.createEntityManager();
for (int i = 21; i <= 25; i++)
{
person.setAge(i);
person.setDay(Day.FRIDAY);
person.setPersonId(i + "");
person.setPersonName("vivek" + i);
em.persist(person);
}
for (int i = 10; i <= 20; i++)
{
PersonES p = em.find(PersonES.class, i + "");
if (i > 15)
{
em.remove(p);
}
else
{
p.setPersonName("updatedName" + i);
em.merge(p);
}
}
em.flush(); // explicit flush
em.clear();
// Assert after explicit flush
for (int i = 10; i <= 15; i++)
{
if (i > 15)
{
Assert.assertNull(em.find(PersonES.class, i + "")); // assert on
// removed
}
else
{
PersonES found = em.find(PersonES.class, i + "");
Assert.assertNotNull(found);
Assert.assertEquals("updatedName" + i, found.getPersonName());
}
}
for (int i = 1; i <= 25; i++)
{
PersonES found = em.find(PersonES.class, i + "");
if (found != null) // as some of record are already removed.
em.remove(found);
}
// TODO: Update/delete by JPA query.
// String deleteQuery = "Delete p from PersonES p";
em.close();
emf.close();
}
/**
* Test specific field retrieval.
*
* @throws InterruptedException
* the interrupted exception
*/
@Test
public void testSpecificFieldRetrieval() throws InterruptedException
{
waitThread();
String queryWithOutAndClause = "Select p.personName,p.age from PersonES p where p.personName = 'karthik' OR p.personName = 'pragalbh' ORDER BY p.personName";
Query nameQuery = em.createNamedQuery(queryWithOutAndClause);
List persons = nameQuery.getResultList();
Assert.assertFalse(persons.isEmpty());
Assert.assertEquals(2, persons.size());
Assert.assertEquals("karthik", ((ArrayList) persons.get(0)).get(0));
Assert.assertEquals(10, ((ArrayList) persons.get(0)).get(1));
Assert.assertEquals("pragalbh", ((ArrayList) persons.get(1)).get(0));
Assert.assertEquals(20, ((ArrayList) persons.get(1)).get(1));
}
/**
* Test find jpql.
*
* @throws InterruptedException
* the interrupted exception
*/
@Test
public void testFindJPQL() throws InterruptedException
{
String queryWithId = "Select p from PersonES p where p.personId = 3";
Query nameQuery = em.createNamedQuery(queryWithId);
List<PersonES> persons = nameQuery.getResultList();
Assert.assertFalse(persons.isEmpty());
Assert.assertEquals(1, persons.size());
Assert.assertEquals("amit", persons.get(0).getPersonName());
Assert.assertEquals(30, persons.get(0).getAge().intValue());
String queryWithOutAndClause = "Select p from PersonES p where p.personName = 'karthik'";
nameQuery = em.createNamedQuery(queryWithOutAndClause);
persons = nameQuery.getResultList();
Assert.assertFalse(persons.isEmpty());
Assert.assertEquals(1, persons.size());
Assert.assertEquals("karthik", persons.get(0).getPersonName());
String queryWithOutClause = "Select p.personName, p.personId from PersonES p";
nameQuery = em.createNamedQuery(queryWithOutClause);
List personsNames = nameQuery.getResultList();
Assert.assertFalse(personsNames.isEmpty());
Assert.assertEquals(4, personsNames.size());
String invalidQueryWithAndClause = "Select p from PersonES p where p.personName = 'karthik' AND p.age = 34";
nameQuery = em.createNamedQuery(invalidQueryWithAndClause);
persons = nameQuery.getResultList();
Assert.assertTrue(persons.isEmpty());
String queryWithAndClause = "Select p from PersonES p where p.personName = 'karthik' AND p.age = 10";
nameQuery = em.createNamedQuery(queryWithAndClause);
persons = nameQuery.getResultList();
Assert.assertFalse(persons.isEmpty());
Assert.assertFalse(persons.isEmpty());
Assert.assertEquals(1, persons.size());
Assert.assertEquals("karthik", persons.get(0).getPersonName());
String queryWithORClause = "Select p from PersonES p where p.personName = 'karthik' OR p.personName = 'amit'";
nameQuery = em.createNamedQuery(queryWithORClause);
persons = nameQuery.getResultList();
Assert.assertFalse(persons.isEmpty());
Assert.assertEquals(2, persons.size());
String invalidQueryWithORClause = "Select p from PersonES p where p.personName = 'amit' OR p.personName = 'lkl'";
nameQuery = em.createNamedQuery(invalidQueryWithORClause);
persons = nameQuery.getResultList();
Assert.assertFalse(persons.isEmpty());
Assert.assertEquals(1, persons.size());
// TODO: >,<,>=,<=
String notConditionOnRowKey = "Select p from PersonES p where p.personId <> '1'";
nameQuery = em.createNamedQuery(notConditionOnRowKey);
persons = nameQuery.getResultList();
assertResultList(persons, person2, person3, person4);
String notConditionOnNonRowKey = "Select p from PersonES p where p.personName <> 'amit'";
nameQuery = em.createNamedQuery(notConditionOnNonRowKey);
persons = nameQuery.getResultList();
assertResultList(persons, person1, person2, person4);
String notConditionOnNonRowKeyWithAnd = "Select p from PersonES p where p.personName <> 'amit' and p.personId > 2";
nameQuery = em.createNamedQuery(notConditionOnNonRowKeyWithAnd);
persons = nameQuery.getResultList();
assertResultList(persons, person4);
String notConditionOnNonRowKeyWithOr = "Select p from PersonES p where p.personName <> 'amit' or p.personId <> 3";
nameQuery = em.createNamedQuery(notConditionOnNonRowKeyWithOr);
persons = nameQuery.getResultList();
assertResultList(persons, person1, person2, person4);
testCount();
testCountWithField();
testCountWithWhere();
testCountWithWhereAnd();
testCountWithWhereNullAnd();
testCountWithWhereOr();
testCountWithNot();
testCountWithIn();
testCountWithInString();
testInWithStringArray();
testInWithIntegerArray();
testInWithListPositionalParameter();
testInWithStringList();
testInWithIntegerList();
testInWithObjectList();
testInWithBlankList();
testInWithIntegerSet();
testInWithStringSet();
testInWithIntegerValues();
testInWithStringValues();
testInWithOrClause();
testInWithAndClause();
testFieldWithInClause();
testMinWithIn();
testInWithBlankValues();
}
/**
* Test not with delete.
*/
@Test
public void testNotWithDelete()
{
String queryString = "delete from PersonES p where p.personId <> 2";
Query query = em.createQuery(queryString);
int rowUpdataCount = query.executeUpdate();
waitThread();
Assert.assertEquals(3, rowUpdataCount);
List<PersonES> resultList = em.createQuery("Select p from PersonES p").getResultList();
Assert.assertEquals(1, resultList.size());
Assert.assertEquals("2", resultList.get(0).getPersonId());
}
/**
* Test not with update.
*/
@Test
public void testNotWithUpdate()
{
String notConditionUpdateQuery = "update PersonES p set p.age = 50 where p.personName <> 'amit'";
Query updateQuery = em.createQuery(notConditionUpdateQuery);
int updateCount = updateQuery.executeUpdate();
Assert.assertEquals(3, updateCount);
PersonES person = em.find(PersonES.class, "1");
Assert.assertEquals(50, person.getAge().intValue());
person = em.find(PersonES.class, "2");
Assert.assertEquals(50, person.getAge().intValue());
person = em.find(PersonES.class, "4");
Assert.assertEquals(50, person.getAge().intValue());
}
/**
* Test count.
*/
public void testCount()
{
String queryString = "Select count(p) from PersonES p";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(4, ((Long) resultList.get(0)).intValue());
}
/**
* Test count with field.
*/
public void testCountWithField()
{
String queryString = "Select count(p.age) from PersonES p";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(4, ((Long) resultList.get(0)).intValue());
}
/**
* Test count with where.
*/
public void testCountWithWhere()
{
String queryString = "Select count(p.age) from PersonES p where p.age > 25";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(2, ((Long) resultList.get(0)).intValue());
}
/**
* Test count with where and.
*/
public void testCountWithWhereAnd()
{
String queryString = "Select count(p.age) from PersonES p where p.age > 25 and p.personName = 'amit'";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(1, ((Long) resultList.get(0)).intValue());
}
/**
* Test count with where null and.
*/
public void testCountWithWhereNullAnd()
{
String queryString = "Select count(p.age) from PersonES p where p.age < 25 and p.personName = 'amit'";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(0, ((Long) resultList.get(0)).intValue());
}
/**
* Test count with where or.
*/
public void testCountWithWhereOr()
{
String queryString = "Select count(p) from PersonES p where p.age < 25 or p.personName = 'amit'";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(3, ((Long) resultList.get(0)).intValue());
}
/**
* Test count with not.
*/
public void testCountWithNot()
{
String queryString = "Select count(p.age) from PersonES p where p.personName <> 'amit'";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(3, ((Long) resultList.get(0)).intValue());
}
/**
* Test count with in.
*/
public void testCountWithIn()
{
String queryString = "Select count(p.age) from PersonES p where p.age In (20, 30)";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(2, ((Long) resultList.get(0)).intValue());
}
/**
* Test count with in string.
*/
public void testCountWithInString()
{
String queryString = "Select count(p.age) from PersonES p where p.personName IN ('amit', 'dev', 'lilkl')";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(2, ((Long) resultList.get(0)).intValue());
}
/**
* Test in with string array.
*/
public void testInWithStringArray()
{
String queryString = "Select p from PersonES p where p.personId IN :values";
Query query = em.createQuery(queryString);
String values[] = { "3", "4", "1" };
query.setParameter("values", values);
List resultList = query.getResultList();
assertResultList(resultList, person1, person3, person4);
}
/**
* Test in with integer array.
*/
public void testInWithIntegerArray()
{
String queryString = "Select p from PersonES p where p.age IN :values";
Query query = em.createQuery(queryString);
Integer values[] = { 10, 20, 50 };
query.setParameter("values", values);
List resultList = query.getResultList();
assertResultList(resultList, person1, person2);
}
/**
* Test in with list positional parameter.
*/
public void testInWithListPositionalParameter()
{
String queryString = "Select p from PersonES p where p.age IN ?1";
Query query = em.createQuery(queryString);
List<Integer> inputList = new ArrayList();
inputList.add(20);
inputList.add(30);
query.setParameter(1, inputList);
List<PersonES> resultList = query.getResultList();
assertResultList(resultList, person2, person3);
}
/**
* Test in with string list.
*/
public void testInWithStringList()
{
String queryString = "Select p from PersonES p where p.personId IN :list";
Query query = em.createQuery(queryString);
ArrayList<String> input = new ArrayList<String>();
input.add("2");
input.add("3");
query.setParameter("list", input);
List<PersonES> resultList = query.getResultList();
assertResultList(resultList, person2, person3);
}
/**
* Test in with integer list.
*/
public void testInWithIntegerList()
{
String queryString = "Select p from PersonES p where p.age IN :list";
Query query = em.createQuery(queryString);
ArrayList<Integer> input = new ArrayList<Integer>();
input.add(20);
input.add(40);
query.setParameter("list", input);
List<PersonES> resultList = query.getResultList();
assertResultList(resultList, person2, person4);
}
/**
* Test in with object list.
*/
public void testInWithObjectList()
{
String queryString = "Select p from PersonES p where p.personId IN :list";
Query query = em.createQuery(queryString);
List inputList = new ArrayList();
inputList.add("2");
inputList.add("3");
query.setParameter("list", inputList);
List<PersonES> resultList = query.getResultList();
assertResultList(resultList, person2, person3);
}
/**
* Test in with blank list.
*/
public void testInWithBlankList()
{
String queryString = "Select p from PersonES p where p.age IN :list";
Query query = em.createQuery(queryString);
ArrayList input = new ArrayList();
query.setParameter("list", input);
List<PersonES> resultList = query.getResultList();
assertResultList(resultList);
}
/**
* Test in with integer set.
*/
public void testInWithIntegerSet()
{
String queryString = "Select p from PersonES p where p.age IN :set";
Query query = em.createQuery(queryString);
Set<Integer> inputSet = new HashSet<Integer>();
inputSet.add(10);
inputSet.add(30);
query.setParameter("set", inputSet);
List<PersonES> resultList = query.getResultList();
assertResultList(resultList, person1, person3);
}
/**
* Test in with string set.
*/
public void testInWithStringSet()
{
String queryString = "Select p from PersonES p where p.personId IN :set";
Query query = em.createQuery(queryString);
Set<String> input = new HashSet<String>();
input.add("2");
input.add("3");
query.setParameter("set", input);
List<PersonES> resultList = query.getResultList();
assertResultList(resultList, person2, person3);
}
/**
* Test in with integer values.
*/
public void testInWithIntegerValues()
{
String queryString = "Select p from PersonES p where p.age IN ( 10, 20)";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
assertResultList(resultList, person1, person2);
}
/**
* Test in with string values.
*/
public void testInWithStringValues()
{
String queryString = "Select p from PersonES p where p.personId IN ( '2', '3','10')";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
assertResultList(resultList, person2, person3);
}
/**
* Test in with or clause.
*/
public void testInWithOrClause()
{
String queryString = "Select p from PersonES p where p.age IN ( 10, 20) or p.age = 40";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
assertResultList(resultList, person1, person2, person4);
}
/**
* Test in with and clause.
*/
public void testInWithAndClause()
{
String queryString = "Select p from PersonES p where p.age IN ( 10, 20) and p.personId = '2'";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
assertResultList(resultList, person2);
}
/**
* Test field with in clause.
*/
public void testFieldWithInClause()
{
String queryString = "Select p.personName from PersonES p where p.personId IN ( '1', '2') and p.age = 10";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals("karthik", resultList.get(0));
}
/**
* Test min with in.
*/
public void testMinWithIn()
{
String queryString = "Select sum(p.age) from PersonES p where p.personId IN ( '1', '2') or p.age = 40";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertNotNull(resultList);
Assert.assertEquals(1, resultList.size());
Assert.assertEquals(70.0, resultList.get(0));
}
/**
* Test in with blank values.
*/
public void testInWithBlankValues()
{
String queryString = "Select p from PersonES p where p.personId IN ( )";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
assertResultList(resultList);
}
/**
* Test in with delete.
*/
@Test
public void testInWithDelete()
{
String queryString = "delete from PersonES p where p.personId IN ( '2', '4' )";
Query query = em.createQuery(queryString);
int deleteCount = query.executeUpdate();
Assert.assertEquals(2, deleteCount);
waitThread();
queryString = "Select p from PersonES p";
query = em.createQuery(queryString);
List resultList = query.getResultList();
assertResultList(resultList, person1, person3);
}
/**
* Tear down after class.
*
* @throws Exception
* the exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
if (node != null)
node.close();
}
/**
* Tear down.
*/
@After
public void tearDown()
{
purge();
em.close();
emf.close();
}
/**
* Wait thread.
*/
private void waitThread()
{
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
/**
* Inits all the records.
*/
private void init()
{
person1 = createPerson("1", 10, "karthik");
person2 = createPerson("2", 20, "pragalbh");
person3 = createPerson("3", 30, "amit");
person4 = createPerson("4", 40, "dev");
waitThread();
}
/**
* Creates the person and persist them.
*
* @param id
* the id
* @param age
* the age
* @param name
* the name
* @return the person es
*/
private PersonES createPerson(String id, int age, String name)
{
PersonES person = new PersonES();
person.setAge(age);
person.setDay(Day.FRIDAY);
person.setPersonId(id);
person.setPersonName(name);
em.persist(person);
return person;
}
/**
* Delete all the records.
*/
private void purge()
{
String deleteQuery = "delete from PersonES p";
Query query = em.createQuery(deleteQuery);
query.executeUpdate();
waitThread();
}
/**
* Verify each person object of result list.
*
* @param resultPersonList
* the result person list
* @param persons
* the persons
*/
private void assertResultList(List<PersonES> resultPersonList, PersonES... persons)
{
boolean flag = false;
Assert.assertNotNull(resultPersonList);
Assert.assertEquals(persons.length, resultPersonList.size());
for (PersonES person : persons)
{
flag = false;
for (PersonES resultPerson : resultPersonList)
{
if (person.getPersonId().equals(resultPerson.getPersonId()))
{
matchPerson(resultPerson, person);
flag = true;
}
}
Assert.assertEquals("Person with id " + person.getPersonId() + " not found in Result list.", true, flag);
}
}
/**
* Match person to verify each field of both PersonES objects are same.
*
* @param resultPerson
* the result person
* @param person
* the person
*/
private void matchPerson(PersonES resultPerson, PersonES person)
{
Assert.assertNotNull(resultPerson);
Assert.assertEquals(person.getPersonId(), resultPerson.getPersonId());
Assert.assertEquals(person.getPersonName(), resultPerson.getPersonName());
Assert.assertEquals(person.getAge(), resultPerson.getAge());
Assert.assertEquals(person.getSalary(), resultPerson.getSalary());
}
}
| |
/*
* Copyright 2020 Google 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/webrisk/v1/webrisk.proto
package com.google.webrisk.v1;
/**
*
*
* <pre>
* A set of raw indices to remove from a local list.
* </pre>
*
* Protobuf type {@code google.cloud.webrisk.v1.RawIndices}
*/
public final class RawIndices extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.webrisk.v1.RawIndices)
RawIndicesOrBuilder {
private static final long serialVersionUID = 0L;
// Use RawIndices.newBuilder() to construct.
private RawIndices(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private RawIndices() {
indices_ = emptyIntList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new RawIndices();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private RawIndices(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8:
{
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
indices_ = newIntList();
mutable_bitField0_ |= 0x00000001;
}
indices_.addInt(input.readInt32());
break;
}
case 10:
{
int length = input.readRawVarint32();
int limit = input.pushLimit(length);
if (!((mutable_bitField0_ & 0x00000001) != 0) && input.getBytesUntilLimit() > 0) {
indices_ = newIntList();
mutable_bitField0_ |= 0x00000001;
}
while (input.getBytesUntilLimit() > 0) {
indices_.addInt(input.readInt32());
}
input.popLimit(limit);
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
indices_.makeImmutable(); // C
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.webrisk.v1.WebRiskProto
.internal_static_google_cloud_webrisk_v1_RawIndices_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.webrisk.v1.WebRiskProto
.internal_static_google_cloud_webrisk_v1_RawIndices_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.webrisk.v1.RawIndices.class, com.google.webrisk.v1.RawIndices.Builder.class);
}
public static final int INDICES_FIELD_NUMBER = 1;
private com.google.protobuf.Internal.IntList indices_;
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @return A list containing the indices.
*/
@java.lang.Override
public java.util.List<java.lang.Integer> getIndicesList() {
return indices_;
}
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @return The count of indices.
*/
public int getIndicesCount() {
return indices_.size();
}
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @param index The index of the element to return.
* @return The indices at the given index.
*/
public int getIndices(int index) {
return indices_.getInt(index);
}
private int indicesMemoizedSerializedSize = -1;
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
getSerializedSize();
if (getIndicesList().size() > 0) {
output.writeUInt32NoTag(10);
output.writeUInt32NoTag(indicesMemoizedSerializedSize);
}
for (int i = 0; i < indices_.size(); i++) {
output.writeInt32NoTag(indices_.getInt(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < indices_.size(); i++) {
dataSize += com.google.protobuf.CodedOutputStream.computeInt32SizeNoTag(indices_.getInt(i));
}
size += dataSize;
if (!getIndicesList().isEmpty()) {
size += 1;
size += com.google.protobuf.CodedOutputStream.computeInt32SizeNoTag(dataSize);
}
indicesMemoizedSerializedSize = dataSize;
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.webrisk.v1.RawIndices)) {
return super.equals(obj);
}
com.google.webrisk.v1.RawIndices other = (com.google.webrisk.v1.RawIndices) obj;
if (!getIndicesList().equals(other.getIndicesList())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getIndicesCount() > 0) {
hash = (37 * hash) + INDICES_FIELD_NUMBER;
hash = (53 * hash) + getIndicesList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.webrisk.v1.RawIndices parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.webrisk.v1.RawIndices parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.webrisk.v1.RawIndices parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.webrisk.v1.RawIndices parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.webrisk.v1.RawIndices parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.webrisk.v1.RawIndices parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.webrisk.v1.RawIndices parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.webrisk.v1.RawIndices parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.webrisk.v1.RawIndices parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.webrisk.v1.RawIndices parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.webrisk.v1.RawIndices parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.webrisk.v1.RawIndices parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.webrisk.v1.RawIndices prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A set of raw indices to remove from a local list.
* </pre>
*
* Protobuf type {@code google.cloud.webrisk.v1.RawIndices}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.webrisk.v1.RawIndices)
com.google.webrisk.v1.RawIndicesOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.webrisk.v1.WebRiskProto
.internal_static_google_cloud_webrisk_v1_RawIndices_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.webrisk.v1.WebRiskProto
.internal_static_google_cloud_webrisk_v1_RawIndices_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.webrisk.v1.RawIndices.class,
com.google.webrisk.v1.RawIndices.Builder.class);
}
// Construct using com.google.webrisk.v1.RawIndices.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
indices_ = emptyIntList();
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.webrisk.v1.WebRiskProto
.internal_static_google_cloud_webrisk_v1_RawIndices_descriptor;
}
@java.lang.Override
public com.google.webrisk.v1.RawIndices getDefaultInstanceForType() {
return com.google.webrisk.v1.RawIndices.getDefaultInstance();
}
@java.lang.Override
public com.google.webrisk.v1.RawIndices build() {
com.google.webrisk.v1.RawIndices result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.webrisk.v1.RawIndices buildPartial() {
com.google.webrisk.v1.RawIndices result = new com.google.webrisk.v1.RawIndices(this);
int from_bitField0_ = bitField0_;
if (((bitField0_ & 0x00000001) != 0)) {
indices_.makeImmutable();
bitField0_ = (bitField0_ & ~0x00000001);
}
result.indices_ = indices_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.webrisk.v1.RawIndices) {
return mergeFrom((com.google.webrisk.v1.RawIndices) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.webrisk.v1.RawIndices other) {
if (other == com.google.webrisk.v1.RawIndices.getDefaultInstance()) return this;
if (!other.indices_.isEmpty()) {
if (indices_.isEmpty()) {
indices_ = other.indices_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureIndicesIsMutable();
indices_.addAll(other.indices_);
}
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.webrisk.v1.RawIndices parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.webrisk.v1.RawIndices) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private com.google.protobuf.Internal.IntList indices_ = emptyIntList();
private void ensureIndicesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
indices_ = mutableCopy(indices_);
bitField0_ |= 0x00000001;
}
}
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @return A list containing the indices.
*/
public java.util.List<java.lang.Integer> getIndicesList() {
return ((bitField0_ & 0x00000001) != 0)
? java.util.Collections.unmodifiableList(indices_)
: indices_;
}
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @return The count of indices.
*/
public int getIndicesCount() {
return indices_.size();
}
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @param index The index of the element to return.
* @return The indices at the given index.
*/
public int getIndices(int index) {
return indices_.getInt(index);
}
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @param index The index to set the value at.
* @param value The indices to set.
* @return This builder for chaining.
*/
public Builder setIndices(int index, int value) {
ensureIndicesIsMutable();
indices_.setInt(index, value);
onChanged();
return this;
}
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @param value The indices to add.
* @return This builder for chaining.
*/
public Builder addIndices(int value) {
ensureIndicesIsMutable();
indices_.addInt(value);
onChanged();
return this;
}
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @param values The indices to add.
* @return This builder for chaining.
*/
public Builder addAllIndices(java.lang.Iterable<? extends java.lang.Integer> values) {
ensureIndicesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, indices_);
onChanged();
return this;
}
/**
*
*
* <pre>
* The indices to remove from a lexicographically-sorted local list.
* </pre>
*
* <code>repeated int32 indices = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearIndices() {
indices_ = emptyIntList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.webrisk.v1.RawIndices)
}
// @@protoc_insertion_point(class_scope:google.cloud.webrisk.v1.RawIndices)
private static final com.google.webrisk.v1.RawIndices DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.webrisk.v1.RawIndices();
}
public static com.google.webrisk.v1.RawIndices getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<RawIndices> PARSER =
new com.google.protobuf.AbstractParser<RawIndices>() {
@java.lang.Override
public RawIndices parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new RawIndices(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<RawIndices> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<RawIndices> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.webrisk.v1.RawIndices getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* 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.geode.redis.internal.netty;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import it.unimi.dsi.fastutil.bytes.ByteArrays;
import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet;
import org.apache.logging.log4j.Logger;
import org.apache.geode.annotations.VisibleForTesting;
import org.apache.geode.logging.internal.log4j.api.LogService;
import org.apache.geode.redis.internal.commands.Command;
import org.apache.geode.redis.internal.commands.executor.RedisResponse;
import org.apache.geode.redis.internal.pubsub.PubSub;
public class Client {
private static final Logger logger = LogService.getLogger();
private final Channel channel;
private final ByteBufAllocator byteBufAllocator;
private byte[] name;
/**
* The subscription sets do not need to be thread safe
* because they are only used by a single thread as it
* does pubsub operations for a particular Client.
*/
private final Set<byte[]> channelSubscriptions =
new ObjectOpenCustomHashSet<>(ByteArrays.HASH_STRATEGY);
private final Set<byte[]> patternSubscriptions =
new ObjectOpenCustomHashSet<>(ByteArrays.HASH_STRATEGY);
public Client(Channel remoteAddress, PubSub pubsub) {
channel = remoteAddress;
byteBufAllocator = channel.alloc();
channel.closeFuture().addListener(future -> pubsub.clientDisconnect(this));
}
public String getRemoteAddress() {
return channel.remoteAddress().toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Client client = (Client) o;
return Objects.equals(channel, client.channel);
}
@Override
public int hashCode() {
return Objects.hash(channel);
}
public String toString() {
return channel.toString();
}
public boolean hasSubscriptions() {
return !channelSubscriptions.isEmpty() || !patternSubscriptions.isEmpty();
}
public long getSubscriptionCount() {
return channelSubscriptions.size() + patternSubscriptions.size();
}
public void clearSubscriptions() {
channelSubscriptions.clear();
patternSubscriptions.clear();
}
public boolean addChannelSubscription(byte[] channel) {
return channelSubscriptions.add(channel);
}
public boolean addPatternSubscription(byte[] pattern) {
return patternSubscriptions.add(pattern);
}
public boolean removeChannelSubscription(byte[] channel) {
return channelSubscriptions.remove(channel);
}
public boolean removePatternSubscription(byte[] pattern) {
return patternSubscriptions.remove(pattern);
}
public List<byte[]> getChannelSubscriptions() {
if (channelSubscriptions.isEmpty()) {
return Collections.emptyList();
}
return new ArrayList<>(channelSubscriptions);
}
public List<byte[]> getPatternSubscriptions() {
if (patternSubscriptions.isEmpty()) {
return Collections.emptyList();
}
return new ArrayList<>(patternSubscriptions);
}
public ByteBuf getChannelWriteBuffer() {
return byteBufAllocator.ioBuffer();
}
public ChannelFuture writeBufferToChannel(ByteBuf buffer) {
if (!logger.isDebugEnabled()) {
return channel.writeAndFlush(buffer);
} else {
// snapshot buffer before netty reuses it
final byte[] bufferBytes = getBufferBytes(buffer);
return channel.writeAndFlush(buffer)
.addListener(
(ChannelFutureListener) f -> logResponse(bufferBytes, channel.remoteAddress(),
f.cause()));
}
}
@VisibleForTesting
byte[] getBufferBytes(ByteBuf buffer) {
int size = buffer.readableBytes();
byte[] result = new byte[size];
buffer.getBytes(0, result);
return result;
}
public ChannelFuture writeToChannel(RedisResponse response) {
if (!logger.isDebugEnabled() && !response.hasAfterWriteCallback()) {
return channel.writeAndFlush(response.encode(byteBufAllocator));
} else {
return channel.writeAndFlush(response.encode(byteBufAllocator))
.addListener((ChannelFutureListener) f -> {
response.afterWrite();
logResponse(response, channel.remoteAddress(), f.cause());
});
}
}
private void logResponse(RedisResponse response, Object extraMessage, Throwable cause) {
if (logger.isDebugEnabled() && response != null) {
ByteBuf buf = response.encode(new UnpooledByteBufAllocator(false));
if (cause == null) {
logger.debug("Redis command returned: {} - {}",
Command.getHexEncodedString(buf.array(), buf.readableBytes()), extraMessage);
} else {
logger.debug("Redis command FAILED to return: {} - {}",
Command.getHexEncodedString(buf.array(), buf.readableBytes()), extraMessage, cause);
}
}
}
private void logResponse(byte[] bytes, Object extraMessage, Throwable cause) {
if (logger.isDebugEnabled()) {
if (cause == null) {
logger.debug("Redis command returned: {} - {}",
Command.getHexEncodedString(bytes, bytes.length), extraMessage);
} else {
logger.debug("Redis command FAILED to return: {} - {}",
Command.getHexEncodedString(bytes, bytes.length), extraMessage, cause);
}
}
}
public void setName(byte[] name) {
if (name.length == 0) {
this.name = null;
} else {
this.name = name;
}
}
public byte[] getName() {
return name;
}
}
| |
package hk.microos.tools;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import hk.microos.data.Ellipse;
import hk.microos.data.Flags;
import hk.microos.data.MyImage;
public class IOTool {
private IOTool() {
}
public static boolean isTextFile(File f) {
// String type = null;
// try {
// type = Files.probeContentType(f.toPath());
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// if(type == null) return false;
// if(type.startsWith("text")) return true;
// return false;
return f.getAbsolutePath().endsWith(".txt");
}
public static ArrayList<String> readText(File f) {
Path filePath = f.toPath();
Charset charset = Charset.defaultCharset();
ArrayList<String> stringList;
try {
stringList = (ArrayList<String>) Files.readAllLines(filePath, charset);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return stringList;
}
public static HashMap<String, MyImage> filterImageList(ArrayList<String> list, JFrame dialogFatherFrame) {
HashMap<String, MyImage> map = new HashMap<>();
ArrayList<String> failed = new ArrayList<>();
int failedNum = 0;
for (String l : list) {
if (l.trim().equals("")) {
continue;
}
if (!new File(l).exists()) {
failedNum++;
if (failed.size() < 10) {
failed.add(l);
}
continue;
}
map.put(l, null);
}
if (map.size() == 0) {
JOptionPane.showMessageDialog(dialogFatherFrame,
"None of the images found from paths listed in the seletced file.\nPlease check your file and try again.",
"All failed", JOptionPane.WARNING_MESSAGE);
return map;
}
if (failed.size() != 0) {
String s = "";
if (failed.size() != failedNum) {
s = String.format("Existence checking failed paths(%d listed, %d in total):\n", failed.size(),
failedNum);
} else {
s = String.format("Existence checking failed paths(total: %d):\n", failed.size());
}
int i = 1;
for (String f : failed) {
s += String.format("%2d [%s]\n", i, f);
i++;
}
JOptionPane.showMessageDialog(dialogFatherFrame, s, "Existence checking failed paths",
JOptionPane.WARNING_MESSAGE);
}
return map;
}
private static void writeFile(File f, String content) {
FileWriter fw;
try {
if (!f.exists())
f.createNewFile();
fw = new FileWriter(f);
fw.write(content);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static HashMap<String, ArrayList<Ellipse>> readAnnotationFile(File f, String prefix, String suffix)
throws Exception {
HashMap<String, ArrayList<Ellipse>> map = new HashMap<>();
ArrayList<String> lines = readText(f);
if (Flags.GLOABAL_DEBUG) {
// prefix = "/Users/microos/Downloads/originalPics/";
// prefix = "/home/rick/Space/work/FDDB/data/images/";
prefix = "";
suffix = ".jpg";
}
System.out.println("prefix: "+prefix);
System.out.println("suffix: "+suffix);
// parse annotation files
int at = 0;
while (at < lines.size()) {
String path = prefix + lines.get(at) + suffix;
at++;
int detNum = 0;
try {
detNum = Integer.parseInt(lines.get(at));
} catch (Exception e) {
throw new Exception(String.format("At line %d, failed to parse \"%s\" as number of annotations.\n", at,
lines.get(at)));
}
at++;
ArrayList<Ellipse> elpses = null;
try {
elpses = readEllipse(lines, at, detNum);
} catch (Exception e) {
throw new Exception(e.getMessage());
}
at += detNum;
map.put(path, elpses);
}
return map;
}
private static ArrayList<Ellipse> readEllipse(ArrayList<String> lines, int start, int num) throws Exception {
ArrayList<Ellipse> elps = new ArrayList<>();
for (int i = 0; i < num; i++) {
int at = start + i;
String line = lines.get(at);
String[] splitStr = line.split(" +");
if (splitStr.length < 5) {
throw new Exception(String.format("At line %d: \"%s\"\ncontains less than 5 float values.\nExpected annotation format: major,minor,angle,x,y", at,line));
}
ArrayList<Double> splitFlt = new ArrayList<>();
for (String s : splitStr) {
splitFlt.add(Double.parseDouble(s));
}
elps.add(new Ellipse(splitFlt));
}
return elps;
}
public static void outputEllipse(HashMap<String, MyImage> pathImgPair, String outPath, boolean hasAnnotationLoaded,
JFrame dialogFatherFrame) {
outPath = !outPath.endsWith(".txt") ? outPath += ".txt" : outPath;
System.out.println("OP: " + outPath);
File f = new File(outPath);
if (f.exists()) {
int res = JOptionPane.showConfirmDialog(dialogFatherFrame,
String.format("File %s exists, do you want to overwrite it?", f.getAbsolutePath()), "File exists",
JOptionPane.YES_NO_OPTION);
if (res == JOptionPane.NO_OPTION || res == -1)
return;
}
boolean withBoth = false;
if (hasAnnotationLoaded) {
int res = JOptionPane.showOptionDialog(dialogFatherFrame,
"Do you want to concatenate loaded annotations and annotations marked by you into the output?\n"
+ "(Noted that a image without any annotation will not be included in the output file)",
"", JOptionPane.NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null,
new String[] { "both loaded and marked annotations", "only annotations marked by me" }, 0);
if(res == -1)
return;
if (res == 0)
withBoth = true;
if (res == 1)
withBoth = false;
}
int numImage = 0;
int numAnnot = 0;
StringBuffer sb = new StringBuffer();
for (String p : pathImgPair.keySet()) {
MyImage mim = UniversalTool.getMyImageFromPathImgPair(p, pathImgPair);
String s = mim.getOutputString(withBoth);
sb.append(s);
if (!s.equals("")) {
numImage++;
numAnnot += s.split("\n").length - 2;
}
}
writeFile(f, sb.toString());
JOptionPane.showMessageDialog(dialogFatherFrame, String.format(
"%d annotations from %d images \nhave been written to %s", numAnnot, numImage, f.getAbsolutePath()));
}
}
| |
/*
* 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.index;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.ShadowIndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.indices.recovery.RecoveryTarget;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.snapshots.SnapshotState;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.InternalTestCluster;
import org.elasticsearch.test.transport.MockTransportService;
import org.elasticsearch.transport.*;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.google.common.collect.Lists.newArrayList;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;
import static org.hamcrest.Matchers.*;
/**
* Tests for indices that use shadow replicas and a shared filesystem
*/
@ElasticsearchIntegrationTest.ClusterScope(scope = ElasticsearchIntegrationTest.Scope.TEST, numDataNodes = 0)
public class IndexWithShadowReplicasTests extends ElasticsearchIntegrationTest {
private Settings nodeSettings() {
return Settings.builder()
.put("node.add_id_to_custom_path", false)
.put("node.enable_custom_paths", true)
.put("index.store.fs.fs_lock", randomFrom("native", "simple"))
.build();
}
/**
* Tests the case where we create an index without shadow replicas, snapshot it and then restore into
* an index with shadow replicas enabled.
*/
public void testRestoreToShadow() throws ExecutionException, InterruptedException {
Settings nodeSettings = nodeSettings();
internalCluster().startNodesAsync(3, nodeSettings).get();
final Path dataPath = createTempDir();
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).build();
assertAcked(prepareCreate("foo").setSettings(idxSettings));
ensureGreen();
final int numDocs = randomIntBetween(10, 100);
for (int i = 0; i < numDocs; i++) {
client().prepareIndex("foo", "doc", ""+i).setSource("foo", "bar").get();
}
assertNoFailures(client().admin().indices().prepareFlush().setForce(true).setWaitIfOngoing(true).execute().actionGet());
assertAcked(client().admin().cluster().preparePutRepository("test-repo")
.setType("fs").setSettings(Settings.settingsBuilder()
.put("location", randomRepoPath())));
CreateSnapshotResponse createSnapshotResponse = client().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).setIndices("foo").get();
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
assertThat(client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
Settings shadowSettings = Settings.builder()
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 2).build();
logger.info("--> restore the index into shadow replica index");
RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap")
.setIndexSettings(shadowSettings).setWaitForCompletion(true)
.setRenamePattern("(.+)").setRenameReplacement("$1-copy")
.execute().actionGet();
assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0));
ensureGreen();
refresh();
for (IndicesService service : internalCluster().getDataNodeInstances(IndicesService.class)) {
if (service.hasIndex("foo-copy")) {
IndexShard shard = service.indexServiceSafe("foo-copy").shard(0);
if (shard.routingEntry().primary()) {
assertFalse(shard instanceof ShadowIndexShard);
} else {
assertTrue(shard instanceof ShadowIndexShard);
}
}
}
logger.info("--> performing query");
SearchResponse resp = client().prepareSearch("foo-copy").setQuery(matchAllQuery()).get();
assertHitCount(resp, numDocs);
}
@Test
public void testIndexWithFewDocuments() throws Exception {
Settings nodeSettings = nodeSettings();
internalCluster().startNodesAsync(3, nodeSettings).get();
final String IDX = "test";
final Path dataPath = createTempDir();
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 2)
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=string").get();
ensureGreen(IDX);
// So basically, the primary should fail and the replica will need to
// replay the translog, this is what this tests
client().prepareIndex(IDX, "doc", "1").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "bar").get();
// Check that we can get doc 1 and 2, because we are doing realtime
// gets and getting from the primary
GetResponse gResp1 = client().prepareGet(IDX, "doc", "1").setRealtime(true).setFields("foo").get();
GetResponse gResp2 = client().prepareGet(IDX, "doc", "2").setRealtime(true).setFields("foo").get();
assertThat(gResp1.getField("foo").getValue().toString(), equalTo("bar"));
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar"));
flushAndRefresh(IDX);
client().prepareIndex(IDX, "doc", "3").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "4").setSource("foo", "bar").get();
refresh();
// Check that we can get doc 1 and 2 without realtime
gResp1 = client().prepareGet(IDX, "doc", "1").setRealtime(false).setFields("foo").get();
gResp2 = client().prepareGet(IDX, "doc", "2").setRealtime(false).setFields("foo").get();
assertThat(gResp1.getField("foo").getValue().toString(), equalTo("bar"));
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar"));
logger.info("--> restarting all nodes");
if (randomBoolean()) {
logger.info("--> rolling restart");
internalCluster().rollingRestart();
} else {
logger.info("--> full restart");
internalCluster().fullRestart();
}
client().admin().cluster().prepareHealth().setWaitForNodes("3").get();
ensureGreen(IDX);
flushAndRefresh(IDX);
logger.info("--> performing query");
SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).get();
assertHitCount(resp, 4);
logger.info("--> deleting index");
assertAcked(client().admin().indices().prepareDelete(IDX));
}
@Test
public void testReplicaToPrimaryPromotion() throws Exception {
Settings nodeSettings = nodeSettings();
String node1 = internalCluster().startNode(nodeSettings);
Path dataPath = createTempDir();
String IDX = "test";
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=string").get();
ensureYellow(IDX);
client().prepareIndex(IDX, "doc", "1").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "bar").get();
GetResponse gResp1 = client().prepareGet(IDX, "doc", "1").setFields("foo").get();
GetResponse gResp2 = client().prepareGet(IDX, "doc", "2").setFields("foo").get();
assertTrue(gResp1.isExists());
assertTrue(gResp2.isExists());
assertThat(gResp1.getField("foo").getValue().toString(), equalTo("bar"));
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar"));
// Node1 has the primary, now node2 has the replica
String node2 = internalCluster().startNode(nodeSettings);
ensureGreen(IDX);
client().admin().cluster().prepareHealth().setWaitForNodes("2").get();
flushAndRefresh(IDX);
logger.info("--> stopping node1 [{}]", node1);
internalCluster().stopRandomNode(InternalTestCluster.nameFilter(node1));
ensureYellow(IDX);
logger.info("--> performing query");
SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).get();
assertHitCount(resp, 2);
gResp1 = client().prepareGet(IDX, "doc", "1").setFields("foo").get();
gResp2 = client().prepareGet(IDX, "doc", "2").setFields("foo").get();
assertTrue(gResp1.isExists());
assertTrue(gResp2.toString(), gResp2.isExists());
assertThat(gResp1.getField("foo").getValue().toString(), equalTo("bar"));
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar"));
client().prepareIndex(IDX, "doc", "1").setSource("foo", "foobar").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "foobar").get();
gResp1 = client().prepareGet(IDX, "doc", "1").setFields("foo").get();
gResp2 = client().prepareGet(IDX, "doc", "2").setFields("foo").get();
assertTrue(gResp1.isExists());
assertTrue(gResp2.toString(), gResp2.isExists());
assertThat(gResp1.getField("foo").getValue().toString(), equalTo("foobar"));
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("foobar"));
}
@Test
public void testPrimaryRelocation() throws Exception {
Settings nodeSettings = nodeSettings();
String node1 = internalCluster().startNode(nodeSettings);
Path dataPath = createTempDir();
String IDX = "test";
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=string").get();
ensureYellow(IDX);
client().prepareIndex(IDX, "doc", "1").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "bar").get();
GetResponse gResp1 = client().prepareGet(IDX, "doc", "1").setFields("foo").get();
GetResponse gResp2 = client().prepareGet(IDX, "doc", "2").setFields("foo").get();
assertTrue(gResp1.isExists());
assertTrue(gResp2.isExists());
assertThat(gResp1.getField("foo").getValue().toString(), equalTo("bar"));
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar"));
// Node1 has the primary, now node2 has the replica
String node2 = internalCluster().startNode(nodeSettings);
ensureGreen(IDX);
client().admin().cluster().prepareHealth().setWaitForNodes("2").get();
flushAndRefresh(IDX);
// now prevent primary from being allocated on node 1 move to node_3
String node3 = internalCluster().startNode(nodeSettings);
Settings build = Settings.builder().put("index.routing.allocation.exclude._name", node1).build();
client().admin().indices().prepareUpdateSettings(IDX).setSettings(build).execute().actionGet();
ensureGreen(IDX);
logger.info("--> performing query");
SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).get();
assertHitCount(resp, 2);
gResp1 = client().prepareGet(IDX, "doc", "1").setFields("foo").get();
gResp2 = client().prepareGet(IDX, "doc", "2").setFields("foo").get();
assertTrue(gResp1.isExists());
assertTrue(gResp2.toString(), gResp2.isExists());
assertThat(gResp1.getField("foo").getValue().toString(), equalTo("bar"));
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar"));
client().prepareIndex(IDX, "doc", "3").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "4").setSource("foo", "bar").get();
gResp1 = client().prepareGet(IDX, "doc", "3").setPreference("_primary").setFields("foo").get();
gResp2 = client().prepareGet(IDX, "doc", "4").setPreference("_primary").setFields("foo").get();
assertTrue(gResp1.isExists());
assertTrue(gResp2.isExists());
assertThat(gResp1.getField("foo").getValue().toString(), equalTo("bar"));
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar"));
}
@Test
public void testPrimaryRelocationWithConcurrentIndexing() throws Throwable {
Settings nodeSettings = nodeSettings();
String node1 = internalCluster().startNode(nodeSettings);
Path dataPath = createTempDir();
final String IDX = "test";
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=string").get();
ensureYellow(IDX);
// Node1 has the primary, now node2 has the replica
String node2 = internalCluster().startNode(nodeSettings);
ensureGreen(IDX);
flushAndRefresh(IDX);
String node3 = internalCluster().startNode(nodeSettings);
final AtomicInteger counter = new AtomicInteger(0);
final CountDownLatch started = new CountDownLatch(1);
final int numPhase1Docs = scaledRandomIntBetween(25, 200);
final int numPhase2Docs = scaledRandomIntBetween(25, 200);
final CountDownLatch phase1finished = new CountDownLatch(1);
final CountDownLatch phase2finished = new CountDownLatch(1);
final CopyOnWriteArrayList<Throwable> exceptions = new CopyOnWriteArrayList<>();
Thread thread = new Thread() {
@Override
public void run() {
started.countDown();
while (counter.get() < (numPhase1Docs + numPhase2Docs)) {
try {
final IndexResponse indexResponse = client().prepareIndex(IDX, "doc",
Integer.toString(counter.incrementAndGet())).setSource("foo", "bar").get();
assertTrue(indexResponse.isCreated());
} catch (Throwable t) {
exceptions.add(t);
}
final int docCount = counter.get();
if (docCount == numPhase1Docs) {
phase1finished.countDown();
}
}
logger.info("--> stopping indexing thread");
phase2finished.countDown();
}
};
thread.start();
started.await();
phase1finished.await(); // wait for a certain number of documents to be indexed
logger.info("--> excluding {} from allocation", node1);
// now prevent primary from being allocated on node 1 move to node_3
Settings build = Settings.builder().put("index.routing.allocation.exclude._name", node1).build();
client().admin().indices().prepareUpdateSettings(IDX).setSettings(build).execute().actionGet();
// wait for more documents to be indexed post-recovery, also waits for
// indexing thread to stop
phase2finished.await();
ExceptionsHelper.rethrowAndSuppress(exceptions);
ensureGreen(IDX);
thread.join();
logger.info("--> performing query");
flushAndRefresh();
SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).get();
assertHitCount(resp, counter.get());
assertHitCount(resp, numPhase1Docs + numPhase2Docs);
}
@Test
public void testPrimaryRelocationWhereRecoveryFails() throws Exception {
Settings nodeSettings = Settings.builder()
.put("node.add_id_to_custom_path", false)
.put("node.enable_custom_paths", true)
.put(TransportModule.TRANSPORT_SERVICE_TYPE_KEY, MockTransportService.class.getName())
.build();
String node1 = internalCluster().startNode(nodeSettings);
Path dataPath = createTempDir();
final String IDX = "test";
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=string").get();
ensureYellow(IDX);
// Node1 has the primary, now node2 has the replica
String node2 = internalCluster().startNode(nodeSettings);
ensureGreen(IDX);
flushAndRefresh(IDX);
String node3 = internalCluster().startNode(nodeSettings);
final AtomicInteger counter = new AtomicInteger(0);
final CountDownLatch started = new CountDownLatch(1);
final int numPhase1Docs = scaledRandomIntBetween(25, 200);
final int numPhase2Docs = scaledRandomIntBetween(25, 200);
final int numPhase3Docs = scaledRandomIntBetween(25, 200);
final CountDownLatch phase1finished = new CountDownLatch(1);
final CountDownLatch phase2finished = new CountDownLatch(1);
final CountDownLatch phase3finished = new CountDownLatch(1);
final AtomicBoolean keepFailing = new AtomicBoolean(true);
MockTransportService mockTransportService = ((MockTransportService) internalCluster().getInstance(TransportService.class, node1));
mockTransportService.addDelegate(internalCluster().getInstance(Discovery.class, node3).localNode(),
new MockTransportService.DelegateTransport(mockTransportService.original()) {
@Override
public void sendRequest(DiscoveryNode node, long requestId, String action,
TransportRequest request, TransportRequestOptions options)
throws IOException, TransportException {
if (keepFailing.get() && action.equals(RecoveryTarget.Actions.TRANSLOG_OPS)) {
logger.info("--> failing translog ops");
throw new ElasticsearchException("failing on purpose");
}
super.sendRequest(node, requestId, action, request, options);
}
});
Thread thread = new Thread() {
@Override
public void run() {
started.countDown();
while (counter.get() < (numPhase1Docs + numPhase2Docs + numPhase3Docs)) {
final IndexResponse indexResponse = client().prepareIndex(IDX, "doc",
Integer.toString(counter.incrementAndGet())).setSource("foo", "bar").get();
assertTrue(indexResponse.isCreated());
final int docCount = counter.get();
if (docCount == numPhase1Docs) {
phase1finished.countDown();
} else if (docCount == (numPhase1Docs + numPhase2Docs)) {
phase2finished.countDown();
}
}
logger.info("--> stopping indexing thread");
phase3finished.countDown();
}
};
thread.start();
started.await();
phase1finished.await(); // wait for a certain number of documents to be indexed
logger.info("--> excluding {} from allocation", node1);
// now prevent primary from being allocated on node 1 move to node_3
Settings build = Settings.builder().put("index.routing.allocation.exclude._name", node1).build();
client().admin().indices().prepareUpdateSettings(IDX).setSettings(build).execute().actionGet();
// wait for more documents to be indexed post-recovery, also waits for
// indexing thread to stop
phase2finished.await();
// stop failing
keepFailing.set(false);
// wait for more docs to be indexed
phase3finished.await();
ensureGreen(IDX);
thread.join();
logger.info("--> performing query");
flushAndRefresh();
SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).get();
assertHitCount(resp, counter.get());
}
@Test
public void testIndexWithShadowReplicasCleansUp() throws Exception {
Settings nodeSettings = nodeSettings();
int nodeCount = randomIntBetween(2, 5);
internalCluster().startNodesAsync(nodeCount, nodeSettings).get();
Path dataPath = createTempDir();
String IDX = "test";
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, randomIntBetween(1, nodeCount - 1))
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=string").get();
ensureGreen(IDX);
client().prepareIndex(IDX, "doc", "1").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "bar").get();
flushAndRefresh(IDX);
GetResponse gResp1 = client().prepareGet(IDX, "doc", "1").setFields("foo").get();
GetResponse gResp2 = client().prepareGet(IDX, "doc", "2").setFields("foo").get();
assertThat(gResp1.getField("foo").getValue().toString(), equalTo("bar"));
assertThat(gResp2.getField("foo").getValue().toString(), equalTo("bar"));
logger.info("--> performing query");
SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).get();
assertHitCount(resp, 2);
assertAcked(client().admin().indices().prepareDelete(IDX));
assertPathHasBeenCleared(dataPath);
}
/**
* Tests that shadow replicas can be "naturally" rebalanced and relocated
* around the cluster. By "naturally" I mean without using the reroute API
* @throws Exception
*/
@Test
public void testShadowReplicaNaturalRelocation() throws Exception {
Settings nodeSettings = nodeSettings();
internalCluster().startNodesAsync(2, nodeSettings).get();
Path dataPath = createTempDir();
String IDX = "test";
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 5)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=string").get();
ensureGreen(IDX);
int docCount = randomIntBetween(10, 100);
List<IndexRequestBuilder> builders = newArrayList();
for (int i = 0; i < docCount; i++) {
builders.add(client().prepareIndex(IDX, "doc", i + "").setSource("foo", "bar"));
}
indexRandom(true, true, true, builders);
flushAndRefresh(IDX);
// start a third node, with 5 shards each on the other nodes, they
// should relocate some to the third node
final String node3 = internalCluster().startNode(nodeSettings);
assertBusy(new Runnable() {
@Override
public void run() {
client().admin().cluster().prepareHealth().setWaitForNodes("3").get();
ClusterStateResponse resp = client().admin().cluster().prepareState().get();
RoutingNodes nodes = resp.getState().getRoutingNodes();
for (RoutingNode node : nodes) {
logger.info("--> node has {} shards (needs at least 2)", node.numberOfOwningShards());
assertThat("at least 2 shards on node", node.numberOfOwningShards(), greaterThanOrEqualTo(2));
}
}
});
ensureYellow(IDX);
logger.info("--> performing query");
SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).get();
assertHitCount(resp, docCount);
assertAcked(client().admin().indices().prepareDelete(IDX));
assertPathHasBeenCleared(dataPath);
}
@Test
public void testShadowReplicasUsingFieldData() throws Exception {
Settings nodeSettings = nodeSettings();
internalCluster().startNodesAsync(3, nodeSettings).get();
Path dataPath = createTempDir();
String IDX = "test";
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 2)
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHADOW_REPLICAS, true)
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.build();
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=string,index=not_analyzed").get();
ensureGreen(IDX);
client().prepareIndex(IDX, "doc", "1").setSource("foo", "foo").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "3").setSource("foo", "baz").get();
client().prepareIndex(IDX, "doc", "4").setSource("foo", "eggplant").get();
flushAndRefresh(IDX);
SearchResponse resp = client().prepareSearch(IDX).setQuery(matchAllQuery()).addFieldDataField("foo").addSort("foo", SortOrder.ASC).get();
assertHitCount(resp, 4);
assertOrderedSearchHits(resp, "2", "3", "4", "1");
SearchHit[] hits = resp.getHits().hits();
assertThat(hits[0].field("foo").getValue().toString(), equalTo("bar"));
assertThat(hits[1].field("foo").getValue().toString(), equalTo("baz"));
assertThat(hits[2].field("foo").getValue().toString(), equalTo("eggplant"));
assertThat(hits[3].field("foo").getValue().toString(), equalTo("foo"));
}
/** wait until none of the nodes have shards allocated on them */
private void assertNoShardsOn(final List<String> nodeList) throws Exception {
assertBusy(new Runnable() {
@Override
public void run() {
ClusterStateResponse resp = client().admin().cluster().prepareState().get();
RoutingNodes nodes = resp.getState().getRoutingNodes();
for (RoutingNode node : nodes) {
logger.info("--> node {} has {} shards", node.node().getName(), node.numberOfOwningShards());
if (nodeList.contains(node.node().getName())) {
assertThat("no shards on node", node.numberOfOwningShards(), equalTo(0));
}
}
}
});
}
/** wait until the node has the specified number of shards allocated on it */
private void assertShardCountOn(final String nodeName, final int shardCount) throws Exception {
assertBusy(new Runnable() {
@Override
public void run() {
ClusterStateResponse resp = client().admin().cluster().prepareState().get();
RoutingNodes nodes = resp.getState().getRoutingNodes();
for (RoutingNode node : nodes) {
logger.info("--> node {} has {} shards", node.node().getName(), node.numberOfOwningShards());
if (nodeName.equals(node.node().getName())) {
assertThat(node.numberOfOwningShards(), equalTo(shardCount));
}
}
}
});
}
@Test
public void testIndexOnSharedFSRecoversToAnyNode() throws Exception {
Settings nodeSettings = nodeSettings();
Settings fooSettings = Settings.builder().put(nodeSettings).put("node.affinity", "foo").build();
Settings barSettings = Settings.builder().put(nodeSettings).put("node.affinity", "bar").build();
final Future<List<String>> fooNodes = internalCluster().startNodesAsync(2, fooSettings);
final Future<List<String>> barNodes = internalCluster().startNodesAsync(2, barSettings);
fooNodes.get();
barNodes.get();
Path dataPath = createTempDir();
String IDX = "test";
Settings includeFoo = Settings.builder()
.put("index.routing.allocation.include.affinity", "foo")
.build();
Settings includeBar = Settings.builder()
.put("index.routing.allocation.include.affinity", "bar")
.build();
Settings idxSettings = Settings.builder()
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 5)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
.put(IndexMetaData.SETTING_DATA_PATH, dataPath.toAbsolutePath().toString())
.put(IndexMetaData.SETTING_SHARED_FILESYSTEM, true)
.put(IndexMetaData.SETTING_SHARED_FS_ALLOW_RECOVERY_ON_ANY_NODE, true)
.put(includeFoo) // start with requiring the shards on "foo"
.build();
// only one node, so all primaries will end up on node1
prepareCreate(IDX).setSettings(idxSettings).addMapping("doc", "foo", "type=string,index=not_analyzed").get();
ensureGreen(IDX);
// Index some documents
client().prepareIndex(IDX, "doc", "1").setSource("foo", "foo").get();
client().prepareIndex(IDX, "doc", "2").setSource("foo", "bar").get();
client().prepareIndex(IDX, "doc", "3").setSource("foo", "baz").get();
client().prepareIndex(IDX, "doc", "4").setSource("foo", "eggplant").get();
flushAndRefresh(IDX);
// put shards on "bar"
client().admin().indices().prepareUpdateSettings(IDX).setSettings(includeBar).get();
// wait for the shards to move from "foo" nodes to "bar" nodes
assertNoShardsOn(fooNodes.get());
// put shards back on "foo"
client().admin().indices().prepareUpdateSettings(IDX).setSettings(includeFoo).get();
// wait for the shards to move from "bar" nodes to "foo" nodes
assertNoShardsOn(barNodes.get());
// Stop a foo node
logger.info("--> stopping first 'foo' node");
internalCluster().stopRandomNode(InternalTestCluster.nameFilter(fooNodes.get().get(0)));
// Ensure that the other foo node has all the shards now
assertShardCountOn(fooNodes.get().get(1), 5);
// Assert no shards on the "bar" nodes
assertNoShardsOn(barNodes.get());
// Stop the second "foo" node
logger.info("--> stopping second 'foo' node");
internalCluster().stopRandomNode(InternalTestCluster.nameFilter(fooNodes.get().get(1)));
// The index should still be able to be allocated (on the "bar" nodes),
// all the "foo" nodes are gone
ensureGreen(IDX);
// Start another "foo" node and make sure the index moves back
logger.info("--> starting additional 'foo' node");
String newFooNode = internalCluster().startNode(fooSettings);
assertShardCountOn(newFooNode, 5);
assertNoShardsOn(barNodes.get());
}
}
| |
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.File;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import jdk.testlibrary.ProcessTools;
/**
* @test
* @bug 6434402 8004926
* @library /lib/testlibrary
* @build jdk.testlibrary.ProcessTools
* @build TestManager TestApplication CustomLauncherTest
* @run main/othervm CustomLauncherTest
* @author Jaroslav Bachorik
*/
public class CustomLauncherTest {
private static final String TEST_CLASSPATH = System.getProperty("test.class.path");
private static final String TEST_JDK = System.getProperty("test.jdk");
private static final String TEST_SRC = System.getProperty("test.src");
private static final String OSNAME = System.getProperty("os.name");
private static final String ARCH;
private static final String LIBARCH;
static {
// magic with os.arch
String osarch = System.getProperty("os.arch");
switch (osarch) {
case "i386":
case "i486":
case "i586":
case "i686":
case "i786":
case "i886":
case "i986": {
ARCH = "i586";
break;
}
case "x86_64":
case "amd64": {
ARCH = "amd64";
break;
}
case "sparc":
ARCH = "sparcv9";
break;
default: {
ARCH = osarch;
}
}
LIBARCH = ARCH.equals("i586") ? "i386" : ARCH;
}
public static void main(String[] args) throws Exception {
if (TEST_CLASSPATH == null || TEST_CLASSPATH.isEmpty()) {
System.out.println("Test is designed to be run from jtreg only");
return;
}
String PLATFORM = "";
switch (OSNAME.toLowerCase()) {
case "linux": {
PLATFORM = "linux";
break;
}
case "sunos": {
PLATFORM = "solaris";
break;
}
default: {
System.out.println("Test not designed to run on this operating " +
"system (" + OSNAME + "), skipping...");
return;
}
}
String LAUNCHER = TEST_SRC + File.separator + PLATFORM + "-" + ARCH +
File.separator + "launcher";
final FileSystem FS = FileSystems.getDefault();
Path launcherPath = FS.getPath(LAUNCHER);
final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&&
Files.isReadable(launcherPath);
if (!hasLauncher) {
System.out.println("Launcher [" + LAUNCHER + "] does not exist. Skipping the test.");
return;
}
Path libjvmPath = findLibjvm(FS);
if (libjvmPath == null) {
throw new Error("Unable to locate 'libjvm.so' in " + TEST_JDK);
}
Process serverPrc = null, clientPrc = null;
final Set<PosixFilePermission> launcherOrigPerms =
Files.getPosixFilePermissions(launcherPath, LinkOption.NOFOLLOW_LINKS);
try {
// It is impossible to store an executable file in the source control
// We need to set the executable flag here
if (!Files.isExecutable(launcherPath)) {
Set<PosixFilePermission> perms = new HashSet<>(launcherOrigPerms);
perms.add(PosixFilePermission.OWNER_EXECUTE);
Files.setPosixFilePermissions(launcherPath, perms);
}
System.out.println("Starting custom launcher:");
System.out.println("=========================");
System.out.println(" launcher : " + LAUNCHER);
System.out.println(" libjvm : " + libjvmPath.toString());
System.out.println(" classpath : " + TEST_CLASSPATH);
ProcessBuilder server = new ProcessBuilder(LAUNCHER, libjvmPath.toString(), TEST_CLASSPATH, "TestApplication");
final AtomicReference<String> port = new AtomicReference<>();
final AtomicReference<String> pid = new AtomicReference<>();
serverPrc = ProcessTools.startProcess(
"Launcher",
server,
(String line) -> {
if (line.startsWith("port:")) {
port.set(line.split("\\:")[1]);
} else if (line.startsWith("pid:")) {
pid.set(line.split("\\:")[1]);
} else if (line.startsWith("waiting")) {
return true;
}
return false;
},
5,
TimeUnit.SECONDS
);
System.out.println("Attaching test manager:");
System.out.println("=========================");
System.out.println(" PID : " + pid.get());
System.out.println(" shutdown port : " + port.get());
ProcessBuilder client = ProcessTools.createJavaProcessBuilder(
"-cp",
TEST_CLASSPATH +
File.pathSeparator +
TEST_JDK +
File.separator +
"lib" +
File.separator +
"tools.jar",
"TestManager",
pid.get(),
port.get(),
"true"
);
clientPrc = ProcessTools.startProcess(
"TestManager",
client,
(String line) -> line.startsWith("Starting TestManager for PID"),
10,
TimeUnit.SECONDS
);
int clientExitCode = clientPrc.waitFor();
int serverExitCode = serverPrc.waitFor();
if (clientExitCode != 0 || serverExitCode != 0) {
throw new Error("Test failed");
}
} finally {
// Let's restore the original launcher permissions
Files.setPosixFilePermissions(launcherPath, launcherOrigPerms);
if (clientPrc != null) {
clientPrc.destroy();
clientPrc.waitFor();
}
if (serverPrc != null) {
serverPrc.destroy();
serverPrc.waitFor();
}
}
}
private static Path findLibjvm(FileSystem FS) {
Path libjvmPath = findLibjvm(FS.getPath(TEST_JDK, "jre", "lib", LIBARCH));
if (libjvmPath == null) {
libjvmPath = findLibjvm(FS.getPath(TEST_JDK, "lib", LIBARCH));
}
return libjvmPath;
}
private static Path findLibjvm(Path libPath) {
// ARCH/libjvm.so -> ARCH/server/libjvm.so -> ARCH/client/libjvm.so
Path libjvmPath = libPath.resolve("libjvm.so");
if (isFileOk(libjvmPath)) {
return libjvmPath;
}
libjvmPath = libPath.resolve("server/libjvm.so");
if (isFileOk(libjvmPath)) {
return libjvmPath;
}
libjvmPath = libPath.resolve("client/libjvm.so");
if (isFileOk(libPath)) {
return libjvmPath;
}
return null;
}
private static boolean isFileOk(Path path) {
return Files.isRegularFile(path) && Files.isReadable(path);
}
}
| |
/*
* Copyright 2014, gRPC 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 io.grpc.netty;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.grpc.internal.GrpcUtil.SERVER_KEEPALIVE_TIME_NANOS_DISABLED;
import static io.grpc.netty.NettyServerBuilder.MAX_CONNECTION_AGE_NANOS_DISABLED;
import static io.grpc.netty.NettyServerBuilder.MAX_CONNECTION_IDLE_NANOS_DISABLED;
import static io.grpc.netty.Utils.CONTENT_TYPE_HEADER;
import static io.grpc.netty.Utils.HTTP_METHOD;
import static io.grpc.netty.Utils.TE_HEADER;
import static io.grpc.netty.Utils.TE_TRAILERS;
import static io.netty.buffer.Unpooled.directBuffer;
import static io.netty.buffer.Unpooled.unreleasableBuffer;
import static io.netty.handler.codec.http2.DefaultHttp2LocalFlowController.DEFAULT_WINDOW_UPDATE_RATIO;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import io.grpc.Attributes;
import io.grpc.InternalMetadata;
import io.grpc.InternalStatus;
import io.grpc.Metadata;
import io.grpc.ServerStreamTracer;
import io.grpc.Status;
import io.grpc.internal.GrpcUtil;
import io.grpc.internal.KeepAliveManager;
import io.grpc.internal.LogExceptionRunnable;
import io.grpc.internal.ServerTransportListener;
import io.grpc.internal.StatsTraceContext;
import io.grpc.internal.TransportTracer;
import io.grpc.netty.GrpcHttp2HeadersUtils.GrpcHttp2ServerHeadersDecoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http2.DecoratingHttp2FrameWriter;
import io.netty.handler.codec.http2.DefaultHttp2Connection;
import io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder;
import io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder;
import io.netty.handler.codec.http2.DefaultHttp2FrameReader;
import io.netty.handler.codec.http2.DefaultHttp2FrameWriter;
import io.netty.handler.codec.http2.DefaultHttp2Headers;
import io.netty.handler.codec.http2.DefaultHttp2LocalFlowController;
import io.netty.handler.codec.http2.DefaultHttp2RemoteFlowController;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2ConnectionAdapter;
import io.netty.handler.codec.http2.Http2ConnectionDecoder;
import io.netty.handler.codec.http2.Http2ConnectionEncoder;
import io.netty.handler.codec.http2.Http2Error;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2Exception.StreamException;
import io.netty.handler.codec.http2.Http2FlowController;
import io.netty.handler.codec.http2.Http2FrameAdapter;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2FrameReader;
import io.netty.handler.codec.http2.Http2FrameWriter;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2HeadersDecoder;
import io.netty.handler.codec.http2.Http2InboundFrameLogger;
import io.netty.handler.codec.http2.Http2OutboundFrameLogger;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2Stream;
import io.netty.handler.codec.http2.Http2StreamVisitor;
import io.netty.handler.codec.http2.WeightedFairQueueByteDistributor;
import io.netty.handler.logging.LogLevel;
import io.netty.util.AsciiString;
import io.netty.util.ReferenceCountUtil;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
/**
* Server-side Netty handler for GRPC processing. All event handlers are executed entirely within
* the context of the Netty Channel thread.
*/
class NettyServerHandler extends AbstractNettyHandler {
private static final Logger logger = Logger.getLogger(NettyServerHandler.class.getName());
private static final ByteBuf KEEPALIVE_PING_BUF =
unreleasableBuffer(directBuffer(8).writeLong(0xDEADL));
private final Http2Connection.PropertyKey streamKey;
private final ServerTransportListener transportListener;
private final int maxMessageSize;
private final long keepAliveTimeInNanos;
private final long keepAliveTimeoutInNanos;
private final long maxConnectionAgeInNanos;
private final long maxConnectionAgeGraceInNanos;
private final List<ServerStreamTracer.Factory> streamTracerFactories;
private final TransportTracer transportTracer;
private final KeepAliveEnforcer keepAliveEnforcer;
/** Incomplete attributes produced by negotiator. */
private Attributes negotiationAttributes;
/** Completed attributes produced by transportReady. */
private Attributes attributes;
private Throwable connectionError;
private boolean teWarningLogged;
private WriteQueue serverWriteQueue;
private AsciiString lastKnownAuthority;
@CheckForNull
private KeepAliveManager keepAliveManager;
@CheckForNull
private MaxConnectionIdleManager maxConnectionIdleManager;
@CheckForNull
private ScheduledFuture<?> maxConnectionAgeMonitor;
static NettyServerHandler newHandler(
ServerTransportListener transportListener,
ChannelPromise channelUnused,
List<ServerStreamTracer.Factory> streamTracerFactories,
TransportTracer transportTracer,
int maxStreams,
int flowControlWindow,
int maxHeaderListSize,
int maxMessageSize,
long keepAliveTimeInNanos,
long keepAliveTimeoutInNanos,
long maxConnectionIdleInNanos,
long maxConnectionAgeInNanos,
long maxConnectionAgeGraceInNanos,
boolean permitKeepAliveWithoutCalls,
long permitKeepAliveTimeInNanos) {
Preconditions.checkArgument(maxHeaderListSize > 0, "maxHeaderListSize must be positive");
Http2FrameLogger frameLogger = new Http2FrameLogger(LogLevel.DEBUG, NettyServerHandler.class);
Http2HeadersDecoder headersDecoder = new GrpcHttp2ServerHeadersDecoder(maxHeaderListSize);
Http2FrameReader frameReader = new Http2InboundFrameLogger(
new DefaultHttp2FrameReader(headersDecoder), frameLogger);
Http2FrameWriter frameWriter =
new Http2OutboundFrameLogger(new DefaultHttp2FrameWriter(), frameLogger);
return newHandler(
channelUnused,
frameReader,
frameWriter,
transportListener,
streamTracerFactories,
transportTracer,
maxStreams,
flowControlWindow,
maxHeaderListSize,
maxMessageSize,
keepAliveTimeInNanos,
keepAliveTimeoutInNanos,
maxConnectionIdleInNanos,
maxConnectionAgeInNanos,
maxConnectionAgeGraceInNanos,
permitKeepAliveWithoutCalls,
permitKeepAliveTimeInNanos);
}
@VisibleForTesting
static NettyServerHandler newHandler(
ChannelPromise channelUnused,
Http2FrameReader frameReader,
Http2FrameWriter frameWriter,
ServerTransportListener transportListener,
List<ServerStreamTracer.Factory> streamTracerFactories,
TransportTracer transportTracer,
int maxStreams,
int flowControlWindow,
int maxHeaderListSize,
int maxMessageSize,
long keepAliveTimeInNanos,
long keepAliveTimeoutInNanos,
long maxConnectionIdleInNanos,
long maxConnectionAgeInNanos,
long maxConnectionAgeGraceInNanos,
boolean permitKeepAliveWithoutCalls,
long permitKeepAliveTimeInNanos) {
Preconditions.checkArgument(maxStreams > 0, "maxStreams must be positive");
Preconditions.checkArgument(flowControlWindow > 0, "flowControlWindow must be positive");
Preconditions.checkArgument(maxHeaderListSize > 0, "maxHeaderListSize must be positive");
Preconditions.checkArgument(maxMessageSize > 0, "maxMessageSize must be positive");
final Http2Connection connection = new DefaultHttp2Connection(true);
WeightedFairQueueByteDistributor dist = new WeightedFairQueueByteDistributor(connection);
dist.allocationQuantum(16 * 1024); // Make benchmarks fast again.
DefaultHttp2RemoteFlowController controller =
new DefaultHttp2RemoteFlowController(connection, dist);
connection.remote().flowController(controller);
final KeepAliveEnforcer keepAliveEnforcer = new KeepAliveEnforcer(
permitKeepAliveWithoutCalls, permitKeepAliveTimeInNanos, TimeUnit.NANOSECONDS);
// Create the local flow controller configured to auto-refill the connection window.
connection.local().flowController(
new DefaultHttp2LocalFlowController(connection, DEFAULT_WINDOW_UPDATE_RATIO, true));
frameWriter = new WriteMonitoringFrameWriter(frameWriter, keepAliveEnforcer);
Http2ConnectionEncoder encoder = new DefaultHttp2ConnectionEncoder(connection, frameWriter);
Http2ConnectionDecoder decoder = new DefaultHttp2ConnectionDecoder(connection, encoder,
frameReader);
Http2Settings settings = new Http2Settings();
settings.initialWindowSize(flowControlWindow);
settings.maxConcurrentStreams(maxStreams);
settings.maxHeaderListSize(maxHeaderListSize);
return new NettyServerHandler(
channelUnused,
connection,
transportListener,
streamTracerFactories,
transportTracer,
decoder, encoder, settings,
maxMessageSize,
keepAliveTimeInNanos, keepAliveTimeoutInNanos,
maxConnectionIdleInNanos,
maxConnectionAgeInNanos, maxConnectionAgeGraceInNanos,
keepAliveEnforcer);
}
private NettyServerHandler(
ChannelPromise channelUnused,
final Http2Connection connection,
ServerTransportListener transportListener,
List<ServerStreamTracer.Factory> streamTracerFactories,
TransportTracer transportTracer,
Http2ConnectionDecoder decoder,
Http2ConnectionEncoder encoder,
Http2Settings settings,
int maxMessageSize,
long keepAliveTimeInNanos,
long keepAliveTimeoutInNanos,
long maxConnectionIdleInNanos,
long maxConnectionAgeInNanos,
long maxConnectionAgeGraceInNanos,
final KeepAliveEnforcer keepAliveEnforcer) {
super(channelUnused, decoder, encoder, settings);
final MaxConnectionIdleManager maxConnectionIdleManager;
if (maxConnectionIdleInNanos == MAX_CONNECTION_IDLE_NANOS_DISABLED) {
maxConnectionIdleManager = null;
} else {
maxConnectionIdleManager = new MaxConnectionIdleManager(maxConnectionIdleInNanos) {
@Override
void close(ChannelHandlerContext ctx) {
goAway(
ctx,
Integer.MAX_VALUE,
Http2Error.NO_ERROR.code(),
ByteBufUtil.writeAscii(ctx.alloc(), "max_idle"),
ctx.newPromise());
ctx.flush();
try {
NettyServerHandler.this.close(ctx, ctx.newPromise());
} catch (Exception e) {
onError(ctx, e);
}
}
};
}
connection.addListener(new Http2ConnectionAdapter() {
@Override
public void onStreamActive(Http2Stream stream) {
if (connection.numActiveStreams() == 1) {
keepAliveEnforcer.onTransportActive();
if (maxConnectionIdleManager != null) {
maxConnectionIdleManager.onTransportActive();
}
}
}
@Override
public void onStreamClosed(Http2Stream stream) {
if (connection.numActiveStreams() == 0) {
keepAliveEnforcer.onTransportIdle();
if (maxConnectionIdleManager != null) {
maxConnectionIdleManager.onTransportIdle();
}
}
}
});
checkArgument(maxMessageSize >= 0, "maxMessageSize must be >= 0");
this.maxMessageSize = maxMessageSize;
this.keepAliveTimeInNanos = keepAliveTimeInNanos;
this.keepAliveTimeoutInNanos = keepAliveTimeoutInNanos;
this.maxConnectionIdleManager = maxConnectionIdleManager;
this.maxConnectionAgeInNanos = maxConnectionAgeInNanos;
this.maxConnectionAgeGraceInNanos = maxConnectionAgeGraceInNanos;
this.keepAliveEnforcer = checkNotNull(keepAliveEnforcer, "keepAliveEnforcer");
streamKey = encoder.connection().newKey();
this.transportListener = checkNotNull(transportListener, "transportListener");
this.streamTracerFactories = checkNotNull(streamTracerFactories, "streamTracerFactories");
this.transportTracer = checkNotNull(transportTracer, "transportTracer");
// Set the frame listener on the decoder.
decoder().frameListener(new FrameListener());
}
@Nullable
Throwable connectionError() {
return connectionError;
}
@Override
public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
serverWriteQueue = new WriteQueue(ctx.channel());
// init max connection age monitor
if (maxConnectionAgeInNanos != MAX_CONNECTION_AGE_NANOS_DISABLED) {
maxConnectionAgeMonitor = ctx.executor().schedule(
new LogExceptionRunnable(new Runnable() {
@Override
public void run() {
// send GO_AWAY
ByteBuf debugData = ByteBufUtil.writeAscii(ctx.alloc(), "max_age");
goAway(
ctx,
Integer.MAX_VALUE,
Http2Error.NO_ERROR.code(),
debugData,
ctx.newPromise());
// gracefully shutdown with specified grace time
long savedGracefulShutdownTime = gracefulShutdownTimeoutMillis();
try {
gracefulShutdownTimeoutMillis(
TimeUnit.NANOSECONDS.toMillis(maxConnectionAgeGraceInNanos));
close(ctx, ctx.newPromise());
} catch (Exception e) {
onError(ctx, e);
} finally {
gracefulShutdownTimeoutMillis(savedGracefulShutdownTime);
}
}
}),
maxConnectionAgeInNanos,
TimeUnit.NANOSECONDS);
}
if (maxConnectionIdleManager != null) {
maxConnectionIdleManager.start(ctx);
}
if (keepAliveTimeInNanos != SERVER_KEEPALIVE_TIME_NANOS_DISABLED) {
keepAliveManager = new KeepAliveManager(new KeepAlivePinger(ctx), ctx.executor(),
keepAliveTimeInNanos, keepAliveTimeoutInNanos, true /* keepAliveDuringTransportIdle */);
keepAliveManager.onTransportStarted();
}
if (transportTracer != null) {
assert encoder().connection().equals(decoder().connection());
final Http2Connection connection = encoder().connection();
transportTracer.setFlowControlWindowReader(new TransportTracer.FlowControlReader() {
private final Http2FlowController local = connection.local().flowController();
private final Http2FlowController remote = connection.remote().flowController();
@Override
public TransportTracer.FlowControlWindows read() {
assert ctx.executor().inEventLoop();
return new TransportTracer.FlowControlWindows(
local.windowSize(connection.connectionStream()),
remote.windowSize(connection.connectionStream()));
}
});
}
super.handlerAdded(ctx);
}
private void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers)
throws Http2Exception {
if (!teWarningLogged && !TE_TRAILERS.equals(headers.get(TE_HEADER))) {
logger.warning(String.format("Expected header TE: %s, but %s is received. This means "
+ "some intermediate proxy may not support trailers",
TE_TRAILERS, headers.get(TE_HEADER)));
teWarningLogged = true;
}
try {
// Remove the leading slash of the path and get the fully qualified method name
CharSequence path = headers.path();
if (path == null) {
respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED,
"Expected path but is missing");
return;
}
if (path.charAt(0) != '/') {
respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED,
String.format("Expected path to start with /: %s", path));
return;
}
String method = path.subSequence(1, path.length()).toString();
// Verify that the Content-Type is correct in the request.
CharSequence contentType = headers.get(CONTENT_TYPE_HEADER);
if (contentType == null) {
respondWithHttpError(
ctx, streamId, 415, Status.Code.INTERNAL, "Content-Type is missing from the request");
return;
}
String contentTypeString = contentType.toString();
if (!GrpcUtil.isGrpcContentType(contentTypeString)) {
respondWithHttpError(ctx, streamId, 415, Status.Code.INTERNAL,
String.format("Content-Type '%s' is not supported", contentTypeString));
return;
}
if (!HTTP_METHOD.equals(headers.method())) {
respondWithHttpError(ctx, streamId, 405, Status.Code.INTERNAL,
String.format("Method '%s' is not supported", headers.method()));
return;
}
// The Http2Stream object was put by AbstractHttp2ConnectionHandler before calling this
// method.
Http2Stream http2Stream = requireHttp2Stream(streamId);
Metadata metadata = Utils.convertHeaders(headers);
StatsTraceContext statsTraceCtx =
StatsTraceContext.newServerContext(streamTracerFactories, method, metadata);
NettyServerStream.TransportState state = new NettyServerStream.TransportState(
this,
ctx.channel().eventLoop(),
http2Stream,
maxMessageSize,
statsTraceCtx,
transportTracer);
String authority = getOrUpdateAuthority((AsciiString) headers.authority());
NettyServerStream stream = new NettyServerStream(
ctx.channel(),
state,
attributes,
authority,
statsTraceCtx,
transportTracer);
transportListener.streamCreated(stream, method, metadata);
state.onStreamAllocated();
http2Stream.setProperty(streamKey, state);
} catch (Exception e) {
logger.log(Level.WARNING, "Exception in onHeadersRead()", e);
// Throw an exception that will get handled by onStreamError.
throw newStreamException(streamId, e);
}
}
private String getOrUpdateAuthority(AsciiString authority) {
if (authority == null) {
return null;
} else if (!authority.equals(lastKnownAuthority)) {
lastKnownAuthority = authority;
}
// AsciiString.toString() is internally cached, so subsequent calls will not
// result in recomputing the String representation of lastKnownAuthority.
return lastKnownAuthority.toString();
}
private void onDataRead(int streamId, ByteBuf data, int padding, boolean endOfStream)
throws Http2Exception {
flowControlPing().onDataRead(data.readableBytes(), padding);
try {
NettyServerStream.TransportState stream = serverStream(requireHttp2Stream(streamId));
stream.inboundDataReceived(data, endOfStream);
} catch (Throwable e) {
logger.log(Level.WARNING, "Exception in onDataRead()", e);
// Throw an exception that will get handled by onStreamError.
throw newStreamException(streamId, e);
}
}
private void onRstStreamRead(int streamId, long errorCode) throws Http2Exception {
try {
NettyServerStream.TransportState stream = serverStream(connection().stream(streamId));
if (stream != null) {
stream.transportReportStatus(
Status.CANCELLED.withDescription("RST_STREAM received for code " + errorCode));
}
} catch (Throwable e) {
logger.log(Level.WARNING, "Exception in onRstStreamRead()", e);
// Throw an exception that will get handled by onStreamError.
throw newStreamException(streamId, e);
}
}
@Override
protected void onConnectionError(ChannelHandlerContext ctx, Throwable cause,
Http2Exception http2Ex) {
logger.log(Level.FINE, "Connection Error", cause);
connectionError = cause;
super.onConnectionError(ctx, cause, http2Ex);
}
@Override
protected void onStreamError(ChannelHandlerContext ctx, Throwable cause,
StreamException http2Ex) {
logger.log(Level.WARNING, "Stream Error", cause);
NettyServerStream.TransportState serverStream = serverStream(
connection().stream(Http2Exception.streamId(http2Ex)));
if (serverStream != null) {
serverStream.transportReportStatus(Utils.statusFromThrowable(cause));
}
// TODO(ejona): Abort the stream by sending headers to help the client with debugging.
// Delegate to the base class to send a RST_STREAM.
super.onStreamError(ctx, cause, http2Ex);
}
@Override
public void handleProtocolNegotiationCompleted(Attributes attrs) {
negotiationAttributes = attrs;
}
@VisibleForTesting
KeepAliveManager getKeepAliveManagerForTest() {
return keepAliveManager;
}
@VisibleForTesting
void setKeepAliveManagerForTest(KeepAliveManager keepAliveManager) {
this.keepAliveManager = keepAliveManager;
}
/**
* Handler for the Channel shutting down.
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
try {
if (keepAliveManager != null) {
keepAliveManager.onTransportTermination();
}
if (maxConnectionIdleManager != null) {
maxConnectionIdleManager.onTransportTermination();
}
if (maxConnectionAgeMonitor != null) {
maxConnectionAgeMonitor.cancel(false);
}
final Status status =
Status.UNAVAILABLE.withDescription("connection terminated for unknown reason");
// Any streams that are still active must be closed
connection().forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
NettyServerStream.TransportState serverStream = serverStream(stream);
if (serverStream != null) {
serverStream.transportReportStatus(status);
}
return true;
}
});
} finally {
super.channelInactive(ctx);
}
}
WriteQueue getWriteQueue() {
return serverWriteQueue;
}
/**
* Handler for commands sent from the stream.
*/
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
throws Exception {
if (msg instanceof SendGrpcFrameCommand) {
sendGrpcFrame(ctx, (SendGrpcFrameCommand) msg, promise);
} else if (msg instanceof SendResponseHeadersCommand) {
sendResponseHeaders(ctx, (SendResponseHeadersCommand) msg, promise);
} else if (msg instanceof CancelServerStreamCommand) {
cancelStream(ctx, (CancelServerStreamCommand) msg, promise);
} else if (msg instanceof ForcefulCloseCommand) {
forcefulClose(ctx, (ForcefulCloseCommand) msg, promise);
} else {
AssertionError e =
new AssertionError("Write called for unexpected type: " + msg.getClass().getName());
ReferenceCountUtil.release(msg);
promise.setFailure(e);
throw e;
}
}
/**
* Returns the given processed bytes back to inbound flow control.
*/
void returnProcessedBytes(Http2Stream http2Stream, int bytes) {
try {
decoder().flowController().consumeBytes(http2Stream, bytes);
} catch (Http2Exception e) {
throw new RuntimeException(e);
}
}
private void closeStreamWhenDone(ChannelPromise promise, int streamId) throws Http2Exception {
final NettyServerStream.TransportState stream = serverStream(requireHttp2Stream(streamId));
promise.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
stream.complete();
}
});
}
/**
* Sends the given gRPC frame to the client.
*/
private void sendGrpcFrame(ChannelHandlerContext ctx, SendGrpcFrameCommand cmd,
ChannelPromise promise) throws Http2Exception {
if (cmd.endStream()) {
closeStreamWhenDone(promise, cmd.streamId());
}
// Call the base class to write the HTTP/2 DATA frame.
encoder().writeData(ctx, cmd.streamId(), cmd.content(), 0, cmd.endStream(), promise);
}
/**
* Sends the response headers to the client.
*/
private void sendResponseHeaders(ChannelHandlerContext ctx, SendResponseHeadersCommand cmd,
ChannelPromise promise) throws Http2Exception {
// TODO(carl-mastrangelo): remove this check once https://github.com/netty/netty/issues/6296 is
// fixed.
int streamId = cmd.stream().id();
Http2Stream stream = connection().stream(streamId);
if (stream == null) {
resetStream(ctx, streamId, Http2Error.CANCEL.code(), promise);
return;
}
if (cmd.endOfStream()) {
closeStreamWhenDone(promise, streamId);
}
encoder().writeHeaders(ctx, streamId, cmd.headers(), 0, cmd.endOfStream(), promise);
}
private void cancelStream(ChannelHandlerContext ctx, CancelServerStreamCommand cmd,
ChannelPromise promise) {
// Notify the listener if we haven't already.
cmd.stream().transportReportStatus(cmd.reason());
// Terminate the stream.
encoder().writeRstStream(ctx, cmd.stream().id(), Http2Error.CANCEL.code(), promise);
}
private void forcefulClose(final ChannelHandlerContext ctx, final ForcefulCloseCommand msg,
ChannelPromise promise) throws Exception {
close(ctx, promise);
connection().forEachActiveStream(new Http2StreamVisitor() {
@Override
public boolean visit(Http2Stream stream) throws Http2Exception {
NettyServerStream.TransportState serverStream = serverStream(stream);
if (serverStream != null) {
serverStream.transportReportStatus(msg.getStatus());
resetStream(ctx, stream.id(), Http2Error.CANCEL.code(), ctx.newPromise());
}
stream.close();
return true;
}
});
}
private void respondWithHttpError(
ChannelHandlerContext ctx, int streamId, int code, Status.Code statusCode, String msg) {
Metadata metadata = new Metadata();
metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
metadata.put(InternalStatus.MESSAGE_KEY, msg);
byte[][] serialized = InternalMetadata.serialize(metadata);
Http2Headers headers = new DefaultHttp2Headers(true, serialized.length / 2)
.status("" + code)
.set(CONTENT_TYPE_HEADER, "text/plain; encoding=utf-8");
for (int i = 0; i < serialized.length; i += 2) {
headers.add(new AsciiString(serialized[i], false), new AsciiString(serialized[i + 1], false));
}
encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
ByteBuf msgBuf = ByteBufUtil.writeUtf8(ctx.alloc(), msg);
encoder().writeData(ctx, streamId, msgBuf, 0, true, ctx.newPromise());
}
private Http2Stream requireHttp2Stream(int streamId) {
Http2Stream stream = connection().stream(streamId);
if (stream == null) {
// This should never happen.
throw new AssertionError("Stream does not exist: " + streamId);
}
return stream;
}
/**
* Returns the server stream associated to the given HTTP/2 stream object.
*/
private NettyServerStream.TransportState serverStream(Http2Stream stream) {
return stream == null ? null : (NettyServerStream.TransportState) stream.getProperty(streamKey);
}
private Http2Exception newStreamException(int streamId, Throwable cause) {
return Http2Exception.streamError(
streamId, Http2Error.INTERNAL_ERROR, cause, Strings.nullToEmpty(cause.getMessage()));
}
private class FrameListener extends Http2FrameAdapter {
private boolean firstSettings = true;
@Override
public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) {
if (firstSettings) {
firstSettings = false;
// Delay transportReady until we see the client's HTTP handshake, for coverage with
// handshakeTimeout
attributes = transportListener.transportReady(negotiationAttributes);
}
}
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
boolean endOfStream) throws Http2Exception {
if (keepAliveManager != null) {
keepAliveManager.onDataReceived();
}
NettyServerHandler.this.onDataRead(streamId, data, padding, endOfStream);
return padding;
}
@Override
public void onHeadersRead(ChannelHandlerContext ctx,
int streamId,
Http2Headers headers,
int streamDependency,
short weight,
boolean exclusive,
int padding,
boolean endStream) throws Http2Exception {
if (keepAliveManager != null) {
keepAliveManager.onDataReceived();
}
NettyServerHandler.this.onHeadersRead(ctx, streamId, headers);
}
@Override
public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode)
throws Http2Exception {
if (keepAliveManager != null) {
keepAliveManager.onDataReceived();
}
NettyServerHandler.this.onRstStreamRead(streamId, errorCode);
}
@Override
public void onPingRead(ChannelHandlerContext ctx, ByteBuf data) throws Http2Exception {
if (keepAliveManager != null) {
keepAliveManager.onDataReceived();
}
if (!keepAliveEnforcer.pingAcceptable()) {
ByteBuf debugData = ByteBufUtil.writeAscii(ctx.alloc(), "too_many_pings");
goAway(ctx, connection().remote().lastStreamCreated(), Http2Error.ENHANCE_YOUR_CALM.code(),
debugData, ctx.newPromise());
Status status = Status.RESOURCE_EXHAUSTED.withDescription("Too many pings from client");
try {
forcefulClose(ctx, new ForcefulCloseCommand(status), ctx.newPromise());
} catch (Exception ex) {
onError(ctx, ex);
}
}
}
@Override
public void onPingAckRead(ChannelHandlerContext ctx, ByteBuf data) throws Http2Exception {
if (keepAliveManager != null) {
keepAliveManager.onDataReceived();
}
if (data.getLong(data.readerIndex()) == flowControlPing().payload()) {
flowControlPing().updateWindow();
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, String.format("Window: %d",
decoder().flowController().initialWindowSize(connection().connectionStream())));
}
} else if (!KEEPALIVE_PING_BUF.equals(data)) {
logger.warning("Received unexpected ping ack. No ping outstanding");
}
}
}
private final class KeepAlivePinger implements KeepAliveManager.KeepAlivePinger {
final ChannelHandlerContext ctx;
KeepAlivePinger(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void ping() {
ChannelFuture pingFuture = encoder().writePing(
// slice KEEPALIVE_PING_BUF because tls handler may modify the reader index
ctx, false /* isAck */, KEEPALIVE_PING_BUF.slice(), ctx.newPromise());
ctx.flush();
if (transportTracer != null) {
pingFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
transportTracer.reportKeepAliveSent();
}
}
});
}
}
@Override
public void onPingTimeout() {
try {
forcefulClose(
ctx,
new ForcefulCloseCommand(Status.UNAVAILABLE
.withDescription("Keepalive failed. The connection is likely gone")),
ctx.newPromise());
} catch (Exception ex) {
try {
exceptionCaught(ctx, ex);
} catch (Exception ex2) {
logger.log(Level.WARNING, "Exception while propagating exception", ex2);
logger.log(Level.WARNING, "Original failure", ex);
}
}
}
}
// Use a frame writer so that we know when frames are through flow control and actually being
// written.
private static class WriteMonitoringFrameWriter extends DecoratingHttp2FrameWriter {
private final KeepAliveEnforcer keepAliveEnforcer;
public WriteMonitoringFrameWriter(Http2FrameWriter delegate,
KeepAliveEnforcer keepAliveEnforcer) {
super(delegate);
this.keepAliveEnforcer = keepAliveEnforcer;
}
@Override
public ChannelFuture writeData(ChannelHandlerContext ctx, int streamId, ByteBuf data,
int padding, boolean endStream, ChannelPromise promise) {
keepAliveEnforcer.resetCounters();
return super.writeData(ctx, streamId, data, padding, endStream, promise);
}
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
int padding, boolean endStream, ChannelPromise promise) {
keepAliveEnforcer.resetCounters();
return super.writeHeaders(ctx, streamId, headers, padding, endStream, promise);
}
@Override
public ChannelFuture writeHeaders(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
int streamDependency, short weight, boolean exclusive, int padding, boolean endStream,
ChannelPromise promise) {
keepAliveEnforcer.resetCounters();
return super.writeHeaders(ctx, streamId, headers, streamDependency, weight, exclusive,
padding, endStream, promise);
}
}
}
| |
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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/LICENSE2.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.wso2.carbon.apimgt.core.impl;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.extensions.Deployment;
import io.fabric8.kubernetes.api.model.extensions.Ingress;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.openshift.client.DefaultOpenShiftClient;
import io.fabric8.openshift.client.OpenShiftClient;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException;
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes;
import org.wso2.carbon.apimgt.core.models.API;
import org.wso2.carbon.apimgt.core.template.ContainerBasedGatewayTemplateBuilder;
import org.wso2.carbon.apimgt.core.util.ContainerBasedGatewayConstants;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This is responsible to handle the gateways created in Kubernetes and Openshift
*/
public class KubernetesGatewayImpl extends ContainerBasedGatewayGenerator {
private static final Logger log = LoggerFactory.getLogger(KubernetesGatewayImpl.class);
private static final String TRY_KUBE_CONFIG = "kubernetes.auth.tryKubeConfig";
private static final String TRY_SERVICE_ACCOUNT = "kubernetes.auth.tryServiceAccount";
private static final String DASH = "-";
private static final String FORWARD_SLASH = "/";
private String cmsType;
private String masterURL;
private String namespace;
private String apiCoreUrl;
private String brokerHost;
private String saTokenFileName;
private String gatewayHostname;
private OpenShiftClient client;
/**
* @see ContainerBasedGatewayGenerator#initImpl(Map)
*/
@Override
void initImpl(Map<String, String> implParameters) throws ContainerBasedGatewayException {
try {
setValues(implParameters);
setClient(new DefaultOpenShiftClient(buildConfig()));
} catch (KubernetesClientException e) {
String msg = "Error occurred while creating Default Openshift Client";
throw new ContainerBasedGatewayException(msg, e,
ExceptionCodes.ERROR_INITIALIZING_DEDICATED_CONTAINER_BASED_GATEWAY);
}
}
/**
* Set values for Openshift client
*/
void setValues(Map<String, String> implParameters) {
masterURL = implParameters.get(ContainerBasedGatewayConstants.MASTER_URL);
saTokenFileName = implParameters.get(ContainerBasedGatewayConstants.SA_TOKEN_FILE_NAME);
namespace = implParameters.get(ContainerBasedGatewayConstants.NAMESPACE);
apiCoreUrl = implParameters.get(ContainerBasedGatewayConstants.API_CORE_URL);
brokerHost = implParameters.get(ContainerBasedGatewayConstants.BROKER_HOST);
cmsType = implParameters.get(ContainerBasedGatewayConstants.CMS_TYPE);
gatewayHostname = implParameters.get(ContainerBasedGatewayConstants.GATEWAY_HOSTNAME);
log.debug("master url: {} saTokenFileName: {} namespace: {} apiCoreUrl: {} brokerHost: {} cmsType: {} " +
"gatewayHostname: {}", masterURL, saTokenFileName, namespace, apiCoreUrl, brokerHost,
cmsType, gatewayHostname);
}
/**
* @see ContainerBasedGatewayGenerator#removeContainerBasedGateway(String, API) (String)
*/
@Override
public void removeContainerBasedGateway(String label, API api) throws ContainerBasedGatewayException {
try {
client.services().inNamespace(namespace).withLabel(ContainerBasedGatewayConstants.GATEWAY, label).delete();
client.extensions().deployments().inNamespace(namespace).withLabel(ContainerBasedGatewayConstants.GATEWAY,
label).delete();
client.extensions().ingresses().inNamespace(namespace).withLabel(ContainerBasedGatewayConstants.GATEWAY,
label).delete();
log.info(String.format("Completed deleting the container gateway related %s deployment, service and " +
"ingress resources.", cmsType));
} catch (KubernetesClientException e) {
throw new ContainerBasedGatewayException("Error while removing container based gateway", e,
ExceptionCodes.CONTAINER_GATEWAY_REMOVAL_FAILED);
}
}
/**
* @see ContainerBasedGatewayGenerator#createContainerGateway(String, API)
*/
@Override
public void createContainerGateway(String label, API api) throws ContainerBasedGatewayException {
Map<String, String> templateValues = new HashMap<>();
String serviceName = label + ContainerBasedGatewayConstants.CMS_SERVICE_SUFFIX;
String deploymentName = label + ContainerBasedGatewayConstants.CMS_DEPLOYMENT_SUFFIX;
String ingressName = label + ContainerBasedGatewayConstants.CMS_INGRESS_SUFFIX;
templateValues.put(ContainerBasedGatewayConstants.NAMESPACE, namespace);
templateValues.put(ContainerBasedGatewayConstants.GATEWAY_LABEL, label);
templateValues.put(ContainerBasedGatewayConstants.SERVICE_NAME, serviceName);
templateValues.put(ContainerBasedGatewayConstants.DEPLOYMENT_NAME, deploymentName);
templateValues.put(ContainerBasedGatewayConstants.INGRESS_NAME, ingressName);
templateValues.put(ContainerBasedGatewayConstants.CONTAINER_NAME, label
+ ContainerBasedGatewayConstants.CMS_CONTAINER_SUFFIX);
templateValues.put(ContainerBasedGatewayConstants.API_CORE_URL, apiCoreUrl);
templateValues.put(ContainerBasedGatewayConstants.BROKER_HOST, brokerHost);
templateValues.put(ContainerBasedGatewayConstants.GATEWAY_HOSTNAME, generateSubDomain(api) + "."
+ gatewayHostname);
ContainerBasedGatewayTemplateBuilder builder = new ContainerBasedGatewayTemplateBuilder();
// Create gateway service resource
createServiceResource(builder.generateTemplate(templateValues,
ContainerBasedGatewayConstants.GATEWAY_SERVICE_TEMPLATE), serviceName);
// Create gateway deployment resource
createDeploymentResource(builder.generateTemplate(templateValues,
ContainerBasedGatewayConstants.GATEWAY_DEPLOYMENT_TEMPLATE), deploymentName);
// Create gateway ingress resource
createIngressResource(builder.generateTemplate(templateValues,
ContainerBasedGatewayConstants.GATEWAY_INGRESS_TEMPLATE), ingressName);
}
/**
* Generate a sub domain for the Ingress based on the API's context
*
* @param api API
* @return subDomain
*/
private String generateSubDomain(API api) {
String context = api.getContext();
String[] contextValues = context.split(FORWARD_SLASH);
StringBuffer stringBuffer = new StringBuffer();
for (String contextValue : contextValues) {
if (!contextValue.isEmpty()) {
stringBuffer.append(contextValue + DASH);
}
}
String subDomain = stringBuffer.toString();
if (subDomain.endsWith(DASH)) {
subDomain = subDomain.substring(0, subDomain.length() - 1);
}
log.debug("Sub domain: {} generated for the api: {}", subDomain, api.getName());
return subDomain;
}
/**
* Build configurations for Openshift client
*
* @throws ContainerBasedGatewayException if failed to configure Openshift client
*/
private Config buildConfig() throws ContainerBasedGatewayException {
System.setProperty(TRY_KUBE_CONFIG, "false");
System.setProperty(TRY_SERVICE_ACCOUNT, "true");
ConfigBuilder configBuilder;
if (masterURL != null) {
configBuilder = new ConfigBuilder().withMasterUrl(masterURL);
} else {
throw new ContainerBasedGatewayException("Kubernetes Master URL is not provided!", ExceptionCodes
.ERROR_INITIALIZING_DEDICATED_CONTAINER_BASED_GATEWAY);
}
if (!StringUtils.isEmpty(saTokenFileName)) {
configBuilder.withOauthToken(resolveToken("encrypted" + saTokenFileName));
}
return configBuilder.build();
}
/**
* Set Default Openshift client
*
* @param openShiftClient Openshift client
*/
void setClient(OpenShiftClient openShiftClient) {
this.client = openShiftClient;
}
/**
* Get resources from template
*
* @param template Template as a String
* @return HasMetadata
* @throws ContainerBasedGatewayException if failed to load resource from the template
*/
private HasMetadata getResourcesFromTemplate(String template) throws ContainerBasedGatewayException {
List<HasMetadata> resources;
try (InputStream inputStream = IOUtils.toInputStream(template)) {
resources = client.load(inputStream).get();
if (resources == null || resources.isEmpty()) {
throw new ContainerBasedGatewayException("No resources loaded from the definition provided : ",
ExceptionCodes.NO_RESOURCE_LOADED_FROM_DEFINITION);
}
return resources.get(0);
} catch (IOException e) {
throw new ContainerBasedGatewayException("Client cannot load any resource from the template : "
+ template, e, ExceptionCodes.TEMPLATE_LOAD_EXCEPTION);
}
}
/**
* Create a service in cms
*
* @param serviceTemplate Service template as a String
* @param serviceName Name of the service
* @throws ContainerBasedGatewayException if failed to create a service
*/
private void createServiceResource(String serviceTemplate, String serviceName)
throws ContainerBasedGatewayException {
HasMetadata resource = getResourcesFromTemplate(serviceTemplate);
try {
if (resource instanceof Service) {
// check whether there are existing service already
if (client.services().inNamespace(namespace).withName(serviceName).get() == null) {
log.debug("Deploying in CMS type: {} and the Service resource definition: {} ", cmsType,
serviceTemplate);
Service service = (Service) resource;
Service result = client.services().inNamespace(namespace).create(service);
log.info("Created Service : " + result.getMetadata().getName() + " in Namespace : "
+ result.getMetadata().getNamespace() + " in " + cmsType);
} else {
log.info("There exist a service with the same name in " + cmsType + ". Service name : "
+ serviceName);
}
} else {
throw new ContainerBasedGatewayException("Loaded Resource is not a Service in " + cmsType + "! " +
resource, ExceptionCodes.LOADED_RESOURCE_DEFINITION_IS_NOT_VALID);
}
} catch (KubernetesClientException e) {
throw new ContainerBasedGatewayException("Error while creating container based gateway service in "
+ cmsType + "!", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
}
}
/**
* Create a deployment in cms
*
* @param deploymentTemplate Deployment template as a String
* @param deploymentName Name of the deployment
* @throws ContainerBasedGatewayException if failed to create a deployment
*/
private void createDeploymentResource(String deploymentTemplate, String deploymentName)
throws ContainerBasedGatewayException {
HasMetadata resource = getResourcesFromTemplate(deploymentTemplate);
try {
if (resource instanceof Deployment) {
// check whether there are existing service already
if (client.extensions().deployments().inNamespace(namespace).withName(deploymentName).get() == null) {
log.debug("Deploying in CMS type: {} and the Deployment resource definition: {} ", cmsType,
deploymentTemplate);
Deployment deployment = (Deployment) resource;
Deployment result = client.extensions().deployments().inNamespace(namespace).create(deployment);
log.info("Created Deployment : " + result.getMetadata().getName() + " in Namespace : "
+ result.getMetadata().getNamespace() + " in " + cmsType);
} else {
log.info("There exist a deployment with the same name in " + cmsType + ". Deployment name : "
+ deploymentName);
}
} else {
throw new ContainerBasedGatewayException("Loaded Resource is not a Deployment in " + cmsType + "! " +
resource, ExceptionCodes.LOADED_RESOURCE_DEFINITION_IS_NOT_VALID);
}
} catch (KubernetesClientException e) {
throw new ContainerBasedGatewayException("Error while creating container based gateway deployment in "
+ cmsType + "!", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
}
}
/**
* Create an Ingress resource in cms
*
* @param ingressTemplate Ingress template as a String
* @param ingressName Name of the ingress
* @throws ContainerBasedGatewayException if failed to create a service
*/
private void createIngressResource(String ingressTemplate, String ingressName)
throws ContainerBasedGatewayException {
HasMetadata resource = getResourcesFromTemplate(ingressTemplate);
try {
if (resource instanceof Ingress) {
// check whether there are existing service already
if (client.extensions().ingresses().inNamespace(namespace).withName(ingressName).get() == null) {
log.debug("Deploying in CMS type: {} and the Ingress resource definition: {} ", cmsType,
ingressTemplate);
Ingress ingress = (Ingress) resource;
Ingress result = client.extensions().ingresses().inNamespace(namespace).create(ingress);
log.info("Created Ingress : " + result.getMetadata().getName() + " in Namespace : "
+ result.getMetadata().getNamespace() + " in " + cmsType);
} else {
log.info("There exist an ingress with the same name in " + cmsType + ". Ingress name : "
+ ingressName);
}
} else {
throw new ContainerBasedGatewayException("Loaded Resource is not a Service in " + cmsType + "! " +
resource, ExceptionCodes.LOADED_RESOURCE_DEFINITION_IS_NOT_VALID);
}
} catch (KubernetesClientException e) {
throw new ContainerBasedGatewayException("Error while creating container based gateway ingress in "
+ cmsType + "!", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
}
}
/**
* Get the token after decrypting using {@link FileEncryptionUtility#readFromEncryptedFile(java.lang.String)}
*
* @return service account token
* @throws ContainerBasedGatewayException if an error occurs while resolving the token
*/
private String resolveToken(String encryptedTokenFileName) throws ContainerBasedGatewayException {
String token;
try {
String externalSATokenFilePath = System.getProperty(FileEncryptionUtility.CARBON_HOME)
+ FileEncryptionUtility.SECURITY_DIR + File.separator + encryptedTokenFileName;
token = FileEncryptionUtility.getInstance().readFromEncryptedFile(externalSATokenFilePath);
} catch (APIManagementException e) {
String msg = "Error occurred while resolving externally stored token";
throw new ContainerBasedGatewayException(msg, e,
ExceptionCodes.ERROR_INITIALIZING_DEDICATED_CONTAINER_BASED_GATEWAY);
}
return StringUtils.replace(token, "\n", "");
}
}
| |
/*
* 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.cluster.metadata;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.ResourceAlreadyExistsException;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest;
import org.elasticsearch.action.admin.indices.shrink.ResizeType;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ESAllocationTestCase;
import org.elasticsearch.cluster.EmptyClusterInfoService;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodeRole;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator;
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
import org.elasticsearch.cluster.routing.allocation.decider.MaxRetryAllocationDecider;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.indices.InvalidAliasNameException;
import org.elasticsearch.indices.InvalidIndexNameException;
import org.elasticsearch.indices.ShardLimitValidator;
import org.elasticsearch.indices.SystemIndexDescriptor;
import org.elasticsearch.test.ClusterServiceUtils;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.VersionUtils;
import org.elasticsearch.test.gateway.TestGatewayAllocator;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.hamcrest.Matchers;
import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Collections.emptyMap;
import static org.elasticsearch.cluster.metadata.IndexMetadata.INDEX_NUMBER_OF_ROUTING_SHARDS_SETTING;
import static org.elasticsearch.cluster.metadata.IndexMetadata.INDEX_NUMBER_OF_SHARDS_SETTING;
import static org.elasticsearch.cluster.metadata.IndexMetadata.INDEX_READ_ONLY_BLOCK;
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_INDEX_VERSION_CREATED;
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_READ_ONLY;
import static org.elasticsearch.cluster.metadata.MetadataCreateIndexService.aggregateIndexSettings;
import static org.elasticsearch.cluster.metadata.MetadataCreateIndexService.buildIndexMetadata;
import static org.elasticsearch.cluster.metadata.MetadataCreateIndexService.clusterStateCreateIndex;
import static org.elasticsearch.cluster.metadata.MetadataCreateIndexService.getIndexNumberOfRoutingShards;
import static org.elasticsearch.cluster.metadata.MetadataCreateIndexService.parseV1Mappings;
import static org.elasticsearch.cluster.metadata.MetadataCreateIndexService.resolveAndValidateAliases;
import static org.elasticsearch.index.IndexSettings.INDEX_SOFT_DELETES_SETTING;
import static org.elasticsearch.indices.ShardLimitValidatorTests.createTestShardLimitService;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasValue;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
public class MetadataCreateIndexServiceTests extends ESTestCase {
private AliasValidator aliasValidator;
private CreateIndexClusterStateUpdateRequest request;
private QueryShardContext queryShardContext;
@Before
public void setupCreateIndexRequestAndAliasValidator() {
aliasValidator = new AliasValidator();
request = new CreateIndexClusterStateUpdateRequest("create index", "test", "test");
Settings indexSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1).build();
queryShardContext = new QueryShardContext(0,
new IndexSettings(IndexMetadata.builder("test").settings(indexSettings).build(), indexSettings),
BigArrays.NON_RECYCLING_INSTANCE, null, null, null, null, null, xContentRegistry(), writableRegistry(),
null, null, () -> randomNonNegativeLong(), null, null, () -> true, null);
}
private ClusterState createClusterState(String name, int numShards, int numReplicas, Settings settings) {
int numRoutingShards = settings.getAsInt(IndexMetadata.INDEX_NUMBER_OF_ROUTING_SHARDS_SETTING.getKey(), numShards);
Metadata.Builder metaBuilder = Metadata.builder();
IndexMetadata indexMetadata = IndexMetadata.builder(name).settings(settings(Version.CURRENT)
.put(settings))
.numberOfShards(numShards).numberOfReplicas(numReplicas)
.setRoutingNumShards(numRoutingShards).build();
metaBuilder.put(indexMetadata, false);
Metadata metadata = metaBuilder.build();
RoutingTable.Builder routingTableBuilder = RoutingTable.builder();
routingTableBuilder.addAsNew(metadata.index(name));
RoutingTable routingTable = routingTableBuilder.build();
ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.CLUSTER_NAME_SETTING
.getDefault(Settings.EMPTY))
.metadata(metadata).routingTable(routingTable).blocks(ClusterBlocks.builder().addBlocks(indexMetadata)).build();
return clusterState;
}
public static boolean isShrinkable(int source, int target) {
int x = source / target;
assert source > target : source + " <= " + target;
return target * x == source;
}
public static boolean isSplitable(int source, int target) {
int x = target / source;
assert source < target : source + " >= " + target;
return source * x == target;
}
public void testValidateShrinkIndex() {
int numShards = randomIntBetween(2, 42);
ClusterState state = createClusterState("source", numShards, randomIntBetween(0, 10),
Settings.builder().put("index.blocks.write", true).build());
assertEquals("index [source] already exists",
expectThrows(ResourceAlreadyExistsException.class, () ->
MetadataCreateIndexService.validateShrinkIndex(state, "target", Collections.emptySet(), "source", Settings.EMPTY)
).getMessage());
assertEquals("no such index [no_such_index]",
expectThrows(IndexNotFoundException.class, () ->
MetadataCreateIndexService.validateShrinkIndex(state, "no_such_index", Collections.emptySet(), "target", Settings.EMPTY)
).getMessage());
Settings targetSettings = Settings.builder().put("index.number_of_shards", 1).build();
assertEquals("can't shrink an index with only one shard",
expectThrows(IllegalArgumentException.class, () -> MetadataCreateIndexService.validateShrinkIndex(createClusterState("source",
1, 0, Settings.builder().put("index.blocks.write", true).build()), "source",
Collections.emptySet(), "target", targetSettings)).getMessage());
assertEquals("the number of target shards [10] must be less that the number of source shards [5]",
expectThrows(IllegalArgumentException.class, () -> MetadataCreateIndexService.validateShrinkIndex(createClusterState("source",
5, 0, Settings.builder().put("index.blocks.write", true).build()), "source",
Collections.emptySet(), "target", Settings.builder().put("index.number_of_shards", 10).build())).getMessage());
assertEquals("index source must be read-only to resize index. use \"index.blocks.write=true\"",
expectThrows(IllegalStateException.class, () ->
MetadataCreateIndexService.validateShrinkIndex(
createClusterState("source", randomIntBetween(2, 100), randomIntBetween(0, 10), Settings.EMPTY)
, "source", Collections.emptySet(), "target", targetSettings)
).getMessage());
assertEquals("index source must have all shards allocated on the same node to shrink index",
expectThrows(IllegalStateException.class, () ->
MetadataCreateIndexService.validateShrinkIndex(state, "source", Collections.emptySet(), "target", targetSettings)
).getMessage());
assertEquals("the number of source shards [8] must be a multiple of [3]",
expectThrows(IllegalArgumentException.class, () ->
MetadataCreateIndexService.validateShrinkIndex(createClusterState("source", 8, randomIntBetween(0, 10),
Settings.builder().put("index.blocks.write", true).build()), "source", Collections.emptySet(), "target",
Settings.builder().put("index.number_of_shards", 3).build())
).getMessage());
assertEquals("mappings are not allowed when resizing indices, all mappings are copied from the source index",
expectThrows(IllegalArgumentException.class, () -> {
MetadataCreateIndexService.validateShrinkIndex(state, "source", Collections.singleton("foo"),
"target", targetSettings);
}
).getMessage());
// create one that won't fail
ClusterState clusterState = ClusterState.builder(createClusterState("source", numShards, 0,
Settings.builder().put("index.blocks.write", true).build())).nodes(DiscoveryNodes.builder().add(newNode("node1")))
.build();
AllocationService service = new AllocationService(new AllocationDeciders(
Collections.singleton(new MaxRetryAllocationDecider())),
new TestGatewayAllocator(), new BalancedShardsAllocator(Settings.EMPTY), EmptyClusterInfoService.INSTANCE);
RoutingTable routingTable = service.reroute(clusterState, "reroute").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
// now we start the shard
routingTable = ESAllocationTestCase.startInitializingShardsAndReroute(service, clusterState, "source").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
int targetShards;
do {
targetShards = randomIntBetween(1, numShards/2);
} while (isShrinkable(numShards, targetShards) == false);
MetadataCreateIndexService.validateShrinkIndex(clusterState, "source", Collections.emptySet(), "target",
Settings.builder().put("index.number_of_shards", targetShards).build());
}
public void testValidateSplitIndex() {
int numShards = randomIntBetween(1, 42);
Settings targetSettings = Settings.builder().put("index.number_of_shards", numShards * 2).build();
ClusterState state = createClusterState("source", numShards, randomIntBetween(0, 10),
Settings.builder().put("index.blocks.write", true).build());
assertEquals("index [source] already exists",
expectThrows(ResourceAlreadyExistsException.class, () ->
MetadataCreateIndexService.validateSplitIndex(state, "target", Collections.emptySet(), "source", targetSettings)
).getMessage());
assertEquals("no such index [no_such_index]",
expectThrows(IndexNotFoundException.class, () ->
MetadataCreateIndexService.validateSplitIndex(state, "no_such_index", Collections.emptySet(), "target", targetSettings)
).getMessage());
assertEquals("the number of source shards [10] must be less that the number of target shards [5]",
expectThrows(IllegalArgumentException.class, () -> MetadataCreateIndexService.validateSplitIndex(createClusterState("source",
10, 0, Settings.builder().put("index.blocks.write", true).build()), "source", Collections.emptySet(),
"target", Settings.builder().put("index.number_of_shards", 5).build())
).getMessage());
assertEquals("index source must be read-only to resize index. use \"index.blocks.write=true\"",
expectThrows(IllegalStateException.class, () ->
MetadataCreateIndexService.validateSplitIndex(
createClusterState("source", randomIntBetween(2, 100), randomIntBetween(0, 10), Settings.EMPTY)
, "source", Collections.emptySet(), "target", targetSettings)
).getMessage());
assertEquals("the number of source shards [3] must be a factor of [4]",
expectThrows(IllegalArgumentException.class, () ->
MetadataCreateIndexService.validateSplitIndex(createClusterState("source", 3, randomIntBetween(0, 10),
Settings.builder().put("index.blocks.write", true).build()), "source", Collections.emptySet(), "target",
Settings.builder().put("index.number_of_shards", 4).build())
).getMessage());
assertEquals("mappings are not allowed when resizing indices, all mappings are copied from the source index",
expectThrows(IllegalArgumentException.class, () -> {
MetadataCreateIndexService.validateSplitIndex(state, "source", Collections.singleton("foo"),
"target", targetSettings);
}
).getMessage());
int targetShards;
do {
targetShards = randomIntBetween(numShards+1, 100);
} while (isSplitable(numShards, targetShards) == false);
ClusterState clusterState = ClusterState.builder(createClusterState("source", numShards, 0,
Settings.builder().put("index.blocks.write", true).put("index.number_of_routing_shards", targetShards).build()))
.nodes(DiscoveryNodes.builder().add(newNode("node1"))).build();
AllocationService service = new AllocationService(new AllocationDeciders(
Collections.singleton(new MaxRetryAllocationDecider())),
new TestGatewayAllocator(), new BalancedShardsAllocator(Settings.EMPTY), EmptyClusterInfoService.INSTANCE);
RoutingTable routingTable = service.reroute(clusterState, "reroute").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
// now we start the shard
routingTable = ESAllocationTestCase.startInitializingShardsAndReroute(service, clusterState, "source").routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
MetadataCreateIndexService.validateSplitIndex(clusterState, "source", Collections.emptySet(), "target",
Settings.builder().put("index.number_of_shards", targetShards).build());
}
public void testPrepareResizeIndexSettings() {
final List<Version> versions = Arrays.asList(VersionUtils.randomVersion(random()), VersionUtils.randomVersion(random()));
versions.sort(Comparator.comparingLong(l -> l.id));
final Version version = versions.get(0);
final Version upgraded = versions.get(1);
final Settings.Builder indexSettingsBuilder =
Settings.builder()
.put("index.version.created", version)
.put("index.version.upgraded", upgraded)
.put("index.similarity.default.type", "BM25")
.put("index.analysis.analyzer.default.tokenizer", "keyword")
.put("index.soft_deletes.enabled", "true");
if (randomBoolean()) {
indexSettingsBuilder.put("index.allocation.max_retries", randomIntBetween(1, 1000));
}
runPrepareResizeIndexSettingsTest(
indexSettingsBuilder.build(),
Settings.EMPTY,
Collections.emptyList(),
randomBoolean(),
settings -> {
assertThat("similarity settings must be copied", settings.get("index.similarity.default.type"), equalTo("BM25"));
assertThat(
"analysis settings must be copied",
settings.get("index.analysis.analyzer.default.tokenizer"),
equalTo("keyword"));
assertThat(settings.get("index.routing.allocation.initial_recovery._id"), equalTo("node1"));
assertThat(settings.get("index.allocation.max_retries"), nullValue());
assertThat(settings.getAsVersion("index.version.created", null), equalTo(version));
assertThat(settings.getAsVersion("index.version.upgraded", null), equalTo(upgraded));
assertThat(settings.get("index.soft_deletes.enabled"), equalTo("true"));
});
}
public void testPrepareResizeIndexSettingsCopySettings() {
final int maxMergeCount = randomIntBetween(1, 16);
final int maxThreadCount = randomIntBetween(1, 16);
final Setting<String> nonCopyableExistingIndexSetting =
Setting.simpleString("index.non_copyable.existing", Setting.Property.IndexScope, Setting.Property.NotCopyableOnResize);
final Setting<String> nonCopyableRequestIndexSetting =
Setting.simpleString("index.non_copyable.request", Setting.Property.IndexScope, Setting.Property.NotCopyableOnResize);
runPrepareResizeIndexSettingsTest(
Settings.builder()
.put("index.merge.scheduler.max_merge_count", maxMergeCount)
.put("index.non_copyable.existing", "existing")
.build(),
Settings.builder()
.put("index.blocks.write", (String) null)
.put("index.merge.scheduler.max_thread_count", maxThreadCount)
.put("index.non_copyable.request", "request")
.build(),
Arrays.asList(nonCopyableExistingIndexSetting, nonCopyableRequestIndexSetting),
true,
settings -> {
assertNull(settings.getAsBoolean("index.blocks.write", null));
assertThat(settings.get("index.routing.allocation.require._name"), equalTo("node1"));
assertThat(settings.getAsInt("index.merge.scheduler.max_merge_count", null), equalTo(maxMergeCount));
assertThat(settings.getAsInt("index.merge.scheduler.max_thread_count", null), equalTo(maxThreadCount));
assertNull(settings.get("index.non_copyable.existing"));
assertThat(settings.get("index.non_copyable.request"), equalTo("request"));
});
}
public void testPrepareResizeIndexSettingsAnalysisSettings() {
// analysis settings from the request are not overwritten
runPrepareResizeIndexSettingsTest(
Settings.EMPTY,
Settings.builder().put("index.analysis.analyzer.default.tokenizer", "whitespace").build(),
Collections.emptyList(),
randomBoolean(),
settings ->
assertThat(
"analysis settings are not overwritten",
settings.get("index.analysis.analyzer.default.tokenizer"),
equalTo("whitespace"))
);
}
public void testPrepareResizeIndexSettingsSimilaritySettings() {
// similarity settings from the request are not overwritten
runPrepareResizeIndexSettingsTest(
Settings.EMPTY,
Settings.builder().put("index.similarity.sim.type", "DFR").build(),
Collections.emptyList(),
randomBoolean(),
settings ->
assertThat("similarity settings are not overwritten", settings.get("index.similarity.sim.type"), equalTo("DFR")));
}
public void testDoNotOverrideSoftDeletesSettingOnResize() {
runPrepareResizeIndexSettingsTest(
Settings.builder().put("index.soft_deletes.enabled", "false").build(),
Settings.builder().put("index.soft_deletes.enabled", "true").build(),
Collections.emptyList(),
randomBoolean(),
settings -> assertThat(settings.get("index.soft_deletes.enabled"), equalTo("true")));
}
private void runPrepareResizeIndexSettingsTest(
final Settings sourceSettings,
final Settings requestSettings,
final Collection<Setting<?>> additionalIndexScopedSettings,
final boolean copySettings,
final Consumer<Settings> consumer) {
final String indexName = randomAlphaOfLength(10);
final Settings indexSettings = Settings.builder()
.put("index.blocks.write", true)
.put("index.routing.allocation.require._name", "node1")
.put(sourceSettings)
.build();
final ClusterState initialClusterState =
ClusterState
.builder(createClusterState(indexName, randomIntBetween(2, 10), 0, indexSettings))
.nodes(DiscoveryNodes.builder().add(newNode("node1")))
.build();
final AllocationService service = new AllocationService(
new AllocationDeciders(Collections.singleton(new MaxRetryAllocationDecider())),
new TestGatewayAllocator(),
new BalancedShardsAllocator(Settings.EMPTY),
EmptyClusterInfoService.INSTANCE);
final RoutingTable initialRoutingTable = service.reroute(initialClusterState, "reroute").routingTable();
final ClusterState routingTableClusterState = ClusterState.builder(initialClusterState).routingTable(initialRoutingTable).build();
// now we start the shard
final RoutingTable routingTable
= ESAllocationTestCase.startInitializingShardsAndReroute(service, routingTableClusterState, indexName).routingTable();
final ClusterState clusterState = ClusterState.builder(routingTableClusterState).routingTable(routingTable).build();
final Settings.Builder indexSettingsBuilder = Settings.builder().put("index.number_of_shards", 1).put(requestSettings);
final Set<Setting<?>> settingsSet =
Stream.concat(
IndexScopedSettings.BUILT_IN_INDEX_SETTINGS.stream(),
additionalIndexScopedSettings.stream())
.collect(Collectors.toSet());
MetadataCreateIndexService.prepareResizeIndexSettings(
clusterState,
Collections.emptySet(),
indexSettingsBuilder,
clusterState.metadata().index(indexName).getIndex(),
"target",
ResizeType.SHRINK,
copySettings,
new IndexScopedSettings(Settings.EMPTY, settingsSet));
consumer.accept(indexSettingsBuilder.build());
}
private DiscoveryNode newNode(String nodeId) {
return new DiscoveryNode(
nodeId,
buildNewFakeTransportAddress(),
emptyMap(),
Set.of(DiscoveryNodeRole.MASTER_ROLE, DiscoveryNodeRole.DATA_ROLE), Version.CURRENT);
}
public void testValidateIndexName() throws Exception {
withTemporaryClusterService(((clusterService, threadPool) -> {
MetadataCreateIndexService checkerService = new MetadataCreateIndexService(
Settings.EMPTY,
clusterService,
null,
null,
null,
createTestShardLimitService(randomIntBetween(1, 1000), clusterService), null,
null,
threadPool,
null,
Collections.emptyList(),
false
);
validateIndexName(checkerService, "index?name", "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS);
validateIndexName(checkerService, "index#name", "must not contain '#'");
validateIndexName(checkerService, "_indexname", "must not start with '_', '-', or '+'");
validateIndexName(checkerService, "-indexname", "must not start with '_', '-', or '+'");
validateIndexName(checkerService, "+indexname", "must not start with '_', '-', or '+'");
validateIndexName(checkerService, "INDEXNAME", "must be lowercase");
validateIndexName(checkerService, "..", "must not be '.' or '..'");
validateIndexName(checkerService, "foo:bar", "must not contain ':'");
}));
}
private void validateIndexName(MetadataCreateIndexService metadataCreateIndexService, String indexName, String errorMessage) {
InvalidIndexNameException e = expectThrows(InvalidIndexNameException.class,
() -> metadataCreateIndexService.validateIndexName(indexName, ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING
.getDefault(Settings.EMPTY)).build()));
assertThat(e.getMessage(), endsWith(errorMessage));
}
public void testCalculateNumRoutingShards() {
assertEquals(1024, MetadataCreateIndexService.calculateNumRoutingShards(1, Version.CURRENT));
assertEquals(1024, MetadataCreateIndexService.calculateNumRoutingShards(2, Version.CURRENT));
assertEquals(768, MetadataCreateIndexService.calculateNumRoutingShards(3, Version.CURRENT));
assertEquals(576, MetadataCreateIndexService.calculateNumRoutingShards(9, Version.CURRENT));
assertEquals(1024, MetadataCreateIndexService.calculateNumRoutingShards(512, Version.CURRENT));
assertEquals(2048, MetadataCreateIndexService.calculateNumRoutingShards(1024, Version.CURRENT));
assertEquals(4096, MetadataCreateIndexService.calculateNumRoutingShards(2048, Version.CURRENT));
for (int i = 0; i < 1000; i++) {
int randomNumShards = randomIntBetween(1, 10000);
int numRoutingShards = MetadataCreateIndexService.calculateNumRoutingShards(randomNumShards, Version.CURRENT);
if (numRoutingShards <= 1024) {
assertTrue("numShards: " + randomNumShards, randomNumShards < 513);
assertTrue("numRoutingShards: " + numRoutingShards, numRoutingShards > 512);
} else {
assertEquals("numShards: " + randomNumShards, numRoutingShards / 2, randomNumShards);
}
double ratio = numRoutingShards / randomNumShards;
int intRatio = (int) ratio;
assertEquals(ratio, intRatio, 0.0d);
assertTrue(1 < ratio);
assertTrue(ratio <= 1024);
assertEquals(0, intRatio % 2);
assertEquals("ratio is not a power of two", intRatio, Integer.highestOneBit(intRatio));
}
}
public void testValidateDotIndex() {
List<SystemIndexDescriptor> systemIndexDescriptors = new ArrayList<>();
systemIndexDescriptors.add(new SystemIndexDescriptor(".test", "test"));
systemIndexDescriptors.add(new SystemIndexDescriptor(".test3", "test"));
systemIndexDescriptors.add(new SystemIndexDescriptor(".pattern-test*", "test-1"));
systemIndexDescriptors.add(new SystemIndexDescriptor(".pattern-test-overlapping", "test-2"));
withTemporaryClusterService(((clusterService, threadPool) -> {
MetadataCreateIndexService checkerService = new MetadataCreateIndexService(
Settings.EMPTY,
clusterService,
null,
null,
null,
createTestShardLimitService(randomIntBetween(1, 1000), clusterService), null,
null,
threadPool,
null,
systemIndexDescriptors,
false
);
// Check deprecations
checkerService.validateDotIndex(".test2", ClusterState.EMPTY_STATE, false);
assertWarnings("index name [.test2] starts with a dot '.', in the next major version, index " +
"names starting with a dot are reserved for hidden indices and system indices");
// Check non-system hidden indices don't trigger a warning
checkerService.validateDotIndex(".test2", ClusterState.EMPTY_STATE, true);
// Check NO deprecation warnings if we give the index name
checkerService.validateDotIndex(".test", ClusterState.EMPTY_STATE, false);
checkerService.validateDotIndex(".test3", ClusterState.EMPTY_STATE, false);
// Check that patterns with wildcards work
checkerService.validateDotIndex(".pattern-test", ClusterState.EMPTY_STATE, false);
checkerService.validateDotIndex(".pattern-test-with-suffix", ClusterState.EMPTY_STATE, false);
checkerService.validateDotIndex(".pattern-test-other-suffix", ClusterState.EMPTY_STATE, false);
// Check that an exception is thrown if more than one descriptor matches the index name
AssertionError exception = expectThrows(AssertionError.class,
() -> checkerService.validateDotIndex(".pattern-test-overlapping", ClusterState.EMPTY_STATE, false));
assertThat(exception.getMessage(),
containsString("index name [.pattern-test-overlapping] is claimed as a system index by multiple system index patterns:"));
assertThat(exception.getMessage(), containsString("pattern: [.pattern-test*], description: [test-1]"));
assertThat(exception.getMessage(), containsString("pattern: [.pattern-test-overlapping], description: [test-2]"));
}));
}
public void testParseMappingsAppliesDataFromTemplateAndRequest() throws Exception {
IndexTemplateMetadata templateMetadata = addMatchingTemplate(templateBuilder -> {
templateBuilder.putAlias(AliasMetadata.builder("alias1"));
templateBuilder.putMapping("_doc", createMapping("mapping_from_template", "text"));
});
request.mappings(createMapping("mapping_from_request", "text").string());
Map<String, Object> parsedMappings = MetadataCreateIndexService.parseV1Mappings(request.mappings(),
List.of(templateMetadata.getMappings()), NamedXContentRegistry.EMPTY);
assertThat(parsedMappings, hasKey("_doc"));
Map<String, Object> doc = (Map<String, Object>) parsedMappings.get("_doc");
assertThat(doc, hasKey("properties"));
Map<String, Object> mappingsProperties = (Map<String, Object>) doc.get("properties");
assertThat(mappingsProperties, hasKey("mapping_from_request"));
assertThat(mappingsProperties, hasKey("mapping_from_template"));
}
public void testAggregateSettingsAppliesSettingsFromTemplatesAndRequest() {
IndexTemplateMetadata templateMetadata = addMatchingTemplate(builder -> {
builder.settings(Settings.builder().put("template_setting", "value1"));
});
ImmutableOpenMap.Builder<String, IndexTemplateMetadata> templatesBuilder = ImmutableOpenMap.builder();
templatesBuilder.put("template_1", templateMetadata);
Metadata metadata = new Metadata.Builder().templates(templatesBuilder.build()).build();
ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.CLUSTER_NAME_SETTING
.getDefault(Settings.EMPTY))
.metadata(metadata)
.build();
request.settings(Settings.builder().put("request_setting", "value2").build());
Settings aggregatedIndexSettings = aggregateIndexSettings(clusterState, request, templateMetadata.settings(), Map.of(),
null, Settings.EMPTY, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS, randomShardLimitService());
assertThat(aggregatedIndexSettings.get("template_setting"), equalTo("value1"));
assertThat(aggregatedIndexSettings.get("request_setting"), equalTo("value2"));
}
public void testInvalidAliasName() {
final String[] invalidAliasNames = new String[] { "-alias1", "+alias2", "_alias3", "a#lias", "al:ias", ".", ".." };
String aliasName = randomFrom(invalidAliasNames);
request.aliases(Set.of(new Alias(aliasName)));
expectThrows(InvalidAliasNameException.class, () ->
resolveAndValidateAliases(request.index(), request.aliases(), List.of(), Metadata.builder().build(),
aliasValidator, xContentRegistry(), queryShardContext)
);
}
public void testRequestDataHavePriorityOverTemplateData() throws Exception {
CompressedXContent templateMapping = createMapping("test", "text");
CompressedXContent reqMapping = createMapping("test", "keyword");
IndexTemplateMetadata templateMetadata = addMatchingTemplate(builder -> builder
.putAlias(AliasMetadata.builder("alias").searchRouting("fromTemplate").build())
.putMapping("_doc", templateMapping)
.settings(Settings.builder().put("key1", "templateValue"))
);
request.mappings(reqMapping.string());
request.aliases(Set.of(new Alias("alias").searchRouting("fromRequest")));
request.settings(Settings.builder().put("key1", "requestValue").build());
Map<String, Object> parsedMappings = MetadataCreateIndexService.parseV1Mappings(request.mappings(),
List.of(templateMetadata.mappings()), xContentRegistry());
List<AliasMetadata> resolvedAliases = resolveAndValidateAliases(request.index(), request.aliases(),
MetadataIndexTemplateService.resolveAliases(List.of(templateMetadata)),
Metadata.builder().build(), aliasValidator, xContentRegistry(), queryShardContext);
Settings aggregatedIndexSettings = aggregateIndexSettings(ClusterState.EMPTY_STATE, request, templateMetadata.settings(), Map.of(),
null, Settings.EMPTY, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS, randomShardLimitService());
assertThat(resolvedAliases.get(0).getSearchRouting(), equalTo("fromRequest"));
assertThat(aggregatedIndexSettings.get("key1"), equalTo("requestValue"));
assertThat(parsedMappings, hasKey("_doc"));
Map<String, Object> doc = (Map<String, Object>) parsedMappings.get("_doc");
assertThat(doc, hasKey("properties"));
Map<String, Object> mappingsProperties = (Map<String, Object>) doc.get("properties");
assertThat(mappingsProperties, hasKey("test"));
assertThat((Map<String, Object>) mappingsProperties.get("test"), hasValue("keyword"));
}
public void testDefaultSettings() {
Settings aggregatedIndexSettings = aggregateIndexSettings(ClusterState.EMPTY_STATE, request, Settings.EMPTY, Map.of(),
null, Settings.EMPTY, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS, randomShardLimitService());
assertThat(aggregatedIndexSettings.get(SETTING_NUMBER_OF_SHARDS), equalTo("1"));
}
public void testSettingsFromClusterState() {
Settings aggregatedIndexSettings = aggregateIndexSettings(ClusterState.EMPTY_STATE, request, Settings.EMPTY, Map.of(),
null, Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 15).build(), IndexScopedSettings.DEFAULT_SCOPED_SETTINGS,
randomShardLimitService());
assertThat(aggregatedIndexSettings.get(SETTING_NUMBER_OF_SHARDS), equalTo("15"));
}
public void testTemplateOrder() throws Exception {
List<IndexTemplateMetadata> templates = new ArrayList<>(3);
templates.add(addMatchingTemplate(builder -> builder
.order(3)
.settings(Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 12))
.putAlias(AliasMetadata.builder("alias1").writeIndex(true).searchRouting("3").build())
));
templates.add(addMatchingTemplate(builder -> builder
.order(2)
.settings(Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 11))
.putAlias(AliasMetadata.builder("alias1").searchRouting("2").build())
));
templates.add(addMatchingTemplate(builder -> builder
.order(1)
.settings(Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 10))
.putAlias(AliasMetadata.builder("alias1").searchRouting("1").build())
));
Settings aggregatedIndexSettings = aggregateIndexSettings(ClusterState.EMPTY_STATE, request,
MetadataIndexTemplateService.resolveSettings(templates), Map.of(),
null, Settings.EMPTY, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS, randomShardLimitService());
List<AliasMetadata> resolvedAliases = resolveAndValidateAliases(request.index(), request.aliases(),
MetadataIndexTemplateService.resolveAliases(templates),
Metadata.builder().build(), aliasValidator, xContentRegistry(), queryShardContext);
assertThat(aggregatedIndexSettings.get(SETTING_NUMBER_OF_SHARDS), equalTo("12"));
AliasMetadata alias = resolvedAliases.get(0);
assertThat(alias.getSearchRouting(), equalTo("3"));
assertThat(alias.writeIndex(), is(true));
}
public void testAggregateIndexSettingsIgnoresTemplatesOnCreateFromSourceIndex() throws Exception {
CompressedXContent templateMapping = createMapping("test", "text");
IndexTemplateMetadata templateMetadata = addMatchingTemplate(builder -> builder
.putAlias(AliasMetadata.builder("alias").searchRouting("fromTemplate").build())
.putMapping("_doc", templateMapping)
.settings(Settings.builder().put("templateSetting", "templateValue"))
);
request.settings(Settings.builder().put("requestSetting", "requestValue").build());
request.resizeType(ResizeType.SPLIT);
request.recoverFrom(new Index("sourceIndex", UUID.randomUUID().toString()));
ClusterState clusterState =
createClusterState("sourceIndex", 1, 0,
Settings.builder().put("index.blocks.write", true).build());
Settings aggregatedIndexSettings = aggregateIndexSettings(clusterState, request, templateMetadata.settings(), Map.of(),
clusterState.metadata().index("sourceIndex"), Settings.EMPTY, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS,
randomShardLimitService());
assertThat(aggregatedIndexSettings.get("templateSetting"), is(nullValue()));
assertThat(aggregatedIndexSettings.get("requestSetting"), is("requestValue"));
}
public void testClusterStateCreateIndexThrowsWriteIndexValidationException() throws Exception {
IndexMetadata existingWriteIndex = IndexMetadata.builder("test2")
.settings(settings(Version.CURRENT)).putAlias(AliasMetadata.builder("alias1").writeIndex(true).build())
.numberOfShards(1).numberOfReplicas(0).build();
ClusterState currentClusterState =
ClusterState.builder(ClusterState.EMPTY_STATE).metadata(Metadata.builder().put(existingWriteIndex, false).build()).build();
IndexMetadata newIndex = IndexMetadata.builder("test")
.settings(settings(Version.CURRENT))
.numberOfShards(1)
.numberOfReplicas(0)
.putAlias(AliasMetadata.builder("alias1").writeIndex(true).build())
.build();
assertThat(
expectThrows(IllegalStateException.class,
() -> clusterStateCreateIndex(currentClusterState, Set.of(), newIndex, (state, reason) -> state, null)).getMessage(),
startsWith("alias [alias1] has more than one write index [")
);
}
public void testClusterStateCreateIndex() {
ClusterState currentClusterState =
ClusterState.builder(ClusterState.EMPTY_STATE).build();
IndexMetadata newIndexMetadata = IndexMetadata.builder("test")
.settings(settings(Version.CURRENT).put(SETTING_READ_ONLY, true))
.numberOfShards(1)
.numberOfReplicas(0)
.putAlias(AliasMetadata.builder("alias1").writeIndex(true).build())
.build();
// used as a value container, not for the concurrency and visibility guarantees
AtomicBoolean allocationRerouted = new AtomicBoolean(false);
BiFunction<ClusterState, String, ClusterState> rerouteRoutingTable = (clusterState, reason) -> {
allocationRerouted.compareAndSet(false, true);
return clusterState;
};
ClusterState updatedClusterState = clusterStateCreateIndex(currentClusterState, Set.of(INDEX_READ_ONLY_BLOCK), newIndexMetadata,
rerouteRoutingTable, null);
assertThat(updatedClusterState.blocks().getIndexBlockWithId("test", INDEX_READ_ONLY_BLOCK.id()), is(INDEX_READ_ONLY_BLOCK));
assertThat(updatedClusterState.routingTable().index("test"), is(notNullValue()));
assertThat(allocationRerouted.get(), is(true));
}
public void testClusterStateCreateIndexWithMetadataTransaction() {
ClusterState currentClusterState = ClusterState.builder(ClusterState.EMPTY_STATE)
.metadata(Metadata.builder()
.put(IndexMetadata.builder("my-index")
.settings(settings(Version.CURRENT).put(SETTING_READ_ONLY, true))
.numberOfShards(1)
.numberOfReplicas(0)))
.build();
IndexMetadata newIndexMetadata = IndexMetadata.builder("test")
.settings(settings(Version.CURRENT).put(SETTING_READ_ONLY, true))
.numberOfShards(1)
.numberOfReplicas(0)
.putAlias(AliasMetadata.builder("alias1").writeIndex(true).build())
.build();
// adds alias from new index to existing index
BiConsumer<Metadata.Builder, IndexMetadata> metadataTransformer = (builder, indexMetadata) -> {
AliasMetadata newAlias = indexMetadata.getAliases().iterator().next().value;
IndexMetadata myIndex = builder.get("my-index");
builder.put(IndexMetadata.builder(myIndex).putAlias(AliasMetadata.builder(newAlias.getAlias()).build()));
};
ClusterState updatedClusterState = clusterStateCreateIndex(currentClusterState, Set.of(INDEX_READ_ONLY_BLOCK), newIndexMetadata,
(clusterState, y) -> clusterState, metadataTransformer);
assertTrue(updatedClusterState.metadata().findAllAliases(new String[]{"my-index"}).containsKey("my-index"));
assertNotNull(updatedClusterState.metadata().findAllAliases(new String[]{"my-index"}).get("my-index"));
assertNotNull(updatedClusterState.metadata().findAllAliases(new String[]{"my-index"}).get("my-index").get(0).alias(),
equalTo("alias1"));
}
public void testParseMappingsWithTypedTemplateAndTypelessIndexMapping() throws Exception {
IndexTemplateMetadata templateMetadata = addMatchingTemplate(builder -> {
try {
builder.putMapping("type", "{\"type\": {}}");
} catch (IOException e) {
ExceptionsHelper.reThrowIfNotNull(e);
}
});
Map<String, Object> mappings = parseV1Mappings("{\"_doc\":{}}", List.of(templateMetadata.mappings()), xContentRegistry());
assertThat(mappings, Matchers.hasKey(MapperService.SINGLE_MAPPING_NAME));
}
public void testParseMappingsWithTypedTemplate() throws Exception {
IndexTemplateMetadata templateMetadata = addMatchingTemplate(builder -> {
try {
builder.putMapping("type",
"{\"type\":{\"properties\":{\"field\":{\"type\":\"keyword\"}}}}");
} catch (IOException e) {
ExceptionsHelper.reThrowIfNotNull(e);
}
});
Map<String, Object> mappings = parseV1Mappings("", List.of(templateMetadata.mappings()), xContentRegistry());
assertThat(mappings, Matchers.hasKey(MapperService.SINGLE_MAPPING_NAME));
}
public void testParseMappingsWithTypelessTemplate() throws Exception {
IndexTemplateMetadata templateMetadata = addMatchingTemplate(builder -> {
try {
builder.putMapping(MapperService.SINGLE_MAPPING_NAME, "{\"_doc\": {}}");
} catch (IOException e) {
ExceptionsHelper.reThrowIfNotNull(e);
}
});
Map<String, Object> mappings = parseV1Mappings("", List.of(templateMetadata.mappings()), xContentRegistry());
assertThat(mappings, Matchers.hasKey(MapperService.SINGLE_MAPPING_NAME));
}
public void testBuildIndexMetadata() {
IndexMetadata sourceIndexMetadata = IndexMetadata.builder("parent")
.settings(Settings.builder()
.put("index.version.created", Version.CURRENT)
.build())
.numberOfShards(1)
.numberOfReplicas(0)
.primaryTerm(0, 3L)
.build();
Settings indexSettings = Settings.builder()
.put("index.version.created", Version.CURRENT)
.put(SETTING_NUMBER_OF_REPLICAS, 0)
.put(SETTING_NUMBER_OF_SHARDS, 1)
.build();
List<AliasMetadata> aliases = List.of(AliasMetadata.builder("alias1").build());
IndexMetadata indexMetadata = buildIndexMetadata("test", aliases, () -> null, indexSettings, 4, sourceIndexMetadata);
assertThat(indexMetadata.getAliases().size(), is(1));
assertThat(indexMetadata.getAliases().keys().iterator().next().value, is("alias1"));
assertThat("The source index primary term must be used", indexMetadata.primaryTerm(0), is(3L));
}
public void testGetIndexNumberOfRoutingShardsWithNullSourceIndex() {
Settings indexSettings = Settings.builder()
.put("index.version.created", Version.CURRENT)
.put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 3)
.build();
int targetRoutingNumberOfShards = getIndexNumberOfRoutingShards(indexSettings, null);
assertThat("When the target routing number of shards is not specified the expected value is the configured number of shards " +
"multiplied by 2 at most ten times (ie. 3 * 2^8)", targetRoutingNumberOfShards, is(768));
}
public void testGetIndexNumberOfRoutingShardsWhenExplicitlyConfigured() {
Settings indexSettings = Settings.builder()
.put(INDEX_NUMBER_OF_ROUTING_SHARDS_SETTING.getKey(), 9)
.put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 3)
.build();
int targetRoutingNumberOfShards = getIndexNumberOfRoutingShards(indexSettings, null);
assertThat(targetRoutingNumberOfShards, is(9));
}
public void testGetIndexNumberOfRoutingShardsYieldsSourceNumberOfShards() {
Settings indexSettings = Settings.builder()
.put(INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 3)
.build();
IndexMetadata sourceIndexMetadata = IndexMetadata.builder("parent")
.settings(Settings.builder()
.put("index.version.created", Version.CURRENT)
.build())
.numberOfShards(6)
.numberOfReplicas(0)
.build();
int targetRoutingNumberOfShards = getIndexNumberOfRoutingShards(indexSettings, sourceIndexMetadata);
assertThat(targetRoutingNumberOfShards, is(6));
}
public void testRejectWithSoftDeletesDisabled() {
final IllegalArgumentException error = expectThrows(IllegalArgumentException.class, () -> {
request = new CreateIndexClusterStateUpdateRequest("create index", "test", "test");
request.settings(Settings.builder().put(INDEX_SOFT_DELETES_SETTING.getKey(), false).build());
aggregateIndexSettings(ClusterState.EMPTY_STATE, request, Settings.EMPTY, Map.of(),
null, Settings.EMPTY, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS, randomShardLimitService());
});
assertThat(error.getMessage(), equalTo("Creating indices with soft-deletes disabled is no longer supported. "
+ "Please do not specify a value for setting [index.soft_deletes.enabled]."));
}
public void testRejectTranslogRetentionSettings() {
request = new CreateIndexClusterStateUpdateRequest("create index", "test", "test");
final Settings.Builder settings = Settings.builder();
if (randomBoolean()) {
settings.put(IndexSettings.INDEX_TRANSLOG_RETENTION_AGE_SETTING.getKey(), TimeValue.timeValueMillis(between(1, 120)));
} else {
settings.put(IndexSettings.INDEX_TRANSLOG_RETENTION_SIZE_SETTING.getKey(), between(1, 128) + "mb");
}
if (randomBoolean()) {
settings.put(SETTING_INDEX_VERSION_CREATED.getKey(),
VersionUtils.randomVersionBetween(random(), Version.V_8_0_0, Version.CURRENT));
}
request.settings(settings.build());
IllegalArgumentException error = expectThrows(IllegalArgumentException.class,
() -> aggregateIndexSettings(ClusterState.EMPTY_STATE, request, Settings.EMPTY, Map.of(),
null, Settings.EMPTY, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS, randomShardLimitService()));
assertThat(error.getMessage(), equalTo("Translog retention settings [index.translog.retention.age] " +
"and [index.translog.retention.size] are no longer supported. Please do not specify values for these settings"));
}
public void testDeprecateTranslogRetentionSettings() {
request = new CreateIndexClusterStateUpdateRequest("create index", "test", "test");
final Settings.Builder settings = Settings.builder();
if (randomBoolean()) {
settings.put(IndexSettings.INDEX_TRANSLOG_RETENTION_AGE_SETTING.getKey(), TimeValue.timeValueMillis(between(1, 120)));
} else {
settings.put(IndexSettings.INDEX_TRANSLOG_RETENTION_SIZE_SETTING.getKey(), between(1, 128) + "mb");
}
settings.put(SETTING_INDEX_VERSION_CREATED.getKey(), VersionUtils.randomPreviousCompatibleVersion(random(), Version.V_8_0_0));
request.settings(settings.build());
aggregateIndexSettings(ClusterState.EMPTY_STATE, request, Settings.EMPTY, Map.of(),
null, Settings.EMPTY, IndexScopedSettings.DEFAULT_SCOPED_SETTINGS, randomShardLimitService());
assertWarnings("Translog retention settings [index.translog.retention.age] "
+ "and [index.translog.retention.size] are deprecated and effectively ignored. They will be removed in a future version.");
}
@SuppressWarnings("unchecked")
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/pull/57393")
public void testMappingsMergingIsSmart() throws Exception {
Template ctt1 = new Template(null,
new CompressedXContent("{\"_doc\":{\"_source\":{\"enabled\": false},\"_meta\":{\"ct1\":{\"ver\": \"text\"}}," +
"\"properties\":{\"foo\":{\"type\":\"text\",\"ignore_above\":7,\"analyzer\":\"english\"}}}}"), null);
Template ctt2 = new Template(null,
new CompressedXContent("{\"_doc\":{\"_meta\":{\"ct1\":{\"ver\": \"keyword\"},\"ct2\":\"potato\"}," +
"\"properties\":{\"foo\":{\"type\":\"keyword\",\"ignore_above\":13}}}}"), null);
ComponentTemplate ct1 = new ComponentTemplate(ctt1, null, null);
ComponentTemplate ct2 = new ComponentTemplate(ctt2, null, null);
boolean shouldBeText = randomBoolean();
List<String> composedOf = shouldBeText ? Arrays.asList("ct2", "ct1") : Arrays.asList("ct1", "ct2");
logger.info("--> the {} analyzer should win ({})", shouldBeText ? "text" : "keyword", composedOf);
ComposableIndexTemplate template = new ComposableIndexTemplate(Collections.singletonList("index"),
null, composedOf, null, null, null, null);
ClusterState state = ClusterState.builder(ClusterState.EMPTY_STATE)
.metadata(Metadata.builder(Metadata.EMPTY_METADATA)
.put("ct1", ct1)
.put("ct2", ct2)
.put("index-template", template)
.build())
.build();
Map<String, Object> resolved =
MetadataCreateIndexService.resolveV2Mappings("{\"_doc\":{\"_meta\":{\"ct2\":\"eggplant\"}," +
"\"properties\":{\"bar\":{\"type\":\"text\"}}}}", state,
"index-template", new NamedXContentRegistry(Collections.emptyList()));
assertThat("expected exactly one type but was: " + resolved, resolved.size(), equalTo(1));
Map<String, Object> innerResolved = (Map<String, Object>) resolved.get(MapperService.SINGLE_MAPPING_NAME);
assertThat("was: " + innerResolved, innerResolved.size(), equalTo(3));
Map<String, Object> nonProperties = new HashMap<>(innerResolved);
nonProperties.remove("properties");
Map<String, Object> expectedNonProperties = new HashMap<>();
expectedNonProperties.put("_source", Collections.singletonMap("enabled", false));
Map<String, Object> meta = new HashMap<>();
meta.put("ct2", "eggplant");
if (shouldBeText) {
meta.put("ct1", Collections.singletonMap("ver", "text"));
} else {
meta.put("ct1", Collections.singletonMap("ver", "keyword"));
}
expectedNonProperties.put("_meta", meta);
assertThat(nonProperties, equalTo(expectedNonProperties));
Map<String, Object> innerInnerResolved = (Map<String, Object>) innerResolved.get("properties");
assertThat(innerInnerResolved.size(), equalTo(2));
assertThat(innerInnerResolved.get("bar"), equalTo(Collections.singletonMap("type", "text")));
Map<String, Object> fooMappings = new HashMap<>();
if (shouldBeText) {
fooMappings.put("type", "text");
fooMappings.put("ignore_above", 7);
fooMappings.put("analyzer", "english");
} else {
fooMappings.put("type", "keyword");
fooMappings.put("ignore_above", 13);
}
assertThat(innerInnerResolved.get("foo"), equalTo(fooMappings));
}
@SuppressWarnings("unchecked")
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/pull/57393")
public void testMappingsMergingHandlesDots() throws Exception {
Template ctt1 = new Template(null,
new CompressedXContent("{\"_doc\":{\"properties\":{\"foo\":{\"properties\":{\"bar\":{\"type\": \"long\"}}}}}}"), null);
Template ctt2 = new Template(null,
new CompressedXContent("{\"_doc\":{\"properties\":{\"foo.bar\":{\"type\": \"text\",\"analyzer\":\"english\"}}}}"), null);
ComponentTemplate ct1 = new ComponentTemplate(ctt1, null, null);
ComponentTemplate ct2 = new ComponentTemplate(ctt2, null, null);
ComposableIndexTemplate template = new ComposableIndexTemplate(Collections.singletonList("index"),
null, Arrays.asList("ct2", "ct1"), null, null, null, null);
ClusterState state = ClusterState.builder(ClusterState.EMPTY_STATE)
.metadata(Metadata.builder(Metadata.EMPTY_METADATA)
.put("ct1", ct1)
.put("ct2", ct2)
.put("index-template", template)
.build())
.build();
Map<String, Object> resolved =
MetadataCreateIndexService.resolveV2Mappings("{}", state,
"index-template", new NamedXContentRegistry(Collections.emptyList()));
assertThat("expected exactly one type but was: " + resolved, resolved.size(), equalTo(1));
Map<String, Object> innerResolved = (Map<String, Object>) resolved.get(MapperService.SINGLE_MAPPING_NAME);
assertThat("was: " + innerResolved, innerResolved.size(), equalTo(1));
Map<String, Object> innerInnerResolved = (Map<String, Object>) innerResolved.get("properties");
assertThat(innerInnerResolved.size(), equalTo(1));
assertThat(innerInnerResolved.get("foo"),
equalTo(Collections.singletonMap("properties", Collections.singletonMap("bar", Collections.singletonMap("type", "long")))));
}
public void testMappingsMergingThrowsOnConflictDots() throws Exception {
Template ctt1 = new Template(null,
new CompressedXContent("{\"_doc\":{\"properties\":{\"foo\":{\"properties\":{\"bar\":{\"type\": \"long\"}}}}}}"), null);
Template ctt2 = new Template(null,
new CompressedXContent("{\"_doc\":{\"properties\":{\"foo.bar\":{\"type\": \"text\",\"analyzer\":\"english\"}}}}"), null);
ComponentTemplate ct1 = new ComponentTemplate(ctt1, null, null);
ComponentTemplate ct2 = new ComponentTemplate(ctt2, null, null);
ComposableIndexTemplate template = new ComposableIndexTemplate(Collections.singletonList("index"),
null, Arrays.asList("ct2", "ct1"), null, null, null, null);
ClusterState state = ClusterState.builder(ClusterState.EMPTY_STATE)
.metadata(Metadata.builder(Metadata.EMPTY_METADATA)
.put("ct1", ct1)
.put("ct2", ct2)
.put("index-template", template)
.build())
.build();
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> MetadataCreateIndexService.resolveV2Mappings("{}", state,
"index-template", new NamedXContentRegistry(Collections.emptyList())));
assertThat(e.getMessage(), containsString("mapping fields [foo.bar] cannot be replaced during template composition"));
}
@SuppressWarnings("unchecked")
public void testDedupTemplateDynamicTemplates() throws Exception {
Template template = new Template(null,
new CompressedXContent("{\"_doc\":{\"_source\":{\"enabled\": false}, \"dynamic_templates\": [" +
"{\n" +
" \"docker.container.labels\": {\n" +
" \"mapping\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"match_mapping_type\": \"string\",\n" +
" \"path_match\": \"labels.*\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"docker.container.labels\": {\n" +
" \"mapping\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"match_mapping_type\": \"string\",\n" +
" \"path_match\": \"docker.container.labels.*\"\n" +
" }\n" +
"}]}}"), null);
ComposableIndexTemplate indexTemplate = new ComposableIndexTemplate(Collections.singletonList("index"),
template, null, null, null, null);
ClusterState state = ClusterState.builder(ClusterState.EMPTY_STATE)
.metadata(Metadata.builder(Metadata.EMPTY_METADATA)
.put("index-template", indexTemplate)
.build())
.build();
Map<String, Object> resolved =
MetadataCreateIndexService.resolveV2Mappings("{}", state,
"index-template", new NamedXContentRegistry(Collections.emptyList()));
Map<String, Object> doc = (Map<String, Object>) resolved.get(MapperService.SINGLE_MAPPING_NAME);
List<Map<String, Object>> dynamicTemplates = (List<Map<String, Object>>) doc.get("dynamic_templates");
assertThat(dynamicTemplates.size(), is(1));
Map<String, Object> dynamicMapping = (Map<String, Object>) dynamicTemplates.get(0).get("docker.container.labels");
assertThat(dynamicMapping, is(notNullValue()));
assertThat("last mapping with the same name must override previously defined mappings with the same name",
dynamicMapping.get("path_match"), is("docker.container.labels.*"));
}
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/pull/57393")
public void testDedupRequestDynamicTemplates() throws Exception {
String requestMappingJson = "{\"_doc\":{\"_source\":{\"enabled\": false}, \"dynamic_templates\": [" +
"{\n" +
" \"docker.container.labels\": {\n" +
" \"mapping\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"match_mapping_type\": \"string\",\n" +
" \"path_match\": \"labels.*\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"docker.container.labels\": {\n" +
" \"mapping\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"match_mapping_type\": \"string\",\n" +
" \"path_match\": \"source.request.*\"\n" +
" }\n" +
"}]}}";
String templateMappingJson = "{\"_doc\":{\"_source\":{\"enabled\": false}, \"dynamic_templates\": [" +
"{\n" +
" \"docker.container.labels\": {\n" +
" \"mapping\": {\n" +
" \"type\": \"text\",\n" +
" \"copy_to\": \"text_labels\"\n" +
" },\n" +
" \"match_mapping_type\": \"string\",\n" +
" \"path_match\": \"source.template.*\"\n" +
" }\n" +
" }\n" +
"]}}";
Template template = new Template(null, new CompressedXContent(templateMappingJson), null);
ComposableIndexTemplate indexTemplate = new ComposableIndexTemplate(Collections.singletonList("index"),
template, null, null, null, null);
ClusterState state = ClusterState.builder(ClusterState.EMPTY_STATE)
.metadata(Metadata.builder(Metadata.EMPTY_METADATA)
.put("index-template", indexTemplate)
.build())
.build();
Map<String, Object> resolved =
MetadataCreateIndexService.resolveV2Mappings(requestMappingJson, state,
"index-template", new NamedXContentRegistry(Collections.emptyList()));
Map<String, Object> doc = (Map<String, Object>) resolved.get(MapperService.SINGLE_MAPPING_NAME);
List<Map<String, Object>> dynamicTemplates = (List<Map<String, Object>>) doc.get("dynamic_templates");
assertThat(dynamicTemplates.size(), is(1));
Map<String, Object> dynamicMapping = (Map<String, Object>) dynamicTemplates.get(0).get("docker.container.labels");
assertThat(dynamicMapping, is(notNullValue()));
assertThat("last mapping with the same name must override previously defined mappings with the same name",
dynamicMapping.get("path_match"), is("source.request.*"));
Map<String, Object> mapping = (Map<String, Object>) dynamicMapping.get("mapping");
assertThat("the dynamic template defined in the request must not be merged with the dynamic template with the " +
"same name defined in the index template", mapping.size(), is(1));
assertThat(mapping.get("type"), is("keyword"));
}
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/pull/57393")
public void testMultipleComponentTemplatesDefineSameDynamicTemplate() throws Exception {
String ct1Mapping = "{\"_doc\":{\"_source\":{\"enabled\": false}, \"dynamic_templates\": [" +
"{\n" +
" \"docker.container.labels\": {\n" +
" \"mapping\": {\n" +
" \"type\": \"text\",\n" +
" \"copy_to\": \"text_labels\"\n" +
" },\n" +
" \"match_mapping_type\": \"string\",\n" +
" \"path_match\": \"source.first.ct.*\"\n" +
" }\n" +
" },\n" +
"{\n" +
" \"other.labels\": {\n" +
" \"mapping\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"match_mapping_type\": \"string\",\n" +
" \"path_match\": \"source.first.ct.other.labels*\"\n" +
" }\n" +
" }\n" +
"]}}";
String ct2Mapping = "{\"_doc\":{\"_source\":{\"enabled\": false}, \"dynamic_templates\": [" +
"{\n" +
" \"docker.container.labels\": {\n" +
" \"mapping\": {\n" +
" \"type\": \"keyword\"\n" +
" },\n" +
" \"match_mapping_type\": \"string\",\n" +
" \"path_match\": \"source.second.ct.*\"\n" +
" }\n" +
" }\n" +
"]}}";
Template ctt1 = new Template(null, new CompressedXContent(ct1Mapping), null);
Template ctt2 = new Template(null, new CompressedXContent(ct2Mapping), null);
ComponentTemplate ct1 = new ComponentTemplate(ctt1, null, null);
ComponentTemplate ct2 = new ComponentTemplate(ctt2, null, null);
ComposableIndexTemplate template = new ComposableIndexTemplate(Collections.singletonList("index"),
null, Arrays.asList("ct1", "ct2"), null, null, null);
ClusterState state = ClusterState.builder(ClusterState.EMPTY_STATE)
.metadata(Metadata.builder(Metadata.EMPTY_METADATA)
.put("ct1", ct1)
.put("ct2", ct2)
.put("index-template", template)
.build())
.build();
Map<String, Object> resolved =
MetadataCreateIndexService.resolveV2Mappings("{}", state,
"index-template", new NamedXContentRegistry(Collections.emptyList()));
Map<String, Object> doc = (Map<String, Object>) resolved.get(MapperService.SINGLE_MAPPING_NAME);
List<Map<String, Object>> dynamicTemplates = (List<Map<String, Object>>) doc.get("dynamic_templates");
assertThat(dynamicTemplates.size(), is(2));
Map<String, Object> dockerLabelsDynamicTemplate = dynamicTemplates.get(0).get("docker.container.labels") != null ?
dynamicTemplates.get(0) : dynamicTemplates.get(1);
Map<String, Object> dynamicMapping = (Map<String, Object>) dockerLabelsDynamicTemplate.get("docker.container.labels");
assertThat(dynamicMapping, is(notNullValue()));
assertThat("dynamic template defined in the last defined component template must override the previously defined dynamic templates",
dynamicMapping.get("path_match"), is("source.second.ct.*"));
Map<String, Object> mapping = (Map<String, Object>) dynamicMapping.get("mapping");
assertThat("the dynamic template defined in the second component template must not be merged with the dynamic template with the " +
"same name defined in the first component template", mapping.size(), is(1));
assertThat(mapping.get("type"), is("keyword"));
}
private IndexTemplateMetadata addMatchingTemplate(Consumer<IndexTemplateMetadata.Builder> configurator) {
IndexTemplateMetadata.Builder builder = templateMetadataBuilder("template1", "te*");
configurator.accept(builder);
return builder.build();
}
private IndexTemplateMetadata.Builder templateMetadataBuilder(String name, String pattern) {
return IndexTemplateMetadata
.builder(name)
.patterns(Collections.singletonList(pattern));
}
private CompressedXContent createMapping(String fieldName, String fieldType) {
try {
final String mapping = Strings.toString(XContentFactory.jsonBuilder()
.startObject()
.startObject("_doc")
.startObject("properties")
.startObject(fieldName)
.field("type", fieldType)
.endObject()
.endObject()
.endObject()
.endObject());
return new CompressedXContent(mapping);
} catch (IOException e) {
throw ExceptionsHelper.convertToRuntime(e);
}
}
private ShardLimitValidator randomShardLimitService() {
return createTestShardLimitService(randomIntBetween(10,10000));
}
private void withTemporaryClusterService(BiConsumer<ClusterService, ThreadPool> consumer) {
ThreadPool threadPool = new TestThreadPool(getTestName());
try {
final ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool);
consumer.accept(clusterService, threadPool);
} finally {
threadPool.shutdown();
}
}
}
| |
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.am.gateway.handler.common.vertx.web.handler.impl;
import io.gravitee.am.gateway.handler.common.vertx.utils.RequestUtils;
import io.gravitee.am.gateway.handler.common.vertx.utils.UriBuilderRequest;
import io.vertx.core.http.Cookie;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.CSRFHandler;
import io.vertx.ext.web.handler.SessionHandler;
import io.vertx.reactivex.core.MultiMap;
import io.vertx.reactivex.core.http.HttpServerRequest;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static io.vertx.core.http.HttpMethod.*;
/**
* Override default Vert.x CSRFHandler to enhance routing context with CSRF values to fill in the right value for the form fields.
*
* @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
public class CSRFHandlerImpl implements CSRFHandler {
private static final Logger log = LoggerFactory.getLogger(io.vertx.ext.web.handler.impl.CSRFHandlerImpl.class);
private static final Base64.Encoder BASE64 = Base64.getMimeEncoder();
private final Random RAND = new SecureRandom();
private final Mac mac;
private boolean nagHttps;
private String cookieName = DEFAULT_COOKIE_NAME;
private String cookiePath = DEFAULT_COOKIE_PATH;
private String headerName = DEFAULT_HEADER_NAME;
private long timeout = SessionHandler.DEFAULT_SESSION_TIMEOUT;
private String origin;
private boolean httpOnly;
public CSRFHandlerImpl(final String secret) {
try {
mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256"));
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException(e);
}
}
@Override
public CSRFHandler setOrigin(String origin) {
this.origin = origin;
return this;
}
@Override
public CSRFHandler setCookieName(String cookieName) {
this.cookieName = cookieName;
return this;
}
@Override
public CSRFHandler setCookiePath(String cookiePath) {
this.cookiePath = cookiePath;
return this;
}
@Override
public CSRFHandler setCookieHttpOnly(boolean httpOnly) {
this.httpOnly = httpOnly;
return this;
}
@Override
public CSRFHandler setHeaderName(String headerName) {
this.headerName = headerName;
return this;
}
@Override
public CSRFHandler setTimeout(long timeout) {
this.timeout = timeout;
return this;
}
@Override
public CSRFHandler setNagHttps(boolean nag) {
this.nagHttps = nag;
return this;
}
private String generateToken() {
byte[] salt = new byte[32];
RAND.nextBytes(salt);
String saltPlusToken = BASE64.encodeToString(salt) + "." + Long.toString(System.currentTimeMillis());
String signature = BASE64.encodeToString(mac.doFinal(saltPlusToken.getBytes()));
return saltPlusToken + "." + signature;
}
private boolean validateToken(String header, Cookie cookie) {
// both the header and the cookie must be present, not null and equal
if (header == null || cookie == null || !header.equals(cookie.getValue())) {
return false;
}
String[] tokens = header.split("\\.");
if (tokens.length != 3) {
return false;
}
String saltPlusToken = tokens[0] + "." + tokens[1];
String signature = BASE64.encodeToString(mac.doFinal(saltPlusToken.getBytes()));
if (!signature.equals(tokens[2])) {
return false;
}
try {
// validate validity
return !(System.currentTimeMillis() > Long.parseLong(tokens[1]) + timeout);
} catch (NumberFormatException e) {
return false;
}
}
protected void redirect(RoutingContext ctx) {
final int statusCode = 302;
final HttpServerRequest httpServerRequest = new HttpServerRequest(ctx.request());
final MultiMap queryParams = RequestUtils.getCleanedQueryParams(httpServerRequest);
queryParams.set("error", "session_expired");
queryParams.set("error_description", "Your session expired, please try again.");
final String uri = UriBuilderRequest.resolveProxyRequest(httpServerRequest, ctx.request().path(), queryParams, true);
ctx.response()
.putHeader(HttpHeaders.LOCATION, uri)
.setStatusCode(statusCode)
.end();
}
@Override
public void handle(RoutingContext ctx) {
if (nagHttps) {
String uri = ctx.request().absoluteURI();
if (uri != null && !uri.startsWith("https:")) {
log.warn("Using session cookies without https could make you susceptible to session hijacking: " + uri);
}
}
HttpMethod method = ctx.request().method();
switch (method.name()) {
case "GET":
final String token = generateToken();
// put the token in the context for users who prefer to render the token directly on the HTML
ctx.put(headerName, token);
ctx.addCookie(Cookie.cookie(cookieName, token));
enhanceContext(ctx);
ctx.next();
break;
case "POST":
case "PUT":
case "DELETE":
case "PATCH":
final String header = ctx.request().getHeader(headerName);
final Cookie cookie = ctx.getCookie(cookieName);
if (validateToken(header == null ? ctx.request().getFormAttribute(headerName) : header, cookie)) {
ctx.next();
} else {
redirect(ctx);
}
break;
default:
// ignore these methods
ctx.next();
break;
}
}
private void enhanceContext(RoutingContext ctx) {
Map<String, String> _csrf = new HashMap<>();
_csrf.put("parameterName", io.vertx.ext.web.handler.CSRFHandler.DEFAULT_HEADER_NAME);
_csrf.put("token", ctx.get(io.vertx.ext.web.handler.CSRFHandler.DEFAULT_HEADER_NAME));
ctx.put("_csrf", _csrf);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.storage.queue.implementation.util;
import com.azure.core.credential.AzureSasCredential;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpHeaders;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.policy.AddDatePolicy;
import com.azure.core.http.policy.AddHeadersPolicy;
import com.azure.core.http.policy.AzureSasCredentialPolicy;
import com.azure.core.http.policy.BearerTokenAuthenticationPolicy;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.policy.HttpLoggingPolicy;
import com.azure.core.http.policy.HttpPipelinePolicy;
import com.azure.core.http.policy.HttpPolicyProviders;
import com.azure.core.http.policy.RequestIdPolicy;
import com.azure.core.http.policy.RetryOptions;
import com.azure.core.http.policy.UserAgentPolicy;
import com.azure.core.util.ClientOptions;
import com.azure.core.util.Configuration;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.logging.ClientLogger;
import com.azure.storage.common.StorageSharedKeyCredential;
import com.azure.storage.common.implementation.BuilderUtils;
import com.azure.storage.common.implementation.Constants;
import com.azure.storage.common.implementation.SasImplUtils;
import com.azure.storage.common.implementation.credentials.CredentialValidator;
import com.azure.storage.common.policy.MetadataValidationPolicy;
import com.azure.storage.common.policy.RequestRetryOptions;
import com.azure.storage.common.policy.ResponseValidationPolicyBuilder;
import com.azure.storage.common.policy.ScrubEtagPolicy;
import com.azure.storage.common.policy.StorageSharedKeyCredentialPolicy;
import com.azure.storage.common.sas.CommonSasQueryParameters;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* This class provides helper methods for common builder patterns.
*/
public final class BuilderHelper {
private static final Map<String, String> PROPERTIES =
CoreUtils.getProperties("azure-storage-queue.properties");
private static final String SDK_NAME = "name";
private static final String SDK_VERSION = "version";
private static final String CLIENT_NAME = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName");
private static final String CLIENT_VERSION = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
/**
* Determines whether or not the passed authority is IP style, that is it is of the format
* {@code <host>:<port>}.
*
* @param authority The authority of a URL.
* @throws MalformedURLException If the authority is malformed.
* @return Whether the authority is IP style.
*/
public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException {
return new URL("http://" + authority).getPort() != -1;
}
/**
* Parse the endpoint for the account name, queue name, and SAS token query parameters.
*
* @param endpoint Endpoint to parse.
* @param logger {@link ClientLogger} used to log any exception.
* @return The parsed endpoint as a {@link QueueUrlParts}.
*/
public static QueueUrlParts parseEndpoint(String endpoint, ClientLogger logger) {
Objects.requireNonNull(endpoint);
try {
URL url = new URL(endpoint);
QueueUrlParts parts = new QueueUrlParts().setScheme(url.getProtocol());
if (determineAuthorityIsIpStyle(url.getAuthority())) {
// URL is using an IP pattern of http://127.0.0.1:10000/accountName/queueName
// or http://localhost:10000/accountName/queueName
String path = url.getPath();
if (!CoreUtils.isNullOrEmpty(path) && path.charAt(0) == '/') {
path = path.substring(1);
}
String[] pathPieces = path.split("/", 2);
parts.setAccountName(pathPieces[0]);
if (pathPieces.length == 2) {
parts.setQueueName(pathPieces[1]);
}
parts.setEndpoint(String.format("%s://%s/%s", url.getProtocol(), url.getAuthority(),
parts.getAccountName()));
} else {
// URL is using a pattern of http://accountName.queue.core.windows.net/queueName
String host = url.getHost();
String accountName = null;
if (!CoreUtils.isNullOrEmpty(host)) {
int accountNameIndex = host.indexOf('.');
if (accountNameIndex == -1) {
accountName = host;
} else {
accountName = host.substring(0, accountNameIndex);
}
}
parts.setAccountName(accountName);
String[] pathSegments = url.getPath().split("/", 2);
if (pathSegments.length == 2 && !CoreUtils.isNullOrEmpty(pathSegments[1])) {
parts.setQueueName(pathSegments[1]);
}
parts.setEndpoint(String.format("%s://%s", url.getProtocol(), url.getAuthority()));
}
// Attempt to get the SAS token from the URL passed
String sasToken = new CommonSasQueryParameters(
SasImplUtils.parseQueryString(url.getQuery()), false).encode();
if (!CoreUtils.isNullOrEmpty(sasToken)) {
parts.setSasToken(sasToken);
}
return parts;
} catch (MalformedURLException ex) {
throw logger.logExceptionAsError(
new IllegalArgumentException("The Azure Storage Queue endpoint url is malformed.", ex));
}
}
/**
* Constructs a {@link HttpPipeline} from values passed from a builder.
*
* @param storageSharedKeyCredential {@link StorageSharedKeyCredential} if present.
* @param tokenCredential {@link TokenCredential} if present.
* @param azureSasCredential {@link AzureSasCredential} if present.
* @param sasToken The SAS token if present.
* @param endpoint The endpoint for the client.
* @param retryOptions Storage retry options to set in the retry policy.
* @param coreRetryOptions Core retry options to set in the retry policy.
* @param logOptions Logging options to set in the logging policy.
* @param clientOptions Client options.
* @param httpClient HttpClient to use in the builder.
* @param perCallPolicies Additional {@link HttpPipelinePolicy policies} to set in the pipeline per call.
* @param perRetryPolicies Additional {@link HttpPipelinePolicy policies} to set in the pipeline per retry.
* @param configuration Configuration store contain environment settings.
* @param logger {@link ClientLogger} used to log any exception.
* @return A new {@link HttpPipeline} from the passed values.
*/
public static HttpPipeline buildPipeline(
StorageSharedKeyCredential storageSharedKeyCredential,
TokenCredential tokenCredential, AzureSasCredential azureSasCredential, String sasToken, String endpoint,
RequestRetryOptions retryOptions, RetryOptions coreRetryOptions,
HttpLogOptions logOptions, ClientOptions clientOptions, HttpClient httpClient,
List<HttpPipelinePolicy> perCallPolicies, List<HttpPipelinePolicy> perRetryPolicies,
Configuration configuration, ClientLogger logger) {
CredentialValidator.validateSingleCredentialIsPresent(
storageSharedKeyCredential, tokenCredential, azureSasCredential, sasToken, logger);
// Closest to API goes first, closest to wire goes last.
List<HttpPipelinePolicy> policies = new ArrayList<>();
policies.add(getUserAgentPolicy(configuration, logOptions, clientOptions));
policies.add(new RequestIdPolicy());
policies.addAll(perCallPolicies);
HttpPolicyProviders.addBeforeRetryPolicies(policies);
policies.add(BuilderUtils.createRetryPolicy(retryOptions, coreRetryOptions, logger));
policies.add(new AddDatePolicy());
// We need to place this policy right before the credential policy since headers may affect the string to sign
// of the request.
HttpHeaders headers = new HttpHeaders();
clientOptions.getHeaders().forEach(header -> headers.put(header.getName(), header.getValue()));
if (headers.getSize() > 0) {
policies.add(new AddHeadersPolicy(headers));
}
policies.add(new MetadataValidationPolicy());
HttpPipelinePolicy credentialPolicy;
if (storageSharedKeyCredential != null) {
credentialPolicy = new StorageSharedKeyCredentialPolicy(storageSharedKeyCredential);
} else if (tokenCredential != null) {
httpsValidation(tokenCredential, "bearer token", endpoint, logger);
credentialPolicy = new BearerTokenAuthenticationPolicy(tokenCredential, Constants.STORAGE_SCOPE);
} else if (azureSasCredential != null) {
credentialPolicy = new AzureSasCredentialPolicy(azureSasCredential, false);
} else if (sasToken != null) {
credentialPolicy = new AzureSasCredentialPolicy(new AzureSasCredential(sasToken), false);
} else {
credentialPolicy = null;
}
if (credentialPolicy != null) {
policies.add(credentialPolicy);
}
policies.addAll(perRetryPolicies);
HttpPolicyProviders.addAfterRetryPolicies(policies);
policies.add(getResponseValidationPolicy());
policies.add(new HttpLoggingPolicy(logOptions));
policies.add(new ScrubEtagPolicy());
return new HttpPipelineBuilder()
.policies(policies.toArray(new HttpPipelinePolicy[0]))
.httpClient(httpClient)
.build();
}
/**
* Gets the default http log option for Storage Queue.
*
* @return the default http log options.
*/
public static HttpLogOptions getDefaultHttpLogOptions() {
HttpLogOptions defaultOptions = new HttpLogOptions();
QueueHeadersAndQueryParameters.getQueueHeaders().forEach(defaultOptions::addAllowedHeaderName);
QueueHeadersAndQueryParameters.getQueueQueryParameters().forEach(defaultOptions::addAllowedQueryParamName);
return defaultOptions;
}
/*
* Creates a {@link UserAgentPolicy} using the default blob module name and version.
*
* @param configuration Configuration store used to determine whether telemetry information should be included.
* @param logOptions Logging options to set in the logging policy.
* @param clientOptions Client options.
* @return The default {@link UserAgentPolicy} for the module.
*/
private static UserAgentPolicy getUserAgentPolicy(Configuration configuration, HttpLogOptions logOptions,
ClientOptions clientOptions) {
configuration = (configuration == null) ? Configuration.NONE : configuration;
String applicationId = clientOptions.getApplicationId() != null ? clientOptions.getApplicationId()
: logOptions.getApplicationId();
return new UserAgentPolicy(applicationId, CLIENT_NAME, CLIENT_VERSION, configuration);
}
/*
* Creates a {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} used to validate response data from
* the service.
*
* @return The {@link ResponseValidationPolicyBuilder.ResponseValidationPolicy} for the module.
*/
private static HttpPipelinePolicy getResponseValidationPolicy() {
return new ResponseValidationPolicyBuilder()
.addOptionalEcho(Constants.HeaderConstants.CLIENT_REQUEST_ID)
.build();
}
/**
* Validates that the client is properly configured to use https.
*
* @param objectToCheck The object to check for.
* @param objectName The name of the object.
* @param endpoint The endpoint for the client.
* @param logger {@link ClientLogger} used to log any exception.
*/
public static void httpsValidation(Object objectToCheck, String objectName, String endpoint, ClientLogger logger) {
if (objectToCheck != null && !parseEndpoint(endpoint, logger).getScheme().equals(Constants.HTTPS)) {
throw logger.logExceptionAsError(new IllegalArgumentException(
"Using a(n) " + objectName + " requires https"));
}
}
public static class QueueUrlParts {
private String scheme;
private String endpoint;
private String accountName;
private String queueName;
private String sasToken;
public String getScheme() {
return scheme;
}
public QueueUrlParts setScheme(String scheme) {
this.scheme = scheme;
return this;
}
public String getEndpoint() {
return endpoint;
}
public QueueUrlParts setEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public String getAccountName() {
return accountName;
}
public QueueUrlParts setAccountName(String accountName) {
this.accountName = accountName;
return this;
}
public String getQueueName() {
return queueName;
}
QueueUrlParts setQueueName(String queueName) {
this.queueName = queueName;
return this;
}
public String getSasToken() {
return sasToken;
}
public QueueUrlParts setSasToken(String sasToken) {
this.sasToken = sasToken;
return this;
}
}
}
| |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.BitUtil;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.xmlb.annotations.Transient;
import org.jdom.Element;
import org.jdom.Verifier;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
/**
* @deprecated {@link com.intellij.util.xmlb.XmlSerializer} should be used instead
* @author mike
*/
@SuppressWarnings({"HardCodedStringLiteral"})
public class DefaultJDOMExternalizer {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.DefaultJDOMExternalizer");
private DefaultJDOMExternalizer() {
}
public interface JDOMFilter{
boolean isAccept(@NotNull Field field);
}
public static void writeExternal(@NotNull Object data, @NotNull Element parentNode) throws WriteExternalException {
writeExternal(data, parentNode, null);
}
public static void writeExternal(@NotNull Object data,
@NotNull Element parentNode,
@Nullable("null means all elements accepted") JDOMFilter filter) throws WriteExternalException {
Field[] fields = data.getClass().getFields();
for (Field field : fields) {
if (field.getName().indexOf('$') >= 0) continue;
int modifiers = field.getModifiers();
if (!(Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) &&
/*!Modifier.isFinal(modifiers) &&*/ !Modifier.isTransient(modifiers) &&
field.getAnnotation(Transient.class) == null)) continue;
field.setAccessible(true); // class might be non-public
Class type = field.getType();
if (filter != null && !filter.isAccept(field) || field.getDeclaringClass().getAnnotation(Transient.class) != null) {
continue;
}
String value = null;
try {
if (type.isPrimitive()) {
if (type.equals(byte.class)) {
value = Byte.toString(field.getByte(data));
}
else if (type.equals(short.class)) {
value = Short.toString(field.getShort(data));
}
else if (type.equals(int.class)) {
value = Integer.toString(field.getInt(data));
}
else if (type.equals(long.class)) {
value = Long.toString(field.getLong(data));
}
else if (type.equals(float.class)) {
value = Float.toString(field.getFloat(data));
}
else if (type.equals(double.class)) {
value = Double.toString(field.getDouble(data));
}
else if (type.equals(char.class)) {
value = String.valueOf(field.getChar(data));
}
else if (type.equals(boolean.class)) {
value = Boolean.toString(field.getBoolean(data));
}
else {
continue;
}
}
else if (type.equals(String.class)) {
value = filterXMLCharacters((String)field.get(data));
}
else if (type.isEnum()) {
value = field.get(data).toString();
}
else if (type.equals(Color.class)) {
Color color = (Color)field.get(data);
if (color != null) {
value = Integer.toString(color.getRGB() & 0xFFFFFF, 16);
}
}
else if (ReflectionUtil.isAssignable(JDOMExternalizable.class, type)) {
Element element = new Element("option");
parentNode.addContent(element);
element.setAttribute("name", field.getName());
JDOMExternalizable domValue = (JDOMExternalizable)field.get(data);
if (domValue != null) {
Element valueElement = new Element("value");
element.addContent(valueElement);
domValue.writeExternal(valueElement);
}
continue;
}
else {
LOG.debug("Wrong field type: " + type);
continue;
}
}
catch (IllegalAccessException e) {
continue;
}
Element element = new Element("option");
parentNode.addContent(element);
element.setAttribute("name", field.getName());
if (value != null) {
element.setAttribute("value", value);
}
}
}
@Nullable
public static String filterXMLCharacters(String value) {
if (value != null) {
StringBuilder builder = null;
for (int i=0; i<value.length();i++) {
char c = value.charAt(i);
if (Verifier.isXMLCharacter(c)) {
if (builder != null) {
builder.append(c);
}
}
else {
if (builder == null) {
builder = new StringBuilder(value.length()+5);
builder.append(value, 0, i);
}
}
}
if (builder != null) {
value = builder.toString();
}
}
return value;
}
public static void readExternal(@NotNull Object data, Element parentNode) throws InvalidDataException{
if (parentNode == null) return;
for (final Object o : parentNode.getChildren("option")) {
Element e = (Element)o;
String fieldName = e.getAttributeValue("name");
if (fieldName == null) {
throw new InvalidDataException();
}
try {
Field field = data.getClass().getField(fieldName);
Class type = field.getType();
int modifiers = field.getModifiers();
if (!BitUtil.isSet(modifiers, Modifier.PUBLIC) || BitUtil.isSet(modifiers, Modifier.STATIC)) continue;
field.setAccessible(true); // class might be non-public
if (BitUtil.isSet(modifiers, Modifier.FINAL)) {
// read external contents of final field
Object value = field.get(data);
if (JDOMExternalizable.class.isInstance(value)) {
final List children = e.getChildren("value");
for (Object child : children) {
Element valueTag = (Element)child;
((JDOMExternalizable)value).readExternal(valueTag);
}
}
continue;
}
String value = e.getAttributeValue("value");
if (type.isPrimitive()) {
if (value != null) {
if (type.equals(byte.class)) {
try {
field.setByte(data, Byte.parseByte(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(short.class)) {
try {
field.setShort(data, Short.parseShort(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(int.class)) {
int i = toInt(value);
field.setInt(data, i);
}
else if (type.equals(long.class)) {
try {
field.setLong(data, Long.parseLong(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(float.class)) {
try {
field.setFloat(data, Float.parseFloat(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(double.class)) {
try {
field.setDouble(data, Double.parseDouble(value));
}
catch (NumberFormatException ex) {
throw new InvalidDataException();
}
}
else if (type.equals(char.class)) {
if (value.length() != 1) {
throw new InvalidDataException();
}
field.setChar(data, value.charAt(0));
}
else if (type.equals(boolean.class)) {
if (value.equals("true")) {
field.setBoolean(data, true);
}
else if (value.equals("false")) {
field.setBoolean(data, false);
}
else {
throw new InvalidDataException();
}
}
else {
throw new InvalidDataException();
}
}
}
else if (type.isEnum()) {
for (Object enumValue : type.getEnumConstants()) {
if (enumValue.toString().equals(value)) {
field.set(data, enumValue);
break;
}
}
}
else if (type.equals(String.class)) {
field.set(data, value);
}
else if (type.equals(Color.class)) {
Color color = toColor(value);
field.set(data, color);
}
else if (ReflectionUtil.isAssignable(JDOMExternalizable.class, type)) {
final List<Element> children = e.getChildren("value");
if (!children.isEmpty()) {
// compatibility with Selena's serialization which writes an empty tag for a bean which has a default value
JDOMExternalizable object = null;
for (Element element : children) {
object = (JDOMExternalizable)type.newInstance();
object.readExternal(element);
}
field.set(data, object);
}
}
else {
throw new InvalidDataException("wrong type: " + type);
}
}
catch (NoSuchFieldException ex) {
LOG.debug(ex);
}
catch (SecurityException ex) {
throw new InvalidDataException();
}
catch (IllegalAccessException ex) {
throw new InvalidDataException(ex);
}
catch (InstantiationException ex) {
throw new InvalidDataException();
}
}
}
public static int toInt(@NotNull String value) throws InvalidDataException {
int i;
try {
i = Integer.parseInt(value);
}
catch (NumberFormatException ex) {
throw new InvalidDataException(value, ex);
}
return i;
}
public static Color toColor(@Nullable String value) throws InvalidDataException {
Color color;
if (value == null) {
color = null;
}
else {
try {
int rgb = Integer.parseInt(value, 16);
color = new Color(rgb);
}
catch (NumberFormatException ex) {
LOG.debug("Wrong color value: " + value, ex);
throw new InvalidDataException("Wrong color value: " + value, ex);
}
}
return color;
}
}
| |
package gov.usgs.cida.gcmrcservices.jsl.data;
import gov.usgs.cida.gcmrcservices.column.ColumnMetadata;
import gov.usgs.cida.gcmrcservices.nude.Endpoint;
import static gov.usgs.webservices.jdbc.spec.GCMRCSpec.ASCENDING_ORDER;
import gov.usgs.webservices.jdbc.spec.mapping.ColumnMapping;
import gov.usgs.webservices.jdbc.spec.mapping.SearchMapping;
import gov.usgs.webservices.jdbc.spec.mapping.WhereClauseType;
import gov.usgs.webservices.jdbc.util.CleaningOption;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author dmsibley
*/
public class ParameterSpec extends DataSpec {
private static final Logger log = LoggerFactory.getLogger(ParameterSpec.class);
public ParameterSpec(String stationName, ParameterCode parameterCode, SpecOptions options) {
super(stationName, parameterCode, options);
}
@Override
public ColumnMapping[] setupColumnMap() {
ColumnMapping[] result = null;
if (null != this.stationName && null != this.parameterCode) {
String parameterColumnName = ColumnMetadata.createColumnName(this.stationName, this.parameterCode);
result = new ColumnMapping[] {
new ColumnMapping(C_TSM_DT, S_TSM_DT, ASCENDING_ORDER, S_TSM_DT, null, null, null, "TO_CHAR(" + C_TSM_DT + ", 'YYYY-MM-DD\"T\"HH24:MI:SS')", null, null),
new ColumnMapping(parameterColumnName, S_FINAL_VALUE, ASCENDING_ORDER, S_FINAL_VALUE, null, null, null, C_FINAL_VALUE, null, null),
new ColumnMapping(parameterColumnName + C_RAW_VALUE, S_RAW_VALUE, ASCENDING_ORDER, S_RAW_VALUE, null, null, null, C_RAW_VALUE, null, null),
new ColumnMapping(parameterColumnName + C_MAIN_QUALIFIER, S_MAIN_QUALIFIER, ASCENDING_ORDER, S_MAIN_QUALIFIER, null, null, null, C_MAIN_QUALIFIER, null, null),
new ColumnMapping(parameterColumnName + C_DATA_APPROVAL, S_DATA_APPROVAL, ASCENDING_ORDER, S_DATA_APPROVAL, null, null, null, C_DATA_APPROVAL, null, null),
new ColumnMapping(parameterColumnName + C_MEASUREMENT_GRADE, S_MEASUREMENT_GRADE, ASCENDING_ORDER, S_MEASUREMENT_GRADE, null, null, null, C_MEASUREMENT_GRADE, null, null),
new ColumnMapping(parameterColumnName + C_DEPLOYMENT, S_DEPLOYMENT, ASCENDING_ORDER, S_DEPLOYMENT, null, null, null, C_DEPLOYMENT, null, null),
new ColumnMapping(parameterColumnName + C_ICE_AFFECTED, S_ICE_AFFECTED, ASCENDING_ORDER, S_ICE_AFFECTED, null, null, null, C_ICE_AFFECTED, null, null),
new ColumnMapping(parameterColumnName + C_TURBIDITY_PEGGED, S_TURBIDITY_PEGGED, ASCENDING_ORDER, S_TURBIDITY_PEGGED, null, null, null, C_TURBIDITY_PEGGED, null, null),
new ColumnMapping(parameterColumnName + C_PROBE_TYPE, S_PROBE_TYPE, ASCENDING_ORDER, S_PROBE_TYPE, null, null, null, C_PROBE_TYPE, null, null),
new ColumnMapping(parameterColumnName + C_INSTRUMENT, S_INSTRUMENT, ASCENDING_ORDER, S_INSTRUMENT, null, null, null, C_INSTRUMENT, null, null),
new ColumnMapping(parameterColumnName + C_DATA_LEAD, S_DATA_LEAD, ASCENDING_ORDER, S_DATA_LEAD, null, null, null, C_DATA_LEAD, null, null),
new ColumnMapping(parameterColumnName + C_RAW_FLAG, S_RAW_FLAG, ASCENDING_ORDER, S_RAW_FLAG, null, null, null, C_RAW_FLAG, null, null),
new ColumnMapping(parameterColumnName + C_DATA_QUALIFICATION, S_DATA_QUALIFICATION, ASCENDING_ORDER, S_DATA_QUALIFICATION, null, null, null, C_DATA_QUALIFICATION, null, null),
new ColumnMapping(parameterColumnName + C_ACCURACY_RATING, S_ACCURACY_RATING, ASCENDING_ORDER, S_ACCURACY_RATING, null, null, null, C_ACCURACY_RATING, null, null),
new ColumnMapping(parameterColumnName + C_SOURCE_FILE_NAME, S_SOURCE_FILE_NAME, ASCENDING_ORDER, S_SOURCE_FILE_NAME, null, null, null, C_SOURCE_FILE_NAME, null, null),
new ColumnMapping(parameterColumnName + C_SOURCE_UPLOAD_DATE, S_SOURCE_UPLOAD_DATE, ASCENDING_ORDER, S_SOURCE_UPLOAD_DATE, null, null, null, C_SOURCE_UPLOAD_DATE, null, null),
new ColumnMapping(parameterColumnName + C_NOTES, S_NOTES, ASCENDING_ORDER, S_NOTES, null, null, null, C_NOTES, null, null),
new ColumnMapping(parameterColumnName + C_ER_VALUE, S_ER_VALUE, ASCENDING_ORDER, S_ER_VALUE, null, null, null, C_ER_VALUE, null, null)
};
} else {
log.trace("setupColumnMap stationName=" + this.stationName + " parameterCode=" + this.parameterCode);
}
return result;
}
@Override
public SearchMapping[] setupSearchMap() {
SearchMapping[] result = new SearchMapping[] {
new SearchMapping(S_SITE_NAME, C_SITE_NAME, null, WhereClauseType.equals, null, null, null),
new SearchMapping(S_GROUP_NAME, C_GROUP_NAME, null, WhereClauseType.equals, null, null, null),
new SearchMapping(Endpoint.BEGIN_KEYWORD, C_TSM_DT, null, WhereClauseType.special, CleaningOption.none, FIELD_NAME_KEY + " >= TO_DATE(" + USER_VALUE_KEY + ", 'YYYY-MM-DD\"T\"HH24:MI:SS')", null),
new SearchMapping(Endpoint.END_KEYWORD, C_TSM_DT, null, WhereClauseType.special, CleaningOption.none, FIELD_NAME_KEY + " <= TO_DATE(" + USER_VALUE_KEY + ", 'YYYY-MM-DD\"T\"HH24:MI:SS')", null)
};
return result;
}
@Override
public String setupTableName() {
StringBuilder result = new StringBuilder();
result.append(" (SELECT MEASUREMENT_DATE AS TSM_DT,");
result.append(" FINAL_VALUE,");
result.append(" RAW_VALUE,");
result.append(" MAIN_QUALIFIER,");
result.append(" DATA_APPROVAL,");
result.append(" MEASUREMENT_GRADE,");
result.append(" DEPLOYMENT,");
result.append(" ICE_AFFECTED,");
result.append(" TURBIDITY_PEGGED,");
result.append(" PROBE_TYPE,");
result.append(" INSTRUMENT,");
result.append(" DATA_LEAD,");
result.append(" RAW_FLAG,");
result.append(" DATA_QUALIFICATION,");
result.append(" ACCURACY_RATING,");
result.append(" SOURCE_FILE_NAME,");
result.append(" SOURCE_UPLOAD_DATE,");
result.append(" NOTES,");
result.append(" ER_VALUE,");
result.append(" SITE_NAME,");
result.append(" GROUP_NAME");
result.append(" FROM TIME_SERIES_STAR");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT MEASUREMENT_QUALIFIER_ID, NAME AS MAIN_QUALIFIER_NAME, CODE AS MAIN_QUALIFIER FROM MEASUREMENT_QUALIFIER_STAR");
result.append(" ) T_MAIN_QUALIFIER");
result.append(" ON TIME_SERIES_STAR.ICE_AFFECTED_ID = T_MAIN_QUALIFIER.MEASUREMENT_QUALIFIER_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT DATA_APPROVAL_ID, NAME AS DATA_APPROVAL_NAME, CODE AS DATA_APPROVAL FROM DATA_APPROVAL_STAR");
result.append(" ) T_DATA_APPROVAL");
result.append(" ON TIME_SERIES_STAR.DATA_APPROVAL_ID = T_DATA_APPROVAL.DATA_APPROVAL_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT MEASUREMENT_GRADE_ID, NAME AS MEASUREMENT_GRADE_NAME, CODE AS MEASUREMENT_GRADE FROM MEASUREMENT_GRADE_STAR");
result.append(" ) T_MEASUREMENT_GRADE");
result.append(" ON TIME_SERIES_STAR.MEASUREMENT_GRADE_ID = T_MEASUREMENT_GRADE.MEASUREMENT_GRADE_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT DEPLOYMENT_ID, NAME AS DEPLOYMENT FROM DEPLOYMENT_STAR");
result.append(" ) T_DEPLOYMENT");
result.append(" ON TIME_SERIES_STAR.DEPLOYMENT_ID = T_DEPLOYMENT.DEPLOYMENT_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT ICE_AFFECTED_ID, NAME AS ICE_AFFECTED FROM ICE_AFFECTED_STAR");
result.append(" ) T_ICE");
result.append(" ON TIME_SERIES_STAR.ICE_AFFECTED_ID = T_ICE.ICE_AFFECTED_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT PROBE_TYPE_ID, NAME AS PROBE_TYPE FROM PROBE_TYPE_STAR");
result.append(" ) T_PROBE_TYPE");
result.append(" ON TIME_SERIES_STAR.PROBE_TYPE_ID = T_PROBE_TYPE.PROBE_TYPE_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT INSTRUMENT_ID, NAME AS INSTRUMENT FROM INSTRUMENT_STAR");
result.append(" ) T_INSTRUMENT");
result.append(" ON TIME_SERIES_STAR.INSTRUMENT_ID = T_INSTRUMENT.INSTRUMENT_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT DATA_LEAD_ID, NAME AS DATA_LEAD FROM DATA_LEAD_STAR");
result.append(" ) T_DATA_LEAD");
result.append(" ON TIME_SERIES_STAR.DATA_LEAD_ID = T_DATA_LEAD.DATA_LEAD_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT RAW_FLAG_ID, CODE AS RAW_FLAG FROM RAW_FLAG_STAR");
result.append(" ) T_RAW_FLAG");
result.append(" ON TIME_SERIES_STAR.RAW_FLAG_ID = T_RAW_FLAG.RAW_FLAG_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT DATA_QUALIFICATION_ID, NAME AS DATA_QUALIFICATION FROM DATA_QUALIFICATION_STAR");
result.append(" ) T_DATA_QUALIFICATION");
result.append(" ON TIME_SERIES_STAR.DATA_QUALIFICATION_ID = T_DATA_QUALIFICATION.DATA_QUALIFICATION_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT ACCURACY_RATING_ID, CODE AS ACCURACY_RATING FROM ACCURACY_RATING_STAR");
result.append(" ) T_ACCURACY_RATING");
result.append(" ON TIME_SERIES_STAR.ACCURACY_RATING_ID = T_ACCURACY_RATING.ACCURACY_RATING_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT SOURCE_ID, ORIGINAL_NAME AS SOURCE_FILE_NAME, UPLOAD_DATE AS SOURCE_UPLOAD_DATE FROM SOURCE_STAR");
result.append(" ) T_SOURCE");
result.append(" ON TIME_SERIES_STAR.SOURCE_ID = T_SOURCE.SOURCE_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT SITE_ID,");
result.append(" CASE");
result.append(" WHEN NWIS_SITE_NO IS NULL");
result.append(" THEN SHORT_NAME");
result.append(" ELSE NWIS_SITE_NO");
result.append(" END AS SITE_NAME");
result.append(" FROM SITE_STAR");
result.append(" ) SITE");
result.append(" ON TIME_SERIES_STAR.SITE_ID = SITE.SITE_ID");
result.append(" LEFT OUTER JOIN");
result.append(" (SELECT GROUP_ID, NAME AS GROUP_NAME FROM GROUP_NAME");
result.append(" ) T_GROUP");
result.append(" ON TIME_SERIES_STAR.GROUP_ID = T_GROUP.GROUP_ID");
result.append(" ) T_A_MAIN");
return result.toString();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append("TODO I'm a " + this.stationName + " " + this.parameterCode.toString() + " param Spec!")
.toHashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) { return false; }
if (obj == this) { return true; }
if (obj instanceof ParameterSpec) {
ParameterSpec rhs = (ParameterSpec) obj;
return new EqualsBuilder()
.append(this.stationName, rhs.stationName)
.append(this.parameterCode, rhs.parameterCode)
.isEquals();
}
return false;
}
public static final String C_TSM_DT = "TSM_DT";
public static final String S_TSM_DT = "TSM_DT";
public static final String C_FINAL_VALUE = "FINAL_VALUE";
public static final String S_FINAL_VALUE = "FINAL_VALUE";
public static final String C_SITE_NAME = "SITE_NAME";
public static final String S_SITE_NAME = "SITE_NAME";
public static final String C_GROUP_NAME = "GROUP_NAME";
public static final String S_GROUP_NAME = "GROUP_NAME";
public static final String C_RAW_VALUE = "RAW_VALUE";
public static final String S_RAW_VALUE = "RAW_VALUE";
public static final String C_MAIN_QUALIFIER = "MAIN_QUALIFIER";
public static final String S_MAIN_QUALIFIER = "MAIN_QUALIFIER";
public static final String C_DATA_APPROVAL = "DATA_APPROVAL";
public static final String S_DATA_APPROVAL = "DATA_APPROVAL";
public static final String C_MEASUREMENT_GRADE = "MEASUREMENT_GRADE";
public static final String S_MEASUREMENT_GRADE = "MEASUREMENT_GRADE";
public static final String C_DEPLOYMENT = "DEPLOYMENT";
public static final String S_DEPLOYMENT = "DEPLOYMENT";
public static final String C_ICE_AFFECTED = "ICE_AFFECTED";
public static final String S_ICE_AFFECTED = "ICE_AFFECTED";
public static final String C_TURBIDITY_PEGGED = "TURBIDITY_PEGGED";
public static final String S_TURBIDITY_PEGGED = "TURBIDITY_PEGGED";
public static final String C_PROBE_TYPE = "PROBE_TYPE";
public static final String S_PROBE_TYPE = "PROBE_TYPE";
public static final String C_INSTRUMENT = "INSTRUMENT";
public static final String S_INSTRUMENT = "INSTRUMENT";
public static final String C_DATA_LEAD = "DATA_LEAD";
public static final String S_DATA_LEAD = "DATA_LEAD";
public static final String C_RAW_FLAG = "RAW_FLAG";
public static final String S_RAW_FLAG = "RAW_FLAG";
public static final String C_DATA_QUALIFICATION = "DATA_QUALIFICATION";
public static final String S_DATA_QUALIFICATION = "DATA_QUALIFICATION";
public static final String C_ACCURACY_RATING = "ACCURACY_RATING";
public static final String S_ACCURACY_RATING = "ACCURACY_RATING";
public static final String C_SOURCE_FILE_NAME = "SOURCE_FILE_NAME";
public static final String S_SOURCE_FILE_NAME = "SOURCE_FILE_NAME";
public static final String C_SOURCE_UPLOAD_DATE = "SOURCE_UPLOAD_DATE";
public static final String S_SOURCE_UPLOAD_DATE = "SOURCE_UPLOAD_DATE";
public static final String C_NOTES = "NOTES";
public static final String S_NOTES = "NOTES";
public static final String C_ER_VALUE = "ER_VALUE";
public static final String S_ER_VALUE = "ER_VALUE";
}
| |
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
*******************************************************************************/
package org.caleydo.view.bicluster.internal.loading;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.caleydo.core.data.collection.EDataClass;
import org.caleydo.core.data.collection.EDataType;
import org.caleydo.core.data.collection.column.container.CategoricalClassDescription;
import org.caleydo.core.id.IDCategory;
import org.caleydo.core.id.IDType;
import org.caleydo.core.io.ColumnDescription;
import org.caleydo.core.io.DataDescription;
import org.caleydo.core.io.DataSetDescription;
import org.caleydo.core.io.DataSetDescription.ECreateDefaultProperties;
import org.caleydo.core.io.IDSpecification;
import org.caleydo.core.io.ParsingRule;
import org.caleydo.core.io.gui.dataimport.widget.CategoricalDataPropertiesWidget;
import org.caleydo.core.startup.IStartupAddon;
import org.caleydo.core.startup.IStartupProcedure;
import org.caleydo.datadomain.genetic.TCGADefinitions;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.kohsuke.args4j.Option;
/**
* @author Samuel Gratzl
*
*/
public class BiClusterStartupAddon implements IStartupAddon {
@Option(name = "-bicluster:X", usage = "specify the bicluster x data file")
private File xFile;
@Option(name = "-bicluster:L", usage = "specify the bicluster L data file")
private File lFile;
@Option(name = "-bicluster:Z", usage = "specify the bicluster Z data file")
private File zFile;
@Option(name = "-bicluster:chemical", usage = "specify the bicluster chemical cluster file")
private File chemicalFile;
@Option(name = "-bicluster:thresholds", usage = "specify the bicluster thresholds fiel")
private File thresholdsFile;
@Option(name = "-bicluster:genes", usage = "whether the record names are valid gene symbols")
private boolean genes = false;
private Text lFileUI;
private Text zFileUI;
private Text chemicalFileUI;
private Text thresholdsFileUI;
private Button specifyCategoriesUI;
private CategoricalClassDescription<String> chemicalProperties;
@Override
public boolean init() {
if (validate())
return true;
if (isValid(xFile))
inferFromX();
if (validate())
return true;
return false;
}
private static boolean isValid(File f) {
return f != null && f.isFile() && f.exists();
}
@Override
public Composite create(Composite parent, final WizardPage page, final Listener changeListener) {
// create composite
parent = new Composite(parent, SWT.NONE);
parent.setLayout(new GridLayout(1, true));
{
Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
group.setText("X File");
group.setLayout(new GridLayout(2, false));
group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
final Text xFileUI = new Text(group, SWT.BORDER);
xFileUI.setEditable(false);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, true);
gridData.widthHint = 200;
xFileUI.setLayoutData(gridData);
Button openFileButton = new Button(group, SWT.PUSH);
openFileButton.setText("Choose X");
openFileButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
xFile = onOpenFile(xFileUI);
checkAllThere(page, changeListener);
// infer the other
if (isValid(xFile))
inferFromX();
if (isValid(lFile))
lFileUI.setText(lFile.getAbsolutePath());
if (isValid(zFile))
zFileUI.setText(zFile.getAbsolutePath());
if (isValid(chemicalFile)) {
chemicalFileUI.setText(chemicalFile.getAbsolutePath());
specifyCategoriesUI.setEnabled(true);
}
if (isValid(thresholdsFile))
thresholdsFileUI.setText(thresholdsFile.getAbsolutePath());
checkAllThere(page, changeListener);
}
});
}
{
Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
group.setText("L File");
group.setLayout(new GridLayout(2, false));
group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
this.lFileUI = new Text(group, SWT.BORDER);
lFileUI.setEditable(false);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, true);
gridData.widthHint = 200;
lFileUI.setLayoutData(gridData);
Button openFileButton = new Button(group, SWT.PUSH);
openFileButton.setText("Choose L");
openFileButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
lFile = onOpenFile(lFileUI);
checkAllThere(page, changeListener);
}
});
}
{
Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
group.setText("Z File");
group.setLayout(new GridLayout(2, false));
group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
this.zFileUI = new Text(group, SWT.BORDER);
zFileUI.setEditable(false);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, true);
gridData.widthHint = 200;
zFileUI.setLayoutData(gridData);
Button openFileButton = new Button(group, SWT.PUSH);
openFileButton.setText("Choose Z");
openFileButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
zFile = onOpenFile(zFileUI);
checkAllThere(page, changeListener);
}
});
}
{
Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
group.setText("Chemical Clustering File");
group.setLayout(new GridLayout(2, false));
group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
this.chemicalFileUI = new Text(group, SWT.BORDER);
chemicalFileUI.setEditable(false);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, true);
gridData.widthHint = 200;
chemicalFileUI.setLayoutData(gridData);
Button openFileButton = new Button(group, SWT.PUSH);
openFileButton.setText("Choose");
openFileButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
chemicalFile = onOpenFile(chemicalFileUI);
if (chemicalFile != null)
specifyCategoriesUI.setEnabled(true);
checkAllThere(page, changeListener);
}
});
specifyCategoriesUI = new Button(group, SWT.PUSH);
specifyCategoriesUI.setText("Set Properties");
gridData = new GridData(SWT.FILL, SWT.TOP, true, true);
gridData.horizontalSpan = 2;
specifyCategoriesUI.setLayoutData(gridData);
specifyCategoriesUI.setEnabled(false);
specifyCategoriesUI.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
onSpecifyChemicalCategories();
}
});
}
{
Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
group.setText("Thresholds File");
group.setLayout(new GridLayout(2, false));
group.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
this.thresholdsFileUI = new Text(group, SWT.BORDER);
thresholdsFileUI.setEditable(false);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, true);
gridData.widthHint = 200;
thresholdsFileUI.setLayoutData(gridData);
Button openFileButton = new Button(group, SWT.PUSH);
openFileButton.setText("Choose");
openFileButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
thresholdsFile = onOpenFile(thresholdsFileUI);
checkAllThere(page, changeListener);
}
});
}
{
Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
group.setText("Options");
group.setLayout(new GridLayout(1, false));
group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final Button genesUI = new Button(group, SWT.CHECK);
genesUI.setSelection(true);
genesUI.setText("Row Names are valid Gene Symbols");
genesUI.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
genes = genesUI.getSelection();
}
});
}
{
Composite rest = new Composite(parent, SWT.None);
rest.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
}
return parent;
}
/**
*
*/
protected void onSpecifyChemicalCategories() {
if (this.chemicalFile == null)
return;
ChemicalProperties p = new ChemicalProperties(null, chemicalFile, this.chemicalProperties);
p.setBlockOnOpen(true);
if (p.open() == Window.OK) {
this.chemicalProperties = p.result;
}
}
/**
* @param changeListener
*
*/
protected void checkAllThere(WizardPage page, Listener changeListener) {
boolean ok = validate();
page.setPageComplete(ok);
changeListener.handleEvent(null); // fake it
}
protected File onOpenFile(Text xFileUI) {
FileDialog fileDialog = new FileDialog(xFileUI.getShell());
fileDialog.setText("Open");
// fileDialog.setFilterPath(filePath);
String[] filterExt = { "*.csv" };
fileDialog.setFilterExtensions(filterExt);
fileDialog.setFileName(xFileUI.getText());
String inputFileName = fileDialog.open();
if (inputFileName == null)
return StringUtils.isBlank(xFileUI.getText()) ? null : new File(xFileUI.getText());
xFileUI.setText(StringUtils.defaultString(inputFileName));
return new File(inputFileName);
}
/**
* @return
*/
public List<DataSetDescription> toDataSetDescriptions() {
final IDSpecification geneNames = genes ? TCGADefinitions.createGeneIDSpecificiation() : new IDSpecification(
"GENE_SAMPLES", "GENE_SAMPLES");
final IDSpecification sample = new IDSpecification("SAMPLE", "SAMPLE");
final IDSpecification bicluster = new IDSpecification("BICLUSTER", "BICLUSTER");
List<DataSetDescription> r = new ArrayList<DataSetDescription>();
String name = getProjectName();
{
DataSetDescription x = new DataSetDescription(ECreateDefaultProperties.NUMERICAL);
x.setDataSourcePath(xFile.getAbsolutePath());
x.setDataSetName(name + "_X");
x.setDelimiter("\t");
x.setRowIDSpecification(geneNames);
x.setColumnIDSpecification(sample);
x.addParsingRule(createParsingRule());
r.add(x);
}
{
DataSetDescription l = new DataSetDescription(ECreateDefaultProperties.NUMERICAL);
l.setDataSourcePath(lFile.getAbsolutePath());
l.setDataSetName(name + "_L");
l.setDelimiter("\t");
l.setRowIDSpecification(geneNames);
l.setColumnIDSpecification(bicluster);
l.addParsingRule(createParsingRule());
r.add(l);
}
{
DataSetDescription z = new DataSetDescription(ECreateDefaultProperties.NUMERICAL);
z.setDataSourcePath(zFile.getAbsolutePath());
z.setDataSetName(name + "_Z");
z.setDelimiter("\t");
z.setRowIDSpecification(sample);
z.setColumnIDSpecification(bicluster);
z.addParsingRule(createParsingRule());
r.add(z);
}
if (isValid(chemicalFile)) {
DataSetDescription c = new DataSetDescription();
c.setDataSourcePath(chemicalFile.getAbsolutePath());
c.setDataSetName(name + "_ChemicalClusters");
c.setDelimiter("\t");
c.setRowIDSpecification(sample);
c.setColumnIDSpecification(createDummy(c.getDataSetName()));
ParsingRule p = new ParsingRule();
p.setFromColumn(1);
p.setToColumn(2);
final ColumnDescription desc = new ColumnDescription(new DataDescription(EDataClass.CATEGORICAL, EDataType.STRING));
desc.getDataDescription().setCategoricalClassDescription(chemicalProperties);
p.setColumnDescripton(desc);
c.addParsingRule(p);
r.add(c);
}
if (isValid(thresholdsFile)) {
DataSetDescription t = new DataSetDescription();
t.setDataSourcePath(thresholdsFile.getAbsolutePath());
t.setDataSetName(name + "_Thresholds");
t.setDelimiter("\t");
t.setRowIDSpecification(bicluster);
t.setColumnIDSpecification(createDummy(t.getDataSetName()));
for (int i = 1; i < 3; ++i) {
ParsingRule p = new ParsingRule();
p.setFromColumn(i);
p.setToColumn(i + 1);
p.setColumnDescripton(new ColumnDescription(
new DataDescription(EDataClass.REAL_NUMBER, EDataType.FLOAT)));
t.addParsingRule(p);
}
r.add(t);
}
return r;
}
private String getProjectName() {
String xFileName = xFile.getName();
String name = xFileName.substring(0, xFileName.lastIndexOf("."));
name = StringUtils.removeEnd(name, "_X");
return name;
}
/**
* @param dataSetName
* @return
*/
private IDSpecification createDummy(String dataSetName) {
IDSpecification columnIDSpecification = new IDSpecification();
IDCategory idCategory = IDCategory.registerCategoryIfAbsent(dataSetName + "_column");
idCategory.setInternalCategory(true);
IDType idType = IDType.registerType(dataSetName + "_column", idCategory, EDataType.STRING);
columnIDSpecification.setIDSpecification(idCategory.getCategoryName(), idType.getTypeName());
return columnIDSpecification;
}
protected static ParsingRule createParsingRule() {
ParsingRule r = new ParsingRule();
r.setFromColumn(1);
r.setParseUntilEnd(true);
r.setColumnDescripton(new ColumnDescription());
return r;
}
@Override
public boolean validate() {
return isValid(xFile) && isValid(lFile) && isValid(zFile);
}
/**
*/
private void inferFromX() {
final File p = xFile.getParentFile();
final String base = StringUtils.removeEnd(xFile.getName(), "_X.csv");
if (!isValid(xFile))
lFile = new File(p, base + "_X.csv");
if (!isValid(lFile))
lFile = new File(p, base + "_L.csv");
if (!isValid(zFile))
zFile = new File(p, base + "_Z.csv");
if (!isValid(chemicalFile))
chemicalFile = new File(p, base + "_chemicalClusters.csv");
if (!isValid(thresholdsFile))
thresholdsFile = new File(p, base + "_thresholds.csv");
}
@Override
public IStartupProcedure create() {
return new LoadBiClusterStartupProcedure(getProjectName(), toDataSetDescriptions());
}
private class ChemicalProperties extends Dialog {
private CategoricalDataPropertiesWidget widget;
private CategoricalClassDescription<String> result;
private final File inputFile;
private CategoricalClassDescription<String> old;
/**
* @param parentShell
* @param old
*/
protected ChemicalProperties(Shell parentShell, File inputFile, CategoricalClassDescription<String> old) {
super(parentShell);
this.inputFile = inputFile;
this.old = old;
}
@Override
protected Control createDialogArea(Composite parent) {
List<List<String>> data = parseFile(inputFile);
widget = new CategoricalDataPropertiesWidget(parent);
if (old != null)
widget.updateCategories(data, 1, old);
else
widget.updateCategories(data, 1);
return parent;
}
@Override
protected void okPressed() {
this.result = widget.getCategoricalClassDescription();
super.okPressed();
}
/**
* @param inputFile2
* @return
*/
private List<List<String>> parseFile(File f) {
if (!f.exists() || !f.isFile())
return Collections.emptyList();
List<List<String>> r = new ArrayList<>();
try {
List<String> lines = Files.readAllLines(f.toPath(), Charset.forName("UTF-8"));
for (String line : lines.subList(1, lines.size())) {
r.add(Arrays.asList(line.split("\t")));
}
} catch (IOException e) {
ErrorDialog.openError(getParentShell(), "Can't load file", "Can't load file: " + f, new Status(
IStatus.ERROR, "Caleydo", "Can't load file: " + f, e));
}
return r;
}
}
}
| |
package com.orbital.lead.logic;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.internal.view.menu.MenuBuilder;
import android.support.v7.widget.PopupMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;
import com.nispok.snackbar.Snackbar;
import com.nispok.snackbar.SnackbarManager;
import com.nispok.snackbar.listeners.ActionClickListener;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.orbital.lead.Parser.Parser;
import com.orbital.lead.Parser.ParserFacebook;
import com.orbital.lead.R;
import com.orbital.lead.controller.Activity.AddNewSpecificJournalActivity;
import com.orbital.lead.controller.Activity.EditSpecificJournalActivity;
import com.orbital.lead.controller.Activity.PictureActivity;
import com.orbital.lead.controller.Activity.ProfileActivity;
import com.orbital.lead.controller.Activity.SpecificJournalActivity;
import com.orbital.lead.controller.CustomApplication;
import com.orbital.lead.controller.Fragment.FragmentLogin;
import com.orbital.lead.controller.Activity.MainActivity;
import com.orbital.lead.controller.Service.JournalService;
import com.orbital.lead.controller.Service.PictureService;
import com.orbital.lead.controller.Service.ProjectService;
import com.orbital.lead.logic.Asynchronous.AsyncCountry;
import com.orbital.lead.logic.Asynchronous.AsyncDeleteAlbum;
import com.orbital.lead.logic.Asynchronous.AsyncJournal;
import com.orbital.lead.logic.Asynchronous.AsyncUploadImage;
import com.orbital.lead.logic.Asynchronous.AsyncUserProfilePicture;
import com.orbital.lead.logic.Asynchronous.AsyncUserProfile;
import com.orbital.lead.logic.LocalStorage.LocalStorage;
import com.orbital.lead.logic.Preference.Preference;
import com.orbital.lead.model.Album;
import com.orbital.lead.model.Constant;
import com.orbital.lead.model.Country;
import com.orbital.lead.model.CountryList;
import com.orbital.lead.model.EnumDialogEditJournalType;
import com.orbital.lead.model.EnumJournalServiceType;
import com.orbital.lead.model.EnumOpenPictureActivityType;
import com.orbital.lead.model.EnumPictureServiceType;
import com.orbital.lead.model.EnumPictureType;
import com.orbital.lead.model.EnumProjectServiceType;
import com.orbital.lead.model.Journal;
import com.orbital.lead.model.ProjectList;
import com.orbital.lead.model.Tag;
import com.orbital.lead.model.TagList;
import com.orbital.lead.model.TagSet;
import com.orbital.lead.model.User;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by joseph on 14/6/2015.
*/
public class Logic {
private static Logic mLogic = new Logic();
private final String TAG = this.getClass().getSimpleName();
private ProgressDialog prog;
private Parser mParser;
private LocalStorage mStorageLogic;
private CustomLogging mLogging;
private Preference mPref;
private Logic(){} // private constructor to prevent creating new instance
public static Logic getInstance(){
mLogic.initLogging();
mLogic.initParser();
mLogic.initPreference();
mLogic.initLocalStorageLogic();
return mLogic;
}
/**
* @param username User input a username in plaintext
* @param password User input a password in plaintext
* @return Message object - consists of code and message
*
* **/
public void login(FragmentLogin frag, String username, String password){
//frag.HttpAsyncLogin mAsyncLogin = new frag.HttpAsyncLogin(frag);
// mAsyncLogin.execute(username, password);
}
public void getUserProfile(Activity activity, String leadUserID){
HttpAsyncUserProfile mAsync = new HttpAsyncUserProfile(activity, Constant.TYPE_GET_USER_PROFILE);
mAsync.execute(Constant.TYPE_GET_USER_PROFILE, leadUserID);
}
public void getUserProfilePicture(Activity activity, String leadUserID){
HttpAsyncUserProfilePicture mAsync = new HttpAsyncUserProfilePicture(activity, Constant.PICTURE_QUERY_QUANTITY_PROFILE);
mAsync.execute(Constant.TYPE_GET_USER_PICTURE, leadUserID, Constant.PICTURE_QUERY_QUANTITY_PROFILE);
}
/*
public Bitmap getUserProfilePicture(Context mContext, User currentUser){
if(this.mParser.isStringEmpty(currentUser.getProfilePictureID()) ||
currentUser.getProfilePictureType() == EnumPictureType.NONE){
// profile picture not exist for the user
mLogging.debug(TAG, "getUserProfilePicture => Either user database has no profile pic ID or picture type is NONE");
return null;
}else{
// check if local storage has the picture
// user_id.extension
String fileName = currentUser.getProfilePictureID() + Constant.STORAGE_DOT_EXTENSION + currentUser.getProfilePictureType().toString();
//mLogging.debug(TAG, "getUserProfilePicture => fileName => " + fileName);
if(!this.mStorageLogic.isProfilePictureExist(fileName)){ // not exist
// get picture from S3
// will still return null
// activity will get image from S3 via onReceiveResult
mLogging.debug(TAG, "getUserProfilePicture => Get image from S3");
this.callS3Service(mContext, EnumS3ServiceType.QUERY_PROFILE_PICTURE, currentUser);
}else{
mLogging.debug(TAG, "getUserProfilePicture => Get image from local storage");
return this.getLocalStorageLoadProfilePicture(fileName);
}
}
return null;
}
*/
public String getLocalStorageProfileDirectory(){
return this.mStorageLogic.getProfilePictureDirectory();
}
public Bitmap getLocalStorageLoadProfilePicture(String fileName){
return this.mStorageLogic.loadProfilePicture(fileName);
}
public void getUserJournalList(Context context, String userID){
if(getParser().isStringEmpty(userID)){
this.getLogging().debug(TAG, "retrieveUserJournalList => No journal list ID available.");
}else{
mLogging.debug(TAG, "retrieveUserJournalList => Get journal list from web service");
this.executeJournalService(context, EnumJournalServiceType.GET_ALL_JOURNAL, userID, "", "", "");
}
}
public void updateUserJournal(Context context, String userID, String journalID, String detail) {
if(getParser().isStringEmpty(userID) || getParser().isStringEmpty(journalID) || getParser().isStringEmpty(detail)){
this.getLogging().debug(TAG, "updateUserJournal => No journal list ID available.");
}else{
mLogging.debug(TAG, "updateUserJournal => update journal from web service");
this.executeJournalService(context, EnumJournalServiceType.UPDATE_SPECIFIC_JOURNAL, userID, journalID, "", detail);
}
}
public void getUserSpecificAlbum(Context context, String albumID){
if(this.getParser().isStringEmpty(albumID)){
this.getLogging().debug(TAG, "getUserSpecificAlbum => Album ID is empty.");
}else{
mLogging.debug(TAG, "getUserSpecificAlbum => Get specific album from web service with album ID => " + albumID);
this.executePictureService(context, EnumPictureServiceType.GET_SPECIFIC_ALBUM, albumID, "", "", "", "");
}
}
public void getUserAllAlbum(Context context, String userID){
if(this.getParser().isStringEmpty(userID)){
this.getLogging().debug(TAG, "getUserAllAlbum => User ID is empty.");
}else{
mLogging.debug(TAG, "getUserAllAlbum => Get all album from web service with user ID => " + userID);
this.executePictureService(context, EnumPictureServiceType.GET_ALL_ALBUM, "", userID, "", "", "");
}
}
public void getAllProject(Context context) {
mLogging.debug(TAG, "retrieveAllProject");
executeProjectService(context, EnumProjectServiceType.GET_ALL_PROJECT, "", "", "");
}
public void getAllCountries(Context context){
HttpAsyncCountry mAsync = new HttpAsyncCountry(context);
mAsync.execute(Constant.TYPE_GET_ALL_COUNTRIES);
}
public void updateUserProfileDatabase(Context context, String userID, String detail){
// detail in json string
HttpAsyncUserProfile mAsync = new HttpAsyncUserProfile(context, Constant.TYPE_UPDATE_USER_PROFILE);
mAsync.execute(Constant.TYPE_UPDATE_USER_PROFILE, userID, detail);
}
public void uploadProfilePictureFromFacebook(Context context, String userID, String albumID, String imageUrl, String fileName, String fileType,
boolean fromFacebook, boolean fromLead){
HttpAsyncUploadImage mAsync = new HttpAsyncUploadImage(context, EnumPictureServiceType.UPLOAD_PROFILE_IMAGE_URL);
mAsync.execute(EnumPictureServiceType.UPLOAD_PROFILE_IMAGE_URL.toString(), userID, imageUrl, fileName, fileType,
mParser.convertBooleanToString(fromFacebook),
mParser.convertBooleanToString(fromLead));
}
public void insertUserProfileDatabase(Context context, String detail) {
// detail in json string
HttpAsyncUserProfile mAsync = new HttpAsyncUserProfile(context, Constant.TYPE_CREATE_USER_PROFILE);
mAsync.execute(Constant.TYPE_CREATE_USER_PROFILE, "", detail);
}
public void insertNewJournal(Context context, String userID, String journalID, String albumID, String detail){
if(this.getParser().isStringEmpty(userID) || this.getParser().isStringEmpty(journalID) ||
this.getParser().isStringEmpty(albumID) || this.getParser().isStringEmpty(detail)){
this.getLogging().debug(TAG, "insertNewJournal => some parameter(s) is/are empty.");
}else{
mLogging.debug(TAG, "insertNewJournal");
this.executeJournalService(context, EnumJournalServiceType.INSERT_NEW_JOURNAL, userID, journalID, albumID, detail);
}
}
public void uploadNewPicture(Context context, String filePath, String userID, String albumID) {
if(this.getParser().isStringEmpty(userID) || this.getParser().isStringEmpty(albumID) ||
this.getParser().isStringEmpty(filePath)){
this.getLogging().debug(TAG, "uploadNewPicture => User ID or album ID or file path is empty.");
}else{
this.executePictureService(context, EnumPictureServiceType.UPLOAD_IMAGE_FILE, albumID, userID, "", filePath, "");
}
}
public void uploadFacebookImage(Context context, String userID, String albumID, String url) {
this.executePictureService(context, EnumPictureServiceType.UPLOAD_FACEBOOK_IMAGE, albumID, userID, "", "", url);
}
public void uploadNewPictureURL(Context context, String url, String userID, String albumID) {
if(this.getParser().isStringEmpty(userID) || this.getParser().isStringEmpty(albumID) ||
this.getParser().isStringEmpty(url)){
this.getLogging().debug(TAG, "uploadNewPicture => User ID or album ID or URL is empty.");
}else{
this.executePictureService(context, EnumPictureServiceType.UPLOAD_IMAGE_FILE, albumID, userID, "", "", url);
}
}
public void setAlbumCover(Context context, String userID, String albumID, String pictureID) {
if(this.getParser().isStringEmpty(userID) || this.getParser().isStringEmpty(albumID) ||
this.getParser().isStringEmpty(pictureID)){
this.getLogging().debug(TAG, "uploadNewPicture => User ID or album ID or picture ID is empty.");
}else{
this.executePictureService(context, EnumPictureServiceType.SET_ALBUM_COVER, albumID, userID, pictureID, "", "");
}
}
public void getNewJournalAlbumID(Context context, String userID) {
HttpAsyncJournal mAsync = new HttpAsyncJournal(context, EnumJournalServiceType.GET_NEW_JOURNAL_ALBUM_ID);
mAsync.execute(EnumJournalServiceType.GET_NEW_JOURNAL_ALBUM_ID.toString(), userID);
}
public void deleteAlbum(Context context, String albumID) {
HttpAsyncDeleteAlbum mAsync = new HttpAsyncDeleteAlbum(context);
mAsync.execute(EnumPictureServiceType.DELETE_ALBUM.toString(), albumID);
}
/*============= Display activity =================*/
public void displaySpecificJournalActivity(Context context, Journal journal){
mLogging.debug(TAG, "displaySpecificJournalActivity with journal ID => " + journal.getJournalID());
Intent newIntent = new Intent(context, SpecificJournalActivity.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable(Constant.BUNDLE_PARAM_JOURNAL, journal);
newIntent.putExtras(mBundle);
if(context instanceof MainActivity) {
((MainActivity) context).startActivityForResult(newIntent, MainActivity.START_SPECIFIC_JOURNAL_ACTIVITY);
}
//context.startActivity(newIntent);
}
public void displayPictureActivity(Context context, EnumOpenPictureActivityType type, Album album, String journalID){
//, ArrayList<Picture> picList
mLogging.debug(TAG, "displayPictureActivity");
Intent newIntent = new Intent(context, PictureActivity.class);
Bundle mBundle = new Bundle();
mBundle.putString(Constant.BUNDLE_PARAM_OPEN_FRAGMENT_TYPE, type.getText());
mBundle.putString(Constant.BUNDLE_PARAM_JOURNAL_ID, journalID);
mBundle.putParcelable(Constant.BUNDLE_PARAM_ALBUM, album);
newIntent.putExtras(mBundle);
if(context instanceof SpecificJournalActivity){
((SpecificJournalActivity) context).startActivityForResult(newIntent, SpecificJournalActivity.START_PICTURE_ACTIVITY);
}else if (context instanceof EditSpecificJournalActivity) {
((EditSpecificJournalActivity) context).startActivityForResult(newIntent, EditSpecificJournalActivity.START_PICTURE_ACTIVITY);
}else if(context instanceof AddNewSpecificJournalActivity) {
((AddNewSpecificJournalActivity) context).startActivityForResult(newIntent, AddNewSpecificJournalActivity.START_PICTURE_ACTIVITY);
}
//context.startActivity(newIntent);
}
public void displayEditSpecificJournalActivity(Context context, Journal journal){
Intent newIntent = new Intent(context, EditSpecificJournalActivity.class);
Bundle mBundle = new Bundle();
//mBundle.putString(Constant.BUNDLE_PARAM_JOURNAL_ID, journal.getJournalID());
//mBundle.putString(Constant.BUNDLE_PARAM_JOURNAL_IMAGE_URL, journal.getPictureCoverUrl());
mBundle.putParcelable(Constant.BUNDLE_PARAM_JOURNAL, journal);
newIntent.putExtras(mBundle);
if(context instanceof SpecificJournalActivity){
((SpecificJournalActivity) context).startActivityForResult(newIntent, SpecificJournalActivity.START_EDIT_SPECIFIC_JOURNAL_ACTIVITY);
}
}
public void displayAddNewJournalActivity(Context context) {
Intent newIntent = new Intent(context, AddNewSpecificJournalActivity.class);
if(context instanceof MainActivity){
((MainActivity) context).startActivityForResult(newIntent, MainActivity.START_ADD_NEW_SPECIFIC_JOURNAL_ACTIVITY);
}
//context.startActivity(newIntent);
}
public void displayProfileActivity(Context context){
Intent newIntent = new Intent(context, ProfileActivity.class);
Bundle mBundle = new Bundle();
//mBundle.putString(Constant.BUNDLE_PARAM_JOURNAL_ID, journal.getJournalID());
//mBundle.putString(Constant.BUNDLE_PARAM_JOURNAL_IMAGE_URL, journal.getPictureCoverUrl());
//mBundle.putParcelable(Constant.BUNDLE_PARAM_JOURNAL, journal);
newIntent.putExtras(mBundle);
context.startActivity(newIntent);
}
public void showSnackBarRed(Activity activity){
Snackbar mSnackBar = Snackbar.with(activity)
.text("")
.duration(Snackbar.SnackbarDuration.LENGTH_LONG)
.actionLabel("")
.actionColor(Color.WHITE)
.color(Color.RED)
.actionListener(new ActionClickListener() {
@Override
public void onActionClicked(Snackbar snackbar) {
}
});
SnackbarManager.show(mSnackBar, activity);
}
public void showSnackBarNormal(Activity activity){
Snackbar mSnackBar = Snackbar.with(activity)
.text("")
.duration(Snackbar.SnackbarDuration.LENGTH_LONG)
.actionLabel("")
.actionColor(Color.WHITE)
.actionListener(new ActionClickListener() {
@Override
public void onActionClicked(Snackbar snackbar) {
}
});
SnackbarManager.show(mSnackBar, activity);
}
private void initLogging(){
this.mLogging = CustomLogging.getInstance();
}
private void initParser(){
if(this.mParser == null) {
this.mParser = Parser.getInstance();
}
}
private void initPreference() {
if(this.mPref == null) {
this.mPref = Preference.getInstance();
}
}
private CustomLogging getLogging(){
return this.mLogging;
}
private Parser getParser(){
return this.mParser;
}
private void initLocalStorageLogic(){
this.mStorageLogic = LocalStorage.getInstance();
}
public void showPicture(Context context, final ViewAnimator animator, ImageView targetView, String url){
if(animator != null) {
animator.setDisplayedChild(1);
}
ImageLoader.getInstance()
.displayImage(url, targetView, CustomApplication.getDisplayImageOptions(),
new SimpleImageLoadingListener(){
@Override
public void onLoadingStarted(String imageUri, View view) {
//holder.progressBar.setProgress(0);
//holder.progressBar.setVisibility(View.VISIBLE);
//mLogging.debug(TAG, "onLoadingStarted");
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
//holder.progressBar.setVisibility(View.GONE);
//mLogging.debug(TAG, "onLoadingFailed");
if(animator != null) {
animator.setDisplayedChild(2);
}
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//holder.progressBar.setVisibility(View.GONE);
//mLogging.debug(TAG, "onLoadingComplete");
if(animator != null) {
animator.setDisplayedChild(0);
}
}
},
new ImageLoadingProgressListener() {
@Override
public void onProgressUpdate(String imageUri, View view, int current, int total) {
//mLogging.debug(TAG, "onProgressUpdate => " + Math.round(100.0f * current / total));
//holder.progressBar.setProgress(Math.round(100.0f * current / total));
}
});
}
private class HttpAsyncUserProfile extends AsyncUserProfile {
private Context mContext;
private String type = "";
public HttpAsyncUserProfile(Context c, String type){
this.mContext = c;
this.type = type;
}
@Override
protected void onPreExecute() {
//prog = new ProgressDialog(this.mContext);
// prog.setMessage("Logging in...");
//prog.show();
}
@Override
protected void onPostExecute(final String result) {
// if (prog != null && prog.isShowing()) {
// prog.dismiss();
// }//end if
switch(type){
case Constant.TYPE_GET_USER_PROFILE:
if(mContext instanceof MainActivity){ // calling from mainactivity
// update current login user in mainactivity
User user = mParser.parseJsonToUser(result);
((MainActivity) mContext).setCurrentUser(user);
((MainActivity) mContext).updateCurrentUserProfileFromFacebook();
((MainActivity) mContext).updateCurrentUserProfileToDatabase();
((MainActivity) mContext).uploadProfilePictureFromFacebook();
//((MainActivity) mContext).getUserProfilePicture(user.getUserID());
((MainActivity) mContext).setProfilePicture();
((MainActivity) mContext).setNavigationDrawerUserName();
((MainActivity) mContext).setNavigationDrawerUserEmail();
((MainActivity) mContext).retrieveUserJournalList();
((MainActivity) mContext).retrieveAllProject();
((MainActivity) mContext).retrieveAllCountries();
}
break;
case Constant.TYPE_UPDATE_USER_PROFILE:
if(mContext instanceof MainActivity) { // calling from mainactivity
mLogging.debug(TAG, "HttpAsyncUserProfile onPostExecute result => " + result);
}
break;
case Constant.TYPE_CREATE_USER_PROFILE:
String newUserID = mParser.parseUserIDFromJson(result);
if(mContext instanceof MainActivity) { // calling from mainactivity
if(!mParser.isStringEmpty(newUserID)){ // user id is not empty
mLogging.debug(TAG, "HttpAsyncUserProfile TYPE_CREATE_USER_PROFILE onPostExecute newUserID => " + newUserID);
((MainActivity) mContext).setNewCurrentUserID(newUserID);
((MainActivity) mContext).uploadProfilePictureFromFacebook();
((MainActivity) mContext).setProfilePicture();
((MainActivity) mContext).setNavigationDrawerUserName();
((MainActivity) mContext).setNavigationDrawerUserEmail();
}else{
mLogging.debug(TAG, "Unable to get new lead user ID");
}
}
break;
}
}
}
private class HttpAsyncUserProfilePicture extends AsyncUserProfilePicture {
private Context mContext;
private String query_type = "";
public HttpAsyncUserProfilePicture(Context c, String pic_query_quantity){
this.mContext = c;
this.query_type = pic_query_quantity;
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(final String result) {
if(mContext instanceof MainActivity){ // calling from mainactivity
switch(this.query_type){
case Constant.PICTURE_QUERY_QUANTITY_PROFILE:
User user = ((MainActivity) mContext).getCurrentUser();
String getImageLink = mParser.parseJsonToProfilePictureLink(result);
user.setProfilePicUrl(getImageLink);
//((MainActivity) mContext).setProfilePicture(getImageLink);
break;
case Constant.PICTURE_QUERY_QUANTITY_ALBUM:
break;
case Constant.PICTURE_QUERY_QUANTITY_ALL:
break;
}//end switch
}//end if
}//end onPostExecute
}//end HttpAsyncUserProfilePicture
private class HttpAsyncCountry extends AsyncCountry {
private Context mContext;
public HttpAsyncCountry(Context c){
this.mContext = c;
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(final String result) {
CountryList list = getParser().parseJsonToCountryList(result);
mLogging.debug(TAG, "httpAsyncCountryOnPostExecute result => " + result);
if(mContext instanceof MainActivity) {
((MainActivity) mContext).updateCurrentUserCountryList(list);
}
}//end onPostExecute
}//end HttpAsyncCountry
private class HttpAsyncUploadImage extends AsyncUploadImage {
private Context mContext;
private EnumPictureServiceType type;
public HttpAsyncUploadImage(Context c, EnumPictureServiceType serviceType){
this.mContext = c;
this.type = serviceType;
}
@Override
protected void onPreExecute() {
}
@Override
protected void onPostExecute(final String result) {
mLogging.debug(TAG, "HttpAsyncUploadImage onPostExecute result => " + result);
switch (this.type) {
case UPLOAD_PROFILE_IMAGE_URL:
break;
/*
case UPLOAD_IMAGE_FILE:
break;
*/
}
//if(mContext instanceof MainActivity){ // calling from mainactivity
//User user = ((MainActivity) mContext).getCurrentUser();
//String getImageLink = mParser.parseJsonToProfilePictureLink(result);
//user.setProfilePicUrl(getImageLink);
//((MainActivity) mContext).setProfilePicture(getImageLink);
//}//end if
}//end onPostExecute
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
switch (this.type) {
case UPLOAD_PROFILE_IMAGE_URL:
break;
/*
case UPLOAD_IMAGE_FILE:
if(mContext instanceof PictureActivity) {
}
break;
*/
}
}
}
private class HttpAsyncJournal extends AsyncJournal {
private Context context;
private EnumJournalServiceType serviceType;
public HttpAsyncJournal(Context context, EnumJournalServiceType type){
this.serviceType = type;
this.context = context;
}
protected void onPreExecute() {
}
@Override
protected void onPostExecute(final String result) {
mLogging.debug(TAG, "HttpAsyncJournal onPostExecute result => " + result);
switch (this.serviceType) {
case GET_NEW_JOURNAL_ALBUM_ID:
String newJournalID = getParser().parseJsonToJournalID(result);
String newAlbumID = getParser().parseJsonToAlbumID(result);
if(context instanceof AddNewSpecificJournalActivity) {
((AddNewSpecificJournalActivity) context).setNewJournalID(newJournalID);
((AddNewSpecificJournalActivity) context).setNewAlbumID(newAlbumID);
}
break;
default:
break;
}
}//end onPostExecute
}
private class HttpAsyncDeleteAlbum extends AsyncDeleteAlbum {
private Context context;
public HttpAsyncDeleteAlbum(Context context){
this.context = context;
}
protected void onPreExecute() {
}
@Override
protected void onPostExecute(final String result) {
mLogging.debug(TAG, "HttpAsyncDeleteAlbum onPostExecute result => " + result);
}//end onPostExecute
}
/*=============== SERVICE ==============*/
/*
private void callS3Service(Context mContext, EnumS3ServiceType serviceType, User currentUser){
String fileName = currentUser.getProfilePictureID() + Constant.STORAGE_DOT_EXTENSION + currentUser.getProfilePictureType().toString();
Intent intent = new Intent(Intent.ACTION_SYNC, null, mContext, S3Service.class);
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_ID_TAG, currentUser.getUserID()); // user ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_PROFILE_PICTURE_ID_TAG, currentUser.getProfilePictureID()); // profile picture ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_PROFILE_PICTURE_FILENAME_TAG, fileName); // profile picture file name (include extension)
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_TYPE_TAG, serviceType);
if(mContext instanceof MainActivity){
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_RECEIVER_TAG, ((MainActivity) mContext).getS3Receiver());
}
mContext.startService(intent);
}
*/
private void executeJournalService(Context mContext, EnumJournalServiceType serviceType, String userID, String journalID, String albumID, String detail){
Intent intent = new Intent(Intent.ACTION_SYNC, null, mContext, JournalService.class);
switch(serviceType){
case GET_ALL_JOURNAL:
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_ID_TAG, userID); // user ID
break;
case UPDATE_SPECIFIC_JOURNAL:
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_ID_TAG, userID); // user ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_JOURNAL_ID_TAG, journalID); // journal ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_DETAIL_TAG, detail); // detail
break;
case INSERT_NEW_JOURNAL:
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_ID_TAG, userID); // user ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_JOURNAL_ID_TAG, journalID); // journal ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_ALBUM_ID_TAG, albumID); // journal ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_DETAIL_TAG, detail); // detail
break;
}
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_TYPE_TAG, serviceType);
if(mContext instanceof MainActivity) {
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_RECEIVER_TAG, ((MainActivity) mContext).getJournalReceiver());
}else if (mContext instanceof EditSpecificJournalActivity) {
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_RECEIVER_TAG, ((EditSpecificJournalActivity) mContext).getJournalReceiver());
}else if (mContext instanceof AddNewSpecificJournalActivity) {
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_RECEIVER_TAG, ((AddNewSpecificJournalActivity) mContext).getJournalReceiver());
}
mContext.startService(intent);
}
private void executePictureService(Context mContext, EnumPictureServiceType serviceType, String albumID, String userID, String pictureID, String uploadFilePath, String url) {
Intent intent = new Intent(Intent.ACTION_SYNC, null, mContext, PictureService.class);
switch(serviceType){
case GET_SPECIFIC_ALBUM:
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_ALBUM_ID_TAG, albumID); // album ID
break;
case GET_ALL_ALBUM:
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_ID_TAG, userID); // user ID
break;
/*
case DELETE_ALBUM:
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_ALBUM_ID_TAG, albumID); // album ID
break;
*/
case UPLOAD_IMAGE_FILE:
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_ID_TAG, userID); // user ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_ALBUM_ID_TAG, albumID); // album ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_UPLOAD_FILE_PATH_TAG, uploadFilePath); // Upload File Path
break;
case UPLOAD_PROFILE_IMAGE_URL:
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_ID_TAG, userID); // user ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_ALBUM_ID_TAG, albumID); // album ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_UPLOAD_FILE_URL_TAG, url); // File URL
break;
case UPLOAD_FACEBOOK_IMAGE:
if(getParser().isStringEmpty(url)) {
getLogging().debug(TAG, "url is error");
return;
}
String fileName = ParserFacebook.getFacebookImageName(url);
EnumPictureType fileType = ParserFacebook.getPictureType(url);
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_ID_TAG, userID); // user ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_ALBUM_ID_TAG, albumID); // album ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_UPLOAD_FILE_URL_TAG, url); // File URL
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_UPLOAD_FILE_NAME_TAG, fileName); // File name
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_UPLOAD_FILE_TYPE_TAG, fileType.toString()); // File type
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_UPLOAD_FROM_FACEBOOK_TAG, true); // From facebook
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_UPLOAD_FROM_LEAD_TAG, false); // From lead
break;
case SET_ALBUM_COVER:
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_USER_ID_TAG, userID); // user ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_ALBUM_ID_TAG, albumID); // album ID
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_PICTURE_ID_TAG, pictureID); // picture ID
break;
}
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_TYPE_TAG, serviceType);
if(mContext instanceof SpecificJournalActivity){
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_RECEIVER_TAG, ((SpecificJournalActivity) mContext).getPictureReceiver());
}else if(mContext instanceof PictureActivity){
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_RECEIVER_TAG, ((PictureActivity) mContext).getPictureReceiver());
}
mContext.startService(intent);
}
private void executeProjectService(Context mContext, EnumProjectServiceType serviceType, String projectID, String userID, String detail) {
Intent intent = new Intent(Intent.ACTION_SYNC, null, mContext, ProjectService.class);
switch(serviceType){
// get all project doesnt require any post parameters
}
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_TYPE_TAG, serviceType);
if(mContext instanceof MainActivity){
intent.putExtra(Constant.INTENT_SERVICE_EXTRA_RECEIVER_TAG, ((MainActivity) mContext).getProjectReceiver());
}
mContext.startService(intent);
}
/*=========== DIALOGS WITH CUSTOM LAYOUT ===========*/
public void showAddTagProjectDialog(final Context context, final EnumDialogEditJournalType type, String editTextCurrentValue){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.dialog_add_new_layout, null);
final EditText mEditText = (EditText) dialogView.findViewById(R.id.edit_text_add_new);
TextView mToolbarTitle = (TextView) dialogView.findViewById(R.id.toolbar_text_title_add_new);
switch(type){
case ADD_TAG:
mToolbarTitle.setText(context.getResources().getString(R.string.dialog_toolbar_add_new_tag));
mEditText.setHint(context.getResources().getString(R.string.dialog_editext_tag_hint));
break;
case ADD_PROJECT:
mToolbarTitle.setText(context.getResources().getString(R.string.dialog_toolbar_add_new_project));
mEditText.setHint(context.getResources().getString(R.string.dialog_editext_project_hint));
break;
/*
case EDIT_TAG:
mToolbarTitle.setText(context.getResources().getString(R.string.dialog_toolbar_edit_tag));
mEditText.setText(editTextCurrentValue);
break;
case EDIT_PROJECT:
mToolbarTitle.setText(context.getResources().getString(R.string.dialog_toolbar_edit_project));
mEditText.setText(editTextCurrentValue);
break;
*/
}
builder.setView(dialogView)
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
switch (type) {
case ADD_TAG:
if (!mParser.isStringEmpty(mEditText.getText().toString())) {
// not empty
if (context instanceof EditSpecificJournalActivity) {
Tag newTag = new Tag(mEditText.getText().toString());
((EditSpecificJournalActivity) context).addTag(newTag);
((EditSpecificJournalActivity) context).refreshRecyclerDialogTagAdapter();
}
}
break;
case ADD_PROJECT:
break;
}
dialog.dismiss();
}
}
)
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}
);
builder.create().show();
}
public void showDeleteTagProjectDialog(final Context context, final EnumDialogEditJournalType type, final TagList tagList, final int position){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.dialog_delete_layout, null);
TextView mToolbarTitle = (TextView) dialogView.findViewById(R.id.toolbar_text_title_delete);
TextView mText = (TextView) dialogView.findViewById(R.id.text_delete);
switch(type) {
case DELETE_TAG:
mToolbarTitle.setText(context.getResources().getString(R.string.dialog_toolbar_delete_tag));
mText.setText(context.getResources().getString(R.string.dialog_description_delete_tag));
break;
case DELETE_PROJECT:
mToolbarTitle.setText(context.getResources().getString(R.string.dialog_toolbar_delete_project));
mText.setText(context.getResources().getString(R.string.dialog_description_delete_project));
break;
}
builder.setView(dialogView)
.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if (context instanceof EditSpecificJournalActivity) {
mLogging.debug(TAG, "showDeleteTagProjectDialog tagList.getList().get(position).getName() => " + tagList.getList().get(position).getName());
switch (type) {
case DELETE_TAG:
((EditSpecificJournalActivity) context).removeTag(tagList.getList().get(position));
((EditSpecificJournalActivity) context).refreshRecyclerDialogTagAdapter();
case DELETE_PROJECT:
break;
}
}
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.create().show();
}
/*=========== POPUP MENU ===========*/
public void showJournalPopUpMenu(final Context context, View v, final EnumDialogEditJournalType type, final TagList tagList, final ProjectList projectList, final int position){
PopupMenu menu = new PopupMenu(context, v){
@Override
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
switch (item.getItemId()) {
/*
case R.id.dialog_overflow_edit_journal_edit: // Edit the current row
switch(type){
case EDIT_TAG: //edit tag
showAddTagProjectDialog(context, EnumDialogEditJournalType.EDIT_TAG, currentValue);
break;
case EDIT_PROJECT:
showAddTagProjectDialog(context, EnumDialogEditJournalType.EDIT_PROJECT, currentValue);
break;
}
return true;
*/
case R.id.dialog_overflow_edit_journal_delete: // Delete the current row
switch(type){
case EDIT_TAG:
showDeleteTagProjectDialog(context, EnumDialogEditJournalType.DELETE_TAG, tagList, position);
break;
case EDIT_PROJECT:
showDeleteTagProjectDialog(context, EnumDialogEditJournalType.DELETE_PROJECT, tagList, position);
break;
}
return true;
default:
return super.onMenuItemSelected(menu, item);
}
}
};
menu.inflate(R.menu.menu_overflow_dialog_journal_edit);
menu.show();
}
public void showCountryListPopUpMenu(final Context context, View v, CountryList list){
PopupMenu menu = new PopupMenu(context, v){
@Override
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
switch (item.getItemId()) {
default:
return super.onMenuItemSelected(menu, item);
}
}
};
for(Country country : list.getList()){
menu.getMenu().add(country.getCountry());
}
menu.show();
}
public Rect locateView(View v)
{
int[] loc_int = new int[2];
if (v == null) return null;
try
{
v.getLocationOnScreen(loc_int);
} catch (NullPointerException npe)
{
//Happens when the view doesn't exist on screen anymore.
return null;
}
Rect location = new Rect();
location.left = loc_int[0];
location.top = loc_int[1];
location.right = location.left + v.getWidth();
location.bottom = location.top + v.getHeight();
return location;
}
/*=========== ACCESS TO PREFERENCE ===========*/
public void addPreferenceTagSet(Context context, TagSet addSet) {
mLogging.debug(TAG, "addPreferenceTagSet start");
TagSet currentSet = this.retrievePreferenceTagSet(context);
if(currentSet != null) {
currentSet.add(addSet);
this.savePreferenceTagSet(context, currentSet);
}else{
this.savePreferenceTagSet(context, addSet);
}
mLogging.debug(TAG, "addPreferenceTagSet done");
}
public TagSet retrievePreferenceTagSet(Context context){
mLogging.debug(TAG, "retrievePreferenceTagSet");
try{
String value = this.mPref.getTags(context);
mLogging.debug(TAG, "retrievePreferenceTagSet value => " + value);
if(!mParser.isStringEmpty(value)){
return mParser.parseJsonToTagSet(value);
}
return null;
}catch (FileNotFoundException e){
mLogging.debug(TAG, "error -> " + e.getMessage());
e.printStackTrace();
}catch (IOException e){
mLogging.debug(TAG, "error -> " + e.getMessage());
e.printStackTrace();
}
return null;
}
public void savePreferenceTagSet(Context context, TagSet set){
mLogging.debug(TAG, "savePreferenceTagSet");
try{
String value = mParser.parseTagSetToJson(set);
mLogging.debug(TAG, "savePreferenceTagSet value => " + value);
this.mPref.setTags(context, value);
}catch (FileNotFoundException e){
mLogging.debug(TAG, "error -> " + e.getMessage());
e.printStackTrace();
}catch (IOException e){
mLogging.debug(TAG, "error -> " + e.getMessage());
e.printStackTrace();
}
}
public void showToastLong(Context context, String message) {
Toast.makeText(context, message,
Toast.LENGTH_LONG).show();
}
public void showToastShort(Context context, String message) {
Toast.makeText(context, message,
Toast.LENGTH_SHORT).show();
}
}
| |
/*
* 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.operators;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.io.CleanupWhenUnsuccessful;
import org.apache.flink.api.common.io.OutputFormat;
import org.apache.flink.api.common.io.RichOutputFormat;
import org.apache.flink.api.common.typeutils.TypeComparatorFactory;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerFactory;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.io.IOReadableWritable;
import org.apache.flink.metrics.Counter;
import org.apache.flink.metrics.SimpleCounter;
import org.apache.flink.runtime.execution.CancelTaskException;
import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.io.network.api.reader.MutableReader;
import org.apache.flink.runtime.io.network.api.reader.MutableRecordReader;
import org.apache.flink.runtime.io.network.partition.consumer.UnionInputGate;
import org.apache.flink.runtime.jobgraph.InputOutputFormatContainer;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.metrics.groups.InternalOperatorIOMetricGroup;
import org.apache.flink.runtime.metrics.groups.InternalOperatorMetricGroup;
import org.apache.flink.runtime.operators.chaining.ExceptionInChainedStubException;
import org.apache.flink.runtime.operators.sort.ExternalSorter;
import org.apache.flink.runtime.operators.sort.Sorter;
import org.apache.flink.runtime.operators.util.CloseableInputProvider;
import org.apache.flink.runtime.operators.util.DistributedRuntimeUDFContext;
import org.apache.flink.runtime.operators.util.ReaderIterator;
import org.apache.flink.runtime.operators.util.TaskConfig;
import org.apache.flink.runtime.plugable.DeserializationDelegate;
import org.apache.flink.util.MutableObjectIterator;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* DataSinkTask which is executed by a task manager. The task hands the data to an output format.
*
* @see OutputFormat
*/
public class DataSinkTask<IT> extends AbstractInvokable {
// Obtain DataSinkTask Logger
private static final Logger LOG = LoggerFactory.getLogger(DataSinkTask.class);
// --------------------------------------------------------------------------------------------
// OutputFormat instance. volatile, because the asynchronous canceller may access it
private volatile OutputFormat<IT> format;
private MutableReader<?> inputReader;
// input reader
private MutableObjectIterator<IT> reader;
// The serializer for the input type
private TypeSerializerFactory<IT> inputTypeSerializerFactory;
// local strategy
private CloseableInputProvider<IT> localStrategy;
// task configuration
private TaskConfig config;
// cancel flag
private volatile boolean taskCanceled;
private volatile boolean cleanupCalled;
/**
* Create an Invokable task and set its environment.
*
* @param environment The environment assigned to this invokable.
*/
public DataSinkTask(Environment environment) {
super(environment);
}
@Override
public void invoke() throws Exception {
// --------------------------------------------------------------------
// Initialize
// --------------------------------------------------------------------
LOG.debug(getLogString("Start registering input and output"));
// initialize OutputFormat
initOutputFormat();
// initialize input readers
try {
initInputReaders();
} catch (Exception e) {
throw new RuntimeException(
"Initializing the input streams failed"
+ (e.getMessage() == null ? "." : ": " + e.getMessage()),
e);
}
LOG.debug(getLogString("Finished registering input and output"));
// --------------------------------------------------------------------
// Invoke
// --------------------------------------------------------------------
LOG.debug(getLogString("Starting data sink operator"));
RuntimeContext ctx = createRuntimeContext();
final Counter numRecordsIn;
{
Counter tmpNumRecordsIn;
try {
InternalOperatorIOMetricGroup ioMetricGroup =
((InternalOperatorMetricGroup) ctx.getMetricGroup()).getIOMetricGroup();
ioMetricGroup.reuseInputMetricsForTask();
ioMetricGroup.reuseOutputMetricsForTask();
tmpNumRecordsIn = ioMetricGroup.getNumRecordsInCounter();
} catch (Exception e) {
LOG.warn("An exception occurred during the metrics setup.", e);
tmpNumRecordsIn = new SimpleCounter();
}
numRecordsIn = tmpNumRecordsIn;
}
if (RichOutputFormat.class.isAssignableFrom(this.format.getClass())) {
((RichOutputFormat) this.format).setRuntimeContext(ctx);
LOG.debug(getLogString("Rich Sink detected. Initializing runtime context."));
}
ExecutionConfig executionConfig = getExecutionConfig();
boolean objectReuseEnabled = executionConfig.isObjectReuseEnabled();
try {
// initialize local strategies
MutableObjectIterator<IT> input1;
switch (this.config.getInputLocalStrategy(0)) {
case NONE:
// nothing to do
localStrategy = null;
input1 = reader;
break;
case SORT:
// initialize sort local strategy
try {
// get type comparator
TypeComparatorFactory<IT> compFact =
this.config.getInputComparator(0, getUserCodeClassLoader());
if (compFact == null) {
throw new Exception(
"Missing comparator factory for local strategy on input " + 0);
}
// initialize sorter
Sorter<IT> sorter =
ExternalSorter.newBuilder(
getEnvironment().getMemoryManager(),
this,
this.inputTypeSerializerFactory.getSerializer(),
compFact.createComparator())
.maxNumFileHandles(this.config.getFilehandlesInput(0))
.enableSpilling(
getEnvironment().getIOManager(),
this.config.getSpillingThresholdInput(0))
.memoryFraction(this.config.getRelativeMemoryInput(0))
.objectReuse(
this.getExecutionConfig().isObjectReuseEnabled())
.largeRecords(this.config.getUseLargeRecordHandler())
.build(this.reader);
this.localStrategy = sorter;
input1 = sorter.getIterator();
} catch (Exception e) {
throw new RuntimeException(
"Initializing the input processing failed"
+ (e.getMessage() == null ? "." : ": " + e.getMessage()),
e);
}
break;
default:
throw new RuntimeException("Invalid local strategy for DataSinkTask");
}
// read the reader and write it to the output
final TypeSerializer<IT> serializer = this.inputTypeSerializerFactory.getSerializer();
final MutableObjectIterator<IT> input = input1;
final OutputFormat<IT> format = this.format;
// check if task has been canceled
if (this.taskCanceled) {
return;
}
LOG.debug(getLogString("Starting to produce output"));
// open
format.open(
this.getEnvironment().getTaskInfo().getIndexOfThisSubtask(),
this.getEnvironment().getTaskInfo().getNumberOfParallelSubtasks());
if (objectReuseEnabled) {
IT record = serializer.createInstance();
// work!
while (!this.taskCanceled && ((record = input.next(record)) != null)) {
numRecordsIn.inc();
format.writeRecord(record);
}
} else {
IT record;
// work!
while (!this.taskCanceled && ((record = input.next()) != null)) {
numRecordsIn.inc();
format.writeRecord(record);
}
}
// close. We close here such that a regular close throwing an exception marks a task as
// failed.
if (!this.taskCanceled) {
this.format.close();
this.format = null;
}
} catch (Exception ex) {
// make a best effort to clean up
try {
if (!cleanupCalled && format instanceof CleanupWhenUnsuccessful) {
cleanupCalled = true;
((CleanupWhenUnsuccessful) format).tryCleanupOnError();
}
} catch (Throwable t) {
LOG.error("Cleanup on error failed.", t);
}
ex = ExceptionInChainedStubException.exceptionUnwrap(ex);
if (ex instanceof CancelTaskException) {
// forward canceling exception
throw ex;
}
// drop, if the task was canceled
else if (!this.taskCanceled) {
if (LOG.isErrorEnabled()) {
LOG.error(getLogString("Error in user code: " + ex.getMessage()), ex);
}
throw ex;
}
} finally {
if (this.format != null) {
// close format, if it has not been closed, yet.
// This should only be the case if we had a previous error, or were canceled.
try {
this.format.close();
} catch (Throwable t) {
if (LOG.isWarnEnabled()) {
LOG.warn(getLogString("Error closing the output format"), t);
}
}
}
// close local strategy if necessary
if (localStrategy != null) {
try {
this.localStrategy.close();
} catch (Throwable t) {
LOG.error("Error closing local strategy", t);
}
}
BatchTask.clearReaders(new MutableReader<?>[] {inputReader});
}
if (!this.taskCanceled) {
LOG.debug(getLogString("Finished data sink operator"));
} else {
LOG.debug(getLogString("Data sink operator cancelled"));
}
}
@Override
public void cancel() throws Exception {
this.taskCanceled = true;
OutputFormat<IT> format = this.format;
if (format != null) {
try {
this.format.close();
} catch (Throwable t) {
}
// make a best effort to clean up
try {
if (!cleanupCalled && format instanceof CleanupWhenUnsuccessful) {
cleanupCalled = true;
((CleanupWhenUnsuccessful) format).tryCleanupOnError();
}
} catch (Throwable t) {
LOG.error("Cleanup on error failed.", t);
}
}
LOG.debug(getLogString("Cancelling data sink operator"));
}
/**
* Initializes the OutputFormat implementation and configuration.
*
* @throws RuntimeException Throws if instance of OutputFormat implementation can not be
* obtained.
*/
private void initOutputFormat() {
ClassLoader userCodeClassLoader = getUserCodeClassLoader();
// obtain task configuration (including stub parameters)
Configuration taskConf = getTaskConfiguration();
this.config = new TaskConfig(taskConf);
final Pair<OperatorID, OutputFormat<IT>> operatorIDAndOutputFormat;
InputOutputFormatContainer formatContainer =
new InputOutputFormatContainer(config, userCodeClassLoader);
try {
operatorIDAndOutputFormat = formatContainer.getUniqueOutputFormat();
this.format = operatorIDAndOutputFormat.getValue();
// check if the class is a subclass, if the check is required
if (!OutputFormat.class.isAssignableFrom(this.format.getClass())) {
throw new RuntimeException(
"The class '"
+ this.format.getClass().getName()
+ "' is not a subclass of '"
+ OutputFormat.class.getName()
+ "' as is required.");
}
} catch (ClassCastException ccex) {
throw new RuntimeException(
"The stub class is not a proper subclass of " + OutputFormat.class.getName(),
ccex);
}
Thread thread = Thread.currentThread();
ClassLoader original = thread.getContextClassLoader();
// configure the stub. catch exceptions here extra, to report them as originating from the
// user code
try {
thread.setContextClassLoader(userCodeClassLoader);
this.format.configure(
formatContainer.getParameters(operatorIDAndOutputFormat.getKey()));
} catch (Throwable t) {
throw new RuntimeException(
"The user defined 'configure()' method in the Output Format caused an error: "
+ t.getMessage(),
t);
} finally {
thread.setContextClassLoader(original);
}
}
/**
* Initializes the input readers of the DataSinkTask.
*
* @throws RuntimeException Thrown in case of invalid task input configuration.
*/
@SuppressWarnings("unchecked")
private void initInputReaders() throws Exception {
int numGates = 0;
// ---------------- create the input readers ---------------------
// in case where a logical input unions multiple physical inputs, create a union reader
final int groupSize = this.config.getGroupSize(0);
numGates += groupSize;
if (groupSize == 1) {
// non-union case
inputReader =
new MutableRecordReader<DeserializationDelegate<IT>>(
getEnvironment().getInputGate(0),
getEnvironment().getTaskManagerInfo().getTmpDirectories());
} else if (groupSize > 1) {
// union case
inputReader =
new MutableRecordReader<IOReadableWritable>(
new UnionInputGate(getEnvironment().getAllInputGates()),
getEnvironment().getTaskManagerInfo().getTmpDirectories());
} else {
throw new Exception("Illegal input group size in task configuration: " + groupSize);
}
this.inputTypeSerializerFactory =
this.config.getInputSerializer(0, getUserCodeClassLoader());
@SuppressWarnings({"rawtypes"})
final MutableObjectIterator<?> iter =
new ReaderIterator(inputReader, this.inputTypeSerializerFactory.getSerializer());
this.reader = (MutableObjectIterator<IT>) iter;
// final sanity check
if (numGates != this.config.getNumInputs()) {
throw new Exception(
"Illegal configuration: Number of input gates and group sizes are not consistent.");
}
}
// ------------------------------------------------------------------------
// Utilities
// ------------------------------------------------------------------------
/**
* Utility function that composes a string for logging purposes. The string includes the given
* message and the index of the task in its task group together with the number of tasks in the
* task group.
*
* @param message The main message for the log.
* @return The string ready for logging.
*/
private String getLogString(String message) {
return BatchTask.constructLogString(
message, this.getEnvironment().getTaskInfo().getTaskName(), this);
}
public DistributedRuntimeUDFContext createRuntimeContext() {
Environment env = getEnvironment();
return new DistributedRuntimeUDFContext(
env.getTaskInfo(),
env.getUserCodeClassLoader(),
getExecutionConfig(),
env.getDistributedCacheEntries(),
env.getAccumulatorRegistry().getUserMap(),
getEnvironment()
.getMetricGroup()
.getOrAddOperator(getEnvironment().getTaskInfo().getTaskName()),
env.getExternalResourceInfoProvider(),
env.getJobID());
}
}
| |
package org.kie.dockerui.client.views;
import com.bradrydzewski.gwt.calendar.client.Appointment;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ButtonCell;
import com.github.gwtbootstrap.client.ui.CellTable;
import com.github.gwtbootstrap.client.ui.IconCell;
import com.github.gwtbootstrap.client.ui.constants.IconSize;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.view.client.*;
import org.kie.dockerui.client.KieClientManager;
import org.kie.dockerui.client.Log;
import org.kie.dockerui.client.resources.i18n.Constants;
import org.kie.dockerui.client.service.DockerService;
import org.kie.dockerui.client.service.DockerServiceAsync;
import org.kie.dockerui.client.service.SettingsClientHolder;
import org.kie.dockerui.client.util.ClientUtils;
import org.kie.dockerui.client.widgets.ClickableImageResourceCell;
import org.kie.dockerui.client.widgets.ImageTypesCell;
import org.kie.dockerui.client.widgets.KieCalendar;
import org.kie.dockerui.client.widgets.TimeoutPopupPanel;
import org.kie.dockerui.shared.model.KieAppStatus;
import org.kie.dockerui.shared.model.KieContainer;
import org.kie.dockerui.shared.model.KieImage;
import org.kie.dockerui.shared.settings.Settings;
import org.kie.dockerui.shared.util.SharedUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class ImagesView extends Composite {
interface ImagesViewBinder extends UiBinder<Widget, ImagesView> {}
private static ImagesViewBinder uiBinder = GWT.create(ImagesViewBinder.class);
interface ImagesViewStyle extends CssResource {
String mainPanel();
String imagesPanel();
String imagesList();
String loadingPanel();
String calendarPanel();
String calendar();
String refreshButton();
String calendarButton();
String headerPanel();
}
@UiField
ImagesViewStyle style;
@UiField
FlowPanel mainPanel;
@UiField
Button refreshButton;
@UiField
TimeoutPopupPanel loadingPanel;
@UiField
TimeoutPopupPanel pullPanel;
@UiField
HTML pullText;
@UiField
HTMLPanel imagesPanel;
@UiField(provided = true)
CellTable imagesGrid;
@UiField(provided = true)
SimplePager pager;
@UiField
DisclosurePanel calendarDisclosurePanel;
@UiField
FlowPanel calendarPanel;
private final DockerServiceAsync dockerService = GWT.create(DockerService.class);
private Settings settings = null;
private final KieCalendar calendar = new KieCalendar();
/**
* The provider that holds the list of containers.
*/
private final ListDataProvider<KieImage> imagesProvider = new ListDataProvider<KieImage>();
@UiConstructor
public ImagesView() {
// Init the image list grid.
initImagesGrid();
initWidget(uiBinder.createAndBindUi(this));
// Calendar.
calendar.setWidth("1600px");
calendar.setHeight("340px");
calendar.setDays(7);
calendar.addStyleName(style.calendar());
calendarPanel.add(calendar);
// Refresh button handler.
refreshButton.addClickHandler(refreshButtonClickHandler);
// Calendar appointment open handler.
calendar.addOpenHandler(appointmentOpenHandler);
}
private final ClickHandler refreshButtonClickHandler = new ClickHandler() {
@Override
public void onClick(final ClickEvent event) {
showLoadingView();
KieClientManager.getInstance().reload(new KieClientManager.KieClientManagerCallback() {
@Override
public void onFailure(final Throwable caught) {
showError(caught);
}
@Override
public void onSuccess() {
hideLoadingView();
show();
}
});
}
};
private final OpenHandler<Appointment> appointmentOpenHandler = new OpenHandler<Appointment>() {
@Override
public void onOpen(final OpenEvent<Appointment> event) {
showLoadingView();
final Appointment appt = event.getTarget();
final String imageId = appt.getId();
dockerService.getImage(imageId, new AsyncCallback<KieImage>() {
@Override
public void onFailure(final Throwable caught) {
showError(caught);
}
@Override
public void onSuccess(final KieImage result) {
if (result != null) {
final List<KieImage> list = new ArrayList<KieImage>(1);
list.add(result);
imagesProvider.setList(list);
redrawTable();
} else {
showError(Constants.INSTANCE.notAvailable());
}
hideLoadingView();
}
});
}
};
private static final ProvidesKey<KieImage> KEY_PROVIDER = new ProvidesKey<KieImage>() {
@Override
public Object getKey(KieImage item) {
return item == null ? null : item.getId();
}
};
/**
* Add a new image into the grid provider's list.
*
* @param image the image to add.
*/
public void addImage(KieImage image) {
List<KieImage> contacts = imagesProvider.getList();
// Remove the contact first so we don't add a duplicate.
contacts.remove(image);
contacts.add(image);
}
public void show() {
clear();
showLoadingView();
// Build calendar.
showCalendar();
// Images table.
final KieClientManager kieClientManager = KieClientManager.getInstance();
final List<KieImage> kieImages = kieClientManager.getImages();
if (kieImages != null) {
for (final KieImage kieImage : kieImages) {
addImage(kieImage);
}
redrawTable();
hideLoadingView();
}
mainPanel.setVisible(true);
}
public void show(final List<KieImage> images) {
clear();
showLoadingView();
if (images != null) {
for (final KieImage kieImage : images) {
addImage(kieImage);
}
redrawTable();
hideLoadingView();
}
mainPanel.setVisible(true);
}
private void showCalendar() {
calendar.show();
calendarDisclosurePanel.setVisible(true);
}
private void initImagesGrid() {
imagesGrid = new CellTable<KieImage>(KEY_PROVIDER);
imagesGrid.setWidth("100%", true);
// Do not refresh the headers and footers every time the data is updated.
imagesGrid.setAutoHeaderRefreshDisabled(true);
imagesGrid.setAutoFooterRefreshDisabled(true);
// Attach a column sort handler to the ListDataProvider to sort the list.
ColumnSortEvent.ListHandler<KieImage> sortHandler = new ColumnSortEvent.ListHandler<KieImage>(imagesProvider.getList());
imagesGrid.addColumnSortHandler(sortHandler);
// Create a Pager to control the table.
SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
pager = new SimplePager(SimplePager.TextLocation.CENTER, pagerResources, false, 0, true);
pager.setDisplay(imagesGrid);
// Add a selection model so we can select cells.
final SelectionModel<KieImage> selectionModel = new MultiSelectionModel<KieImage>(KEY_PROVIDER);
imagesGrid.setSelectionModel(selectionModel,
DefaultSelectionEventManager.<KieContainer>createCheckboxManager());
// Initialize the columns.
initTableColumns(selectionModel, sortHandler);
// Add the CellList to the adapter in the database.
addDataDisplay(imagesGrid);
}
private void initTableColumns(SelectionModel<KieImage> selectionModel, ColumnSortEvent.ListHandler<KieImage> sortHandler) {
// Image status.
final ClickableImageResourceCell statusCell = new ClickableImageResourceCell();
final Column<KieImage, ImageResource> statusColumn = new Column<KieImage, ImageResource>(statusCell) {
@Override
public ImageResource getValue(final KieImage image) {
final KieAppStatus status = image.getAppStatus();
final ImageResource imageResource = ClientUtils.getStatusImage(status);
final String iconTooltip = ClientUtils.getStatusText(status);
statusCell.setTooltip(new SafeHtmlBuilder().appendEscaped(iconTooltip).toSafeHtml().asString());
return imageResource;
}
};
imagesGrid.addColumn(statusColumn, Constants.INSTANCE.containerStatus());
imagesGrid.setColumnWidth(statusColumn, 2, Style.Unit.PCT);
// Image id.
final Column<KieImage, String> idColumn = new Column<KieImage, String>(
new EditTextCell()) {
@Override
public String getValue(KieImage object) {
return object.getTruncId();
}
};
idColumn.setSortable(true);
sortHandler.setComparator(idColumn, new Comparator<KieImage>() {
@Override
public int compare(KieImage o1, KieImage o2) {
return o1.getId().compareTo(o2.getId());
}
});
imagesGrid.addColumn(idColumn, Constants.INSTANCE.imageId());
imagesGrid.setColumnWidth(idColumn, 5, Style.Unit.PCT);
// Image type cells.
final Column<KieImage, KieImage> typeColumn = new Column<KieImage, KieImage>(new ImageTypesCell()) {
@Override
public KieImage getValue(KieImage container) {
return container;
}
};
imagesGrid.addColumn(typeColumn, Constants.INSTANCE.categories());
imagesGrid.setColumnWidth(typeColumn, 5, Style.Unit.PCT);
// Repository.
final Column<KieImage, String> imageColumn = new Column<KieImage, String>(
new TextCell()) {
@Override
public String getValue(final KieImage object) {
return object.getRepository();
}
};
imageColumn.setSortable(true);
sortHandler.setComparator(imageColumn, new Comparator<KieImage>() {
@Override
public int compare(KieImage o1, KieImage o2) {
return o1.getRepository().compareTo(o2.getRepository());
}
});
imagesGrid.addColumn(imageColumn, Constants.INSTANCE.imageRepository());
imagesGrid.setColumnWidth(imageColumn, 5, Style.Unit.PCT);
// Tag.
final Column<KieImage, String> tagColumn = new Column<KieImage, String>(
new TextCell()) {
@Override
public String getValue(final KieImage object) {
return object.getTags().toString();
}
};
tagColumn.setSortable(false);
imagesGrid.addColumn(tagColumn, Constants.INSTANCE.tags());
imagesGrid.setColumnWidth(tagColumn, 10, Style.Unit.PCT);
// Image creation date.
final Column<KieImage, String> creationDateColumn = new Column<KieImage, String>(
new TextCell()) {
@Override
public String getValue(final KieImage object) {
return DateTimeFormat.getMediumDateTimeFormat().format(object.getCreated());
}
};
creationDateColumn.setSortable(false);
imagesGrid.addColumn(creationDateColumn, Constants.INSTANCE.imageCreationDate());
imagesGrid.setColumnWidth(creationDateColumn, 5, Style.Unit.PCT);
// Explore containers.
final Column<KieImage, String> containersColumn = new Column<KieImage, String>(
new ButtonCell()) {
@Override
public String getValue(final KieImage object) {
return Constants.INSTANCE.view();
}
};
containersColumn.setFieldUpdater(new FieldUpdater<KieImage, String>() {
@Override
public void update(final int index, final KieImage image, final String value) {
showContainers(image);
}
});
containersColumn.setSortable(false);
imagesGrid.addColumn(containersColumn, Constants.INSTANCE.containers());
imagesGrid.setColumnWidth(containersColumn, 2, Style.Unit.PCT);
if (getSettings().isRegistryEnabled()) {
// Pull image.
final Column<KieImage, String> pullColumn = new Column<KieImage, String>(
new ButtonCell()) {
@Override
public String getValue(final KieImage object) {
return Constants.INSTANCE.pull();
}
};
pullColumn.setFieldUpdater(new FieldUpdater<KieImage, String>() {
@Override
public void update(final int index, final KieImage image, final String value) {
pullImage(image);
}
});
pullColumn.setSortable(false);
imagesGrid.addColumn(pullColumn, Constants.INSTANCE.pull());
imagesGrid.setColumnWidth(pullColumn, 2, Style.Unit.PCT);
}
}
private void pullImage(final KieImage image) {
if (image == null) {
showPopup(Constants.INSTANCE.notAvailable());
} else {
final String pull = SharedUtils.getPullAddress(image, getSettings());
showPullView(pull);
}
}
private void showContainers(final KieImage image) {
showLoadingView();
final KieClientManager kieClientManager = KieClientManager.getInstance();
final List<KieContainer> containers = kieClientManager.getContainers();
if (containers != null) {
final String i = SharedUtils.getImage(image.getRegistry(), image.getRepository(), image.getTags().iterator().next());
final List<KieContainer> result = new LinkedList<KieContainer>();
for (final KieContainer container : containers) {
final String _image = container.getImage();
if (i.equalsIgnoreCase(_image)) result.add(container);
}
hideLoadingView();
fireEvent(new ShowContainersEvent(result));
}
}
private void redrawTable() {
hideLoadingView();
imagesGrid.redraw();
}
private void addDataDisplay(HasData<KieImage> display) {
imagesProvider.addDataDisplay(display);
}
public void clear() {
hideLoadingView();
hidePullView();
calendarDisclosurePanel.setVisible(false);
mainPanel.setVisible(false);
imagesProvider.getList().clear();
}
private void showError(final Throwable throwable) {
showError("ERROR on ImagesView. Exception: " + throwable.getMessage());
}
private void showPopup(final String message) {
Window.alert(message);
}
private void showError(final String message) {
hidePullView();
hideLoadingView();
Log.log(message);
}
private void showLoadingView() {
loadingPanel.center();
loadingPanel.setVisible(true);
loadingPanel.getElement().getStyle().setDisplay(Style.Display.BLOCK);
loadingPanel.show();
}
private void hideLoadingView() {
loadingPanel.setVisible(false);
loadingPanel.getElement().getStyle().setDisplay(Style.Display.NONE);
loadingPanel.hide();
}
private void showPullView(final String pull) {
pullText.setText(pull);
pullPanel.center();
pullPanel.setVisible(true);
pullPanel.getElement().getStyle().setDisplay(Style.Display.BLOCK);
pullPanel.show();
}
private void hidePullView() {
pullPanel.setVisible(false);
pullPanel.getElement().getStyle().setDisplay(Style.Display.NONE);
pullPanel.hide();
}
private Settings getSettings() {
if (settings == null) {
settings = SettingsClientHolder.getInstance().getSettings();
}
return settings;
}
// ****************************************************
// SHOW CONTAINERS EVENT
// ****************************************************
public interface ShowContainersEventHandler extends EventHandler
{
void onShowContainers(ShowContainersEvent event);
}
public static class ShowContainersEvent extends GwtEvent<ShowContainersEventHandler> {
public static Type<ShowContainersEventHandler> TYPE = new Type<ShowContainersEventHandler>();
private List<KieContainer> containers;
public ShowContainersEvent(final List<KieContainer> containers) {
super();
this.containers = containers;
}
@Override
public Type getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(ShowContainersEventHandler handler) {
handler.onShowContainers(this);
}
public List<KieContainer> getContainers() {
return containers;
}
}
public HandlerRegistration addShowContainersEventHandler(final ShowContainersEventHandler handler) {
return addHandler(handler, ShowContainersEvent.TYPE);
}
}
| |
// Copyright 2017 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.lib.rules.genrule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.CompositeRunfilesSupplier;
import com.google.devtools.build.lib.analysis.AliasProvider;
import com.google.devtools.build.lib.analysis.CommandHelper;
import com.google.devtools.build.lib.analysis.ConfigurationMakeVariableContext;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.Runfiles;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.TemplateVariableInfo;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.stringtemplate.ExpansionException;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.packages.TargetUtils;
import com.google.devtools.build.lib.rules.cpp.CcCommon.CcFlagsSupplier;
import com.google.devtools.build.lib.rules.cpp.CppHelper;
import com.google.devtools.build.lib.rules.java.JavaHelper;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.LazyString;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* A base implementation of genrule, to be used by specific implementing rules which can change some
* of the semantics around when the execution info and inputs are changed.
*/
public abstract class GenRuleBase implements RuleConfiguredTargetFactory {
private static final Pattern CROSSTOOL_MAKE_VARIABLE =
Pattern.compile("\\$\\((CC|CC_FLAGS|AR|NM|OBJCOPY|STRIP|GCOVTOOL)\\)");
private static final Pattern JDK_MAKE_VARIABLE =
Pattern.compile("\\$\\((JAVABASE|JAVA)\\)");
protected static boolean requiresCrosstool(String command) {
return CROSSTOOL_MAKE_VARIABLE.matcher(command).find();
}
protected boolean requiresJdk(String command) {
return JDK_MAKE_VARIABLE.matcher(command).find();
}
/**
* Returns a {@link Map} of execution info, which will be used in later processing to construct
* the actual command line that will be executed.
*
* <p>GenRule implementations can override this method to include additional specific information
* needed.
*/
protected Map<String, String> getExtraExecutionInfo(RuleContext ruleContext, String command) {
return ImmutableMap.of();
}
/**
* Returns an {@link Iterable} of {@link NestedSet}s, which will be added to the genrule's inputs
* using the {@link NestedSetBuilder#addTransitive} method.
*
* <p>GenRule implementations can override this method to better control what inputs are needed
* for specific command inputs.
*/
protected Iterable<NestedSet<Artifact>> getExtraInputArtifacts(
RuleContext ruleContext, String command) {
return ImmutableList.of();
}
/**
* Returns {@code true} if the rule should be stamped.
*
* <p>Genrule implementations can set this based on the rule context, including by defining their
* own attributes over and above what is present in {@link GenRuleBaseRule}.
*/
protected abstract boolean isStampingEnabled(RuleContext ruleContext);
/**
* Updates the {@link RuleConfiguredTargetBuilder} that is used for this rule.
*
* <p>GenRule implementations can override this method to enhance and update the builder without
* needing to entirely override the {@link #create} method.
*/
protected RuleConfiguredTargetBuilder updateBuilder(
RuleConfiguredTargetBuilder builder,
RuleContext ruleContext,
NestedSet<Artifact> filesToBuild) {
return builder;
}
@Override
public ConfiguredTarget create(RuleContext ruleContext)
throws RuleErrorException, InterruptedException {
NestedSet<Artifact> filesToBuild =
NestedSetBuilder.wrap(Order.STABLE_ORDER, ruleContext.getOutputArtifacts());
NestedSetBuilder<Artifact> resolvedSrcsBuilder = NestedSetBuilder.stableOrder();
if (filesToBuild.isEmpty()) {
ruleContext.attributeError("outs", "Genrules without outputs don't make sense");
}
if (ruleContext.attributes().get("executable", Type.BOOLEAN)
&& Iterables.size(filesToBuild) > 1) {
ruleContext.attributeError(
"executable",
"if genrules produce executables, they are allowed only one output. "
+ "If you need the executable=1 argument, then you should split this genrule into "
+ "genrules producing single outputs");
}
ImmutableMap.Builder<Label, NestedSet<Artifact>> labelMap = ImmutableMap.builder();
for (TransitiveInfoCollection dep : ruleContext.getPrerequisites("srcs", Mode.TARGET)) {
// This target provides specific types of files for genrules.
GenRuleSourcesProvider provider = dep.getProvider(GenRuleSourcesProvider.class);
NestedSet<Artifact> files = (provider != null)
? provider.getGenruleFiles()
: dep.getProvider(FileProvider.class).getFilesToBuild();
resolvedSrcsBuilder.addTransitive(files);
labelMap.put(AliasProvider.getDependencyLabel(dep), files);
}
NestedSet<Artifact> resolvedSrcs = resolvedSrcsBuilder.build();
CommandHelper commandHelper =
new CommandHelper(
ruleContext, ruleContext.getPrerequisites("tools", Mode.HOST), labelMap.build());
if (ruleContext.hasErrors()) {
return null;
}
String baseCommand = commandHelper.resolveCommandAndHeuristicallyExpandLabels(
ruleContext.attributes().get("cmd", Type.STRING),
"cmd",
ruleContext.attributes().get("heuristic_label_expansion", Type.BOOLEAN));
// Adds the genrule environment setup script before the actual shell command
String command = String.format("source %s; %s",
ruleContext.getPrerequisiteArtifact("$genrule_setup", Mode.HOST).getExecPath(),
baseCommand);
command = resolveCommand(command, ruleContext, resolvedSrcs, filesToBuild);
String messageAttr = ruleContext.attributes().get("message", Type.STRING);
String message = messageAttr.isEmpty() ? "Executing genrule" : messageAttr;
Label label = ruleContext.getLabel();
LazyString progressMessage =
new LazyString() {
@Override
public String toString() {
return message + " " + label;
}
};
Map<String, String> executionInfo = Maps.newLinkedHashMap();
executionInfo.putAll(TargetUtils.getExecutionInfo(ruleContext.getRule()));
if (ruleContext.attributes().get("local", Type.BOOLEAN)) {
executionInfo.put("local", "");
}
executionInfo.putAll(getExtraExecutionInfo(ruleContext, baseCommand));
NestedSetBuilder<Artifact> inputs = NestedSetBuilder.stableOrder();
inputs.addTransitive(resolvedSrcs);
inputs.addAll(commandHelper.getResolvedTools());
FilesToRunProvider genruleSetup =
ruleContext.getPrerequisite("$genrule_setup", Mode.HOST, FilesToRunProvider.class);
inputs.addTransitive(genruleSetup.getFilesToRun());
List<String> argv = commandHelper.buildCommandLine(command, inputs, ".genrule_script.sh",
ImmutableMap.copyOf(executionInfo));
// TODO(bazel-team): Make the make variable expander pass back a list of these.
if (requiresCrosstool(baseCommand)) {
// If cc is used, silently throw in the crosstool filegroup as a dependency.
inputs.addTransitive(
CppHelper.getToolchainUsingDefaultCcToolchainAttribute(ruleContext)
.getCrosstoolMiddleman());
}
if (requiresJdk(baseCommand)) {
// If javac is used, silently throw in the jdk filegroup as a dependency.
// Note we expand Java-related variables with the *host* configuration.
inputs.addTransitive(JavaHelper.getHostJavabaseInputs(ruleContext));
}
for (NestedSet<Artifact> extraInputs : getExtraInputArtifacts(ruleContext, baseCommand)) {
inputs.addTransitive(extraInputs);
}
if (isStampingEnabled(ruleContext)) {
inputs.add(ruleContext.getAnalysisEnvironment().getStableWorkspaceStatusArtifact());
inputs.add(ruleContext.getAnalysisEnvironment().getVolatileWorkspaceStatusArtifact());
}
ruleContext.registerAction(
new GenRuleAction(
ruleContext.getActionOwner(),
ImmutableList.copyOf(commandHelper.getResolvedTools()),
inputs.build(),
filesToBuild,
argv,
ruleContext.getConfiguration().getActionEnvironment(),
ImmutableMap.copyOf(executionInfo),
new CompositeRunfilesSupplier(commandHelper.getToolsRunfilesSuppliers()),
progressMessage));
RunfilesProvider runfilesProvider = RunfilesProvider.withData(
// No runfiles provided if not a data dependency.
Runfiles.EMPTY,
// We only need to consider the outputs of a genrule
// No need to visit the dependencies of a genrule. They cross from the target into the host
// configuration, because the dependencies of a genrule are always built for the host
// configuration.
new Runfiles.Builder(
ruleContext.getWorkspaceName(),
ruleContext.getConfiguration().legacyExternalRunfiles())
.addTransitiveArtifacts(filesToBuild)
.build());
RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext)
.setFilesToBuild(filesToBuild)
.setRunfilesSupport(null, getExecutable(ruleContext, filesToBuild))
.addProvider(RunfilesProvider.class, runfilesProvider);
builder = updateBuilder(builder, ruleContext, filesToBuild);
return builder.build();
}
/**
* Returns the executable artifact, if the rule is marked as executable and there is only one
* artifact.
*/
private static Artifact getExecutable(RuleContext ruleContext, NestedSet<Artifact> filesToBuild) {
if (!ruleContext.attributes().get("executable", Type.BOOLEAN)) {
return null;
}
if (Iterables.size(filesToBuild) == 1) {
return Iterables.getOnlyElement(filesToBuild);
}
return null;
}
/**
* Resolves any variables, including make and genrule-specific variables, in the command and
* returns the expanded command.
*
* <p>GenRule implementations may override this method to perform additional expansions.
*/
protected String resolveCommand(String command, final RuleContext ruleContext,
final NestedSet<Artifact> resolvedSrcs, final NestedSet<Artifact> filesToBuild) {
return ruleContext
.getExpander(new CommandResolverContext(ruleContext, resolvedSrcs, filesToBuild))
.expand("cmd", command);
}
/**
* Implementation of {@link ConfigurationMakeVariableContext} used to expand variables in a
* genrule command string.
*/
protected static class CommandResolverContext extends ConfigurationMakeVariableContext {
private final RuleContext ruleContext;
private final NestedSet<Artifact> resolvedSrcs;
private final NestedSet<Artifact> filesToBuild;
private final Iterable<TemplateVariableInfo> toolchains;
public CommandResolverContext(
RuleContext ruleContext,
NestedSet<Artifact> resolvedSrcs,
NestedSet<Artifact> filesToBuild) {
super(
ruleContext.getMakeVariables(ImmutableList.of(":cc_toolchain")),
ruleContext.getRule().getPackage(),
ruleContext.getConfiguration(),
ImmutableList.of(new CcFlagsSupplier(ruleContext)));
this.ruleContext = ruleContext;
this.resolvedSrcs = resolvedSrcs;
this.filesToBuild = filesToBuild;
this.toolchains = ruleContext.getPrerequisites(
"toolchains", Mode.TARGET, TemplateVariableInfo.PROVIDER);
}
public RuleContext getRuleContext() {
return ruleContext;
}
private String resolveVariableFromToolchains(String variableName) {
for (TemplateVariableInfo info : toolchains) {
String result = info.getVariables().get(variableName);
if (result != null) {
return result;
}
}
return null;
}
@Override
public String lookupVariable(String variableName) throws ExpansionException {
if (variableName.equals("SRCS")) {
return Artifact.joinExecPaths(" ", resolvedSrcs);
}
if (variableName.equals("<")) {
return expandSingletonArtifact(resolvedSrcs, "$<", "input file");
}
if (variableName.equals("OUTS")) {
return Artifact.joinExecPaths(" ", filesToBuild);
}
if (variableName.equals("@")) {
return expandSingletonArtifact(filesToBuild, "$@", "output file");
}
if (variableName.equals("@D")) {
// The output directory. If there is only one filename in outs,
// this expands to the directory containing that file. If there are
// multiple filenames, this variable instead expands to the
// package's root directory in the genfiles tree, even if all the
// generated files belong to the same subdirectory!
if (Iterables.size(filesToBuild) == 1) {
Artifact outputFile = Iterables.getOnlyElement(filesToBuild);
PathFragment relativeOutputFile = outputFile.getExecPath();
if (relativeOutputFile.segmentCount() <= 1) {
// This should never happen, since the path should contain at
// least a package name and a file name.
throw new IllegalStateException(
"$(@D) for genrule " + ruleContext.getLabel() + " has less than one segment");
}
return relativeOutputFile.getParentDirectory().getPathString();
} else {
PathFragment dir;
if (ruleContext.getRule().hasBinaryOutput()) {
dir = ruleContext.getConfiguration().getBinFragment();
} else {
dir = ruleContext.getConfiguration().getGenfilesFragment();
}
PathFragment relPath =
ruleContext.getRule().getLabel().getPackageIdentifier().getSourceRoot();
return dir.getRelative(relPath).getPathString();
}
}
String valueFromToolchains = resolveVariableFromToolchains(variableName);
if (valueFromToolchains != null) {
return valueFromToolchains;
}
if (JDK_MAKE_VARIABLE.matcher("$(" + variableName + ")").find()) {
List<String> attributes = new ArrayList<>();
attributes.addAll(ConfigurationMakeVariableContext.DEFAULT_MAKE_VARIABLE_ATTRIBUTES);
attributes.add(":host_jdk");
return new ConfigurationMakeVariableContext(
ruleContext.getMakeVariables(attributes),
ruleContext.getTarget().getPackage(),
ruleContext.getHostConfiguration())
.lookupVariable(variableName);
}
return super.lookupVariable(variableName);
}
/**
* Returns the path of the sole element "artifacts", generating an exception with an informative
* error message iff the set is not a singleton. Used to expand "$<", "$@".
*/
private final String expandSingletonArtifact(Iterable<Artifact> artifacts,
String variable,
String artifactName)
throws ExpansionException {
if (Iterables.isEmpty(artifacts)) {
throw new ExpansionException("variable '" + variable
+ "' : no " + artifactName);
} else if (Iterables.size(artifacts) > 1) {
throw new ExpansionException("variable '" + variable
+ "' : more than one " + artifactName);
}
return Iterables.getOnlyElement(artifacts).getExecPathString();
}
}
}
| |
package com.mguidi.soa.generator.android;
import com.google.common.base.Objects;
import com.google.inject.Inject;
import com.mguidi.soa.generator.Libraries;
import com.mguidi.soa.generator.java.Utils;
import com.mguidi.soa.soa.Architecture;
import com.mguidi.soa.soa.Model;
import com.mguidi.soa.soa.Module;
import java.util.HashSet;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.xbase.lib.Extension;
@SuppressWarnings("all")
public class GradleBuildGenerator {
@Inject
@Extension
private Utils utils;
public CharSequence generateBuildModel(final Architecture architecture, final Resource resource) {
StringConcatenation _builder = new StringConcatenation();
_builder.append("apply plugin: \'com.android.library\'");
_builder.newLine();
_builder.newLine();
_builder.append("buildscript {");
_builder.newLine();
_builder.append(" ");
_builder.append("repositories {");
_builder.newLine();
_builder.append(" ");
_builder.append("jcenter()");
_builder.newLine();
_builder.append(" ");
_builder.append("}");
_builder.newLine();
_builder.append(" ");
_builder.append("dependencies {");
_builder.newLine();
_builder.append(" ");
_builder.append("classpath \'");
_builder.append(Libraries.GRADLE, " ");
_builder.append("\'");
_builder.newLineIfNotEmpty();
_builder.append(" ");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("android {");
_builder.newLine();
_builder.append(" ");
_builder.append("compileSdkVersion ");
_builder.append(Libraries.COMPILE_SDK_VERSION, " ");
_builder.newLineIfNotEmpty();
_builder.append(" ");
_builder.append("buildToolsVersion \"");
_builder.append(Libraries.BUILD_TOOLS_VERSIONE, " ");
_builder.append("\"");
_builder.newLineIfNotEmpty();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("task androidSourcesJar(type: Jar) {");
_builder.newLine();
_builder.append("\t");
_builder.append("classifier = \'sources\'");
_builder.newLine();
_builder.append("\t");
_builder.append("from android.sourceSets.main.java.srcDirs");
_builder.newLine();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("artifacts {");
_builder.newLine();
_builder.append("\t");
_builder.append("archives androidSourcesJar");
_builder.newLine();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("repositories {");
_builder.newLine();
_builder.append("\t");
_builder.append("mavenLocal()");
_builder.newLine();
_builder.append("\t");
_builder.append("jcenter()");
_builder.newLine();
_builder.append("}");
_builder.newLine();
{
HashSet<Utils.Dependency> _modelDependencies = this.utils.modelDependencies(architecture);
int _size = _modelDependencies.size();
boolean _greaterThan = (_size > 0);
if (_greaterThan) {
_builder.newLine();
_builder.append("dependencies {");
_builder.newLine();
{
HashSet<Utils.Dependency> _modelDependencies_1 = this.utils.modelDependencies(architecture);
for(final Utils.Dependency dependency : _modelDependencies_1) {
_builder.append(" ");
_builder.append("compile \'");
_builder.append(((((dependency.applicationId + ":") + dependency.moduleName) + "-model:") + dependency.version), " ");
_builder.append("\'");
_builder.newLineIfNotEmpty();
}
}
_builder.append("}");
_builder.newLine();
}
}
_builder.newLine();
_builder.append("apply plugin: \'maven\'");
_builder.newLine();
_builder.newLine();
_builder.append("uploadArchives {");
_builder.newLine();
_builder.append(" ");
_builder.append("repositories {");
_builder.newLine();
_builder.append(" ");
_builder.append("mavenDeployer {");
_builder.newLine();
_builder.append(" ");
_builder.append("repository(url: mavenLocal().url)");
_builder.newLine();
_builder.append(" ");
_builder.newLine();
_builder.append(" ");
_builder.append("pom.groupId = \'");
String _applicationId = this.utils.applicationId(architecture);
_builder.append(_applicationId, " ");
_builder.append("\'");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
_builder.append("pom.artifactId = \'");
String _moduleName = this.utils.moduleName(architecture);
_builder.append(_moduleName, "\t\t\t");
_builder.append("-model\'");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
_builder.append("pom.version = \'");
String _version = this.utils.version(architecture);
_builder.append(_version, "\t\t\t");
_builder.append("\'");
_builder.newLineIfNotEmpty();
_builder.append(" ");
_builder.append("}");
_builder.newLine();
_builder.append(" ");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
_builder.newLine();
return _builder;
}
public CharSequence generateBuildService(final Architecture architecture, final Resource resource) {
StringConcatenation _builder = new StringConcatenation();
_builder.append("apply plugin: \'com.android.library\'");
_builder.newLine();
_builder.newLine();
_builder.append("buildscript {");
_builder.newLine();
_builder.append(" ");
_builder.append("repositories {");
_builder.newLine();
_builder.append(" ");
_builder.append("jcenter()");
_builder.newLine();
_builder.append(" ");
_builder.append("}");
_builder.newLine();
_builder.append(" ");
_builder.append("dependencies {");
_builder.newLine();
_builder.append(" ");
_builder.append("classpath \'");
_builder.append(Libraries.GRADLE, " ");
_builder.append("\'");
_builder.newLineIfNotEmpty();
_builder.append(" ");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("android {");
_builder.newLine();
_builder.append(" ");
_builder.append("compileSdkVersion ");
_builder.append(Libraries.COMPILE_SDK_VERSION, " ");
_builder.newLineIfNotEmpty();
_builder.append(" ");
_builder.append("buildToolsVersion \"");
_builder.append(Libraries.BUILD_TOOLS_VERSIONE, " ");
_builder.append("\"");
_builder.newLineIfNotEmpty();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("task androidSourcesJar(type: Jar) {");
_builder.newLine();
_builder.append("\t");
_builder.append("classifier = \'sources\'");
_builder.newLine();
_builder.append("\t");
_builder.append("from android.sourceSets.main.java.srcDirs");
_builder.newLine();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("artifacts {");
_builder.newLine();
_builder.append("\t");
_builder.append("archives androidSourcesJar");
_builder.newLine();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("repositories {");
_builder.newLine();
_builder.append("\t");
_builder.append("mavenLocal()");
_builder.newLine();
_builder.append("\t");
_builder.append("jcenter()");
_builder.newLine();
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("dependencies {");
_builder.newLine();
_builder.append(" ");
_builder.append("compile \'");
_builder.append(Libraries.COMMON_SERVICE, " ");
_builder.append("\'");
_builder.newLineIfNotEmpty();
{
Module _module = architecture.getModule();
Model _model = _module.getModel();
boolean _notEquals = (!Objects.equal(_model, null));
if (_notEquals) {
_builder.append(" ");
_builder.append("compile \'");
String _applicationId = this.utils.applicationId(architecture);
_builder.append(_applicationId, " ");
_builder.append(":");
String _moduleName = this.utils.moduleName(architecture);
_builder.append(_moduleName, " ");
_builder.append("-model:");
String _version = this.utils.version(architecture);
_builder.append(_version, " ");
_builder.append("\'");
_builder.newLineIfNotEmpty();
}
}
{
HashSet<Utils.Dependency> _serviceModelDependencies = this.utils.serviceModelDependencies(architecture);
for(final Utils.Dependency dependency : _serviceModelDependencies) {
_builder.append(" ");
_builder.append("compile \'");
_builder.append(((((dependency.applicationId + ":") + dependency.moduleName) + "-model:") + dependency.version), " ");
_builder.append("\'");
_builder.newLineIfNotEmpty();
}
}
{
HashSet<Utils.Dependency> _serviceExceptionDependencies = this.utils.serviceExceptionDependencies(architecture);
for(final Utils.Dependency dependency_1 : _serviceExceptionDependencies) {
_builder.append(" ");
_builder.append("compile \'");
_builder.append(((((dependency_1.applicationId + ":") + dependency_1.moduleName) + "-service:") + dependency_1.version), " ");
_builder.append("\'");
_builder.newLineIfNotEmpty();
}
}
_builder.append("}");
_builder.newLine();
_builder.newLine();
_builder.append("apply plugin: \'maven\'");
_builder.newLine();
_builder.newLine();
_builder.append("uploadArchives {");
_builder.newLine();
_builder.append(" ");
_builder.append("repositories {");
_builder.newLine();
_builder.append(" ");
_builder.append("mavenDeployer {");
_builder.newLine();
_builder.append(" ");
_builder.append("repository(url: mavenLocal().url)");
_builder.newLine();
_builder.append(" ");
_builder.newLine();
_builder.append(" ");
_builder.append("pom.groupId = \'");
String _applicationId_1 = this.utils.applicationId(architecture);
_builder.append(_applicationId_1, " ");
_builder.append("\'");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
_builder.append("pom.artifactId = \'");
String _moduleName_1 = this.utils.moduleName(architecture);
_builder.append(_moduleName_1, "\t\t\t");
_builder.append("-service\'");
_builder.newLineIfNotEmpty();
_builder.append("\t\t\t");
_builder.append("pom.version = \'");
String _version_1 = this.utils.version(architecture);
_builder.append(_version_1, "\t\t\t");
_builder.append("\'");
_builder.newLineIfNotEmpty();
_builder.append(" ");
_builder.append("}");
_builder.newLine();
_builder.append(" ");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
return _builder;
}
}
| |
/*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.client.ui;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasValue;
import com.vaadin.client.ApplicationConnection;
import com.vaadin.client.BrowserInfo;
import com.vaadin.client.WidgetUtil;
import com.vaadin.shared.ui.slider.SliderOrientation;
public class VSlider extends SimpleFocusablePanel
implements Field, HasValue<Double>, SubPartAware {
public static final String CLASSNAME = "v-slider";
/**
* Minimum size (width or height, depending on orientation) of the slider
* base.
*/
private static final int MIN_SIZE = 50;
protected ApplicationConnection client;
protected String id;
protected boolean disabled;
protected boolean readonly;
private int acceleration = 1;
protected double min;
protected double max;
protected int resolution;
protected Double value;
protected SliderOrientation orientation = SliderOrientation.HORIZONTAL;
private final HTML feedback = new HTML("", false);
private final VOverlay feedbackPopup = new VOverlay(true, false) {
{
setOwner(VSlider.this);
}
@Override
public void show() {
super.show();
updateFeedbackPosition();
}
};
/* DOM element for slider's base */
private final Element base;
private static final int BASE_BORDER_WIDTH = 1;
/* DOM element for slider's handle */
private final Element handle;
/* DOM element for decrement arrow */
private final Element smaller;
/* DOM element for increment arrow */
private final Element bigger;
/* Temporary dragging/animation variables */
private boolean dragging = false;
private VLazyExecutor delayedValueUpdater = new VLazyExecutor(100, () -> {
fireValueChanged();
acceleration = 1;
});
public VSlider() {
super();
base = DOM.createDiv();
handle = DOM.createDiv();
smaller = DOM.createDiv();
bigger = DOM.createDiv();
setStyleName(CLASSNAME);
getElement().appendChild(bigger);
getElement().appendChild(smaller);
getElement().appendChild(base);
base.appendChild(handle);
// Hide initially
smaller.getStyle().setDisplay(Display.NONE);
bigger.getStyle().setDisplay(Display.NONE);
sinkEvents(Event.MOUSEEVENTS | Event.ONMOUSEWHEEL | Event.KEYEVENTS
| Event.FOCUSEVENTS | Event.TOUCHEVENTS);
feedbackPopup.setWidget(feedback);
}
@Override
public void setStyleName(String style) {
updateStyleNames(style, false);
}
@Override
public void setStylePrimaryName(String style) {
updateStyleNames(style, true);
}
protected void updateStyleNames(String styleName,
boolean isPrimaryStyleName) {
feedbackPopup.removeStyleName(getStylePrimaryName() + "-feedback");
removeStyleName(getStylePrimaryName() + "-vertical");
if (isPrimaryStyleName) {
super.setStylePrimaryName(styleName);
} else {
super.setStyleName(styleName);
}
feedbackPopup.addStyleName(getStylePrimaryName() + "-feedback");
base.setClassName(getStylePrimaryName() + "-base");
handle.setClassName(getStylePrimaryName() + "-handle");
smaller.setClassName(getStylePrimaryName() + "-smaller");
bigger.setClassName(getStylePrimaryName() + "-bigger");
if (isVertical()) {
addStyleName(getStylePrimaryName() + "-vertical");
}
}
public void setFeedbackValue(double value) {
feedback.setText(String.valueOf(value));
}
private void updateFeedbackPosition() {
if (isVertical()) {
feedbackPopup.setPopupPosition(
handle.getAbsoluteLeft() + handle.getOffsetWidth(),
handle.getAbsoluteTop() + handle.getOffsetHeight() / 2
- feedbackPopup.getOffsetHeight() / 2);
} else {
feedbackPopup.setPopupPosition(
handle.getAbsoluteLeft() + handle.getOffsetWidth() / 2
- feedbackPopup.getOffsetWidth() / 2,
handle.getAbsoluteTop() - feedbackPopup.getOffsetHeight());
}
}
/** For internal use only. May be removed or replaced in the future. */
public void buildBase() {
final String styleAttribute = isVertical() ? "height" : "width";
final String oppositeStyleAttribute = isVertical() ? "width" : "height";
final String domProperty = isVertical() ? "offsetHeight"
: "offsetWidth";
// clear unnecessary opposite style attribute
base.getStyle().clearProperty(oppositeStyleAttribute);
/*
* To resolve defect #13681 we should not return from method buildBase()
* if slider has no parentElement, because such operations as
* buildHandle() and setValues(), which are needed for Slider, are
* called at the end of method buildBase(). And these methods will not
* be called if there is no parentElement. So, instead of returning from
* method buildBase() if there is no parentElement "if condition" is
* applied to call code for parentElement only in case it exists.
*/
if (getElement().hasParentElement()) {
final Element p = getElement();
if (p.getPropertyInt(domProperty) > MIN_SIZE) {
if (isVertical()) {
setHeight();
} else {
base.getStyle().clearProperty(styleAttribute);
}
} else {
// Set minimum size and adjust after all components have
// (supposedly) been drawn completely.
base.getStyle().setPropertyPx(styleAttribute, MIN_SIZE);
Scheduler.get().scheduleDeferred(new Command() {
@Override
public void execute() {
final Element p = getElement();
if (p.getPropertyInt(domProperty) > MIN_SIZE + 5
|| propertyNotNullOrEmpty(styleAttribute, p)) {
if (isVertical()) {
setHeight();
} else {
base.getStyle().clearProperty(styleAttribute);
}
// Ensure correct position
setValue(value, false);
}
}
// Style has non empty property
private boolean propertyNotNullOrEmpty(
final String styleAttribute, final Element p) {
return p.getStyle().getProperty(styleAttribute) != null
&& !p.getStyle().getProperty(styleAttribute)
.isEmpty();
}
});
}
}
if (!isVertical()) {
// Draw handle with a delay to allow base to gain maximum width
Scheduler.get().scheduleDeferred(() -> {
buildHandle();
setValue(value, false);
});
} else {
buildHandle();
setValue(value, false);
}
// TODO attach listeners for focusing and arrow keys
}
void buildHandle() {
final String handleAttribute = isVertical() ? "marginTop"
: "marginLeft";
final String oppositeHandleAttribute = isVertical() ? "marginLeft"
: "marginTop";
handle.getStyle().setProperty(handleAttribute, "0");
// clear unnecessary opposite handle attribute
handle.getStyle().clearProperty(oppositeHandleAttribute);
}
@Override
public void onBrowserEvent(Event event) {
if (disabled || readonly) {
return;
}
final Element targ = DOM.eventGetTarget(event);
if (DOM.eventGetType(event) == Event.ONMOUSEWHEEL) {
processMouseWheelEvent(event);
} else if (dragging || targ == handle) {
processHandleEvent(event);
} else if (targ == smaller) {
decreaseValue(true);
} else if (targ == bigger) {
increaseValue(true);
} else if (DOM.eventGetType(event) == Event.MOUSEEVENTS) {
processBaseEvent(event);
} else if (BrowserInfo.get().isGecko()
&& DOM.eventGetType(event) == Event.ONKEYPRESS
|| !BrowserInfo.get().isGecko()
&& DOM.eventGetType(event) == Event.ONKEYDOWN) {
if (handleNavigation(event.getKeyCode(), event.getCtrlKey(),
event.getShiftKey())) {
feedbackPopup.show();
delayedValueUpdater.trigger();
DOM.eventPreventDefault(event);
DOM.eventCancelBubble(event, true);
}
} else if (targ.equals(getElement())
&& DOM.eventGetType(event) == Event.ONFOCUS) {
feedbackPopup.show();
} else if (targ.equals(getElement())
&& DOM.eventGetType(event) == Event.ONBLUR) {
feedbackPopup.hide();
} else if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
feedbackPopup.show();
}
if (WidgetUtil.isTouchEvent(event)) {
event.preventDefault(); // avoid simulated events
event.stopPropagation();
}
}
private void processMouseWheelEvent(final Event event) {
final int dir = DOM.eventGetMouseWheelVelocityY(event);
if (dir < 0) {
increaseValue(false);
} else {
decreaseValue(false);
}
delayedValueUpdater.trigger();
DOM.eventPreventDefault(event);
DOM.eventCancelBubble(event, true);
}
private void processHandleEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
case Event.ONTOUCHSTART:
if (!disabled && !readonly) {
focus();
feedbackPopup.show();
dragging = true;
handle.setClassName(getStylePrimaryName() + "-handle");
handle.addClassName(getStylePrimaryName() + "-handle-active");
DOM.setCapture(getElement());
DOM.eventPreventDefault(event); // prevent selecting text
DOM.eventCancelBubble(event, true);
event.stopPropagation();
}
break;
case Event.ONMOUSEMOVE:
case Event.ONTOUCHMOVE:
if (dragging) {
setValueByEvent(event, false);
updateFeedbackPosition();
event.stopPropagation();
}
break;
case Event.ONTOUCHEND:
feedbackPopup.hide();
case Event.ONMOUSEUP:
// feedbackPopup.hide();
dragging = false;
handle.setClassName(getStylePrimaryName() + "-handle");
DOM.releaseCapture(getElement());
setValueByEvent(event, true);
event.stopPropagation();
break;
default:
break;
}
}
private void processBaseEvent(Event event) {
if (DOM.eventGetType(event) == Event.ONMOUSEDOWN) {
if (!disabled && !readonly && !dragging) {
setValueByEvent(event, true);
DOM.eventCancelBubble(event, true);
}
}
}
private void decreaseValue(boolean updateToServer) {
setValue(new Double(value.doubleValue() - Math.pow(10, -resolution)),
updateToServer);
}
private void increaseValue(boolean updateToServer) {
setValue(new Double(value.doubleValue() + Math.pow(10, -resolution)),
updateToServer);
}
private void setValueByEvent(Event event, boolean updateToServer) {
double v = min; // Fallback to min
final int coord = getEventPosition(event);
final int handleSize, baseSize, baseOffset;
if (isVertical()) {
handleSize = handle.getOffsetHeight();
baseSize = base.getOffsetHeight();
baseOffset = base.getAbsoluteTop() - Window.getScrollTop()
- handleSize / 2;
} else {
handleSize = handle.getOffsetWidth();
baseSize = base.getOffsetWidth();
baseOffset = base.getAbsoluteLeft() - Window.getScrollLeft()
+ handleSize / 2;
}
if (isVertical()) {
v = (baseSize - (coord - baseOffset))
/ (double) (baseSize - handleSize) * (max - min) + min;
} else {
v = (coord - baseOffset) / (double) (baseSize - handleSize)
* (max - min) + min;
}
if (v < min) {
v = min;
} else if (v > max) {
v = max;
}
setValue(v, updateToServer);
}
/**
* TODO consider extracting touches support to an impl class specific for
* webkit (only browser that really supports touches).
*
* @param event
* @return
*/
protected int getEventPosition(Event event) {
if (isVertical()) {
return WidgetUtil.getTouchOrMouseClientY(event);
} else {
return WidgetUtil.getTouchOrMouseClientX(event);
}
}
public void iLayout() {
if (isVertical()) {
setHeight();
}
// Update handle position
setValue(value, false);
}
private void setHeight() {
// Calculate decoration size
base.getStyle().setHeight(0, Unit.PX);
base.getStyle().setOverflow(Overflow.HIDDEN);
int h = getElement().getOffsetHeight();
if (h < MIN_SIZE) {
h = MIN_SIZE;
}
base.getStyle().setHeight(h, Unit.PX);
base.getStyle().clearOverflow();
}
private void fireValueChanged() {
ValueChangeEvent.fire(VSlider.this, value);
}
/**
* Handles the keyboard events handled by the Slider.
*
* @param keycode
* The key code received
* @param ctrl
* Whether {@code CTRL} was pressed
* @param shift
* Whether {@code SHIFT} was pressed
* @return true if the navigation event was handled
*/
public boolean handleNavigation(int keycode, boolean ctrl, boolean shift) {
// No support for ctrl moving
if (ctrl) {
return false;
}
if (keycode == getNavigationUpKey() && isVertical()
|| keycode == getNavigationRightKey() && !isVertical()) {
if (shift) {
for (int a = 0; a < acceleration; a++) {
increaseValue(false);
}
acceleration++;
} else {
increaseValue(false);
}
return true;
} else if (keycode == getNavigationDownKey() && isVertical()
|| keycode == getNavigationLeftKey() && !isVertical()) {
if (shift) {
for (int a = 0; a < acceleration; a++) {
decreaseValue(false);
}
acceleration++;
} else {
decreaseValue(false);
}
return true;
}
return false;
}
/**
* Get the key that increases the vertical slider. By default it is the up
* arrow key but by overriding this you can change the key to whatever you
* want.
*
* @return The keycode of the key
*/
protected int getNavigationUpKey() {
return KeyCodes.KEY_UP;
}
/**
* Get the key that decreases the vertical slider. By default it is the down
* arrow key but by overriding this you can change the key to whatever you
* want.
*
* @return The keycode of the key
*/
protected int getNavigationDownKey() {
return KeyCodes.KEY_DOWN;
}
/**
* Get the key that decreases the horizontal slider. By default it is the
* left arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationLeftKey() {
return KeyCodes.KEY_LEFT;
}
/**
* Get the key that increases the horizontal slider. By default it is the
* right arrow key but by overriding this you can change the key to whatever
* you want.
*
* @return The keycode of the key
*/
protected int getNavigationRightKey() {
return KeyCodes.KEY_RIGHT;
}
public void setConnection(ApplicationConnection client) {
this.client = client;
}
public void setId(String id) {
this.id = id;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public void setReadOnly(boolean readonly) {
this.readonly = readonly;
}
private boolean isVertical() {
return orientation == SliderOrientation.VERTICAL;
}
public void setOrientation(SliderOrientation orientation) {
if (this.orientation != orientation) {
this.orientation = orientation;
updateStyleNames(getStylePrimaryName(), true);
}
}
public void setMinValue(double value) {
min = value;
}
public void setMaxValue(double value) {
max = value;
}
public void setResolution(int resolution) {
this.resolution = resolution;
}
@Override
public HandlerRegistration addValueChangeHandler(
ValueChangeHandler<Double> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
@Override
public Double getValue() {
return value;
}
@Override
public void setValue(Double value) {
if (value < min) {
value = min;
} else if (value > max) {
value = max;
}
// Update handle position
final String styleAttribute = isVertical() ? "marginTop" : "marginLeft";
final String domProperty = isVertical() ? "offsetHeight"
: "offsetWidth";
final int handleSize = handle.getPropertyInt(domProperty);
final int baseSize = base.getPropertyInt(domProperty)
- 2 * BASE_BORDER_WIDTH;
final int range = baseSize - handleSize;
double v = value.doubleValue();
// Round value to resolution
if (resolution > 0) {
v = Math.round(v * Math.pow(10, resolution));
v = v / Math.pow(10, resolution);
} else {
v = Math.round(v);
}
final double valueRange = max - min;
double p = 0;
if (valueRange > 0) {
p = range * ((v - min) / valueRange);
}
if (p < 0) {
p = 0;
}
if (isVertical()) {
p = range - p;
}
final double pos = p;
handle.getStyle().setPropertyPx(styleAttribute, (int) Math.round(pos));
// Update value
this.value = new Double(v);
setFeedbackValue(v);
}
@Override
public void setValue(Double value, boolean fireEvents) {
if (value == null) {
return;
}
setValue(value);
if (fireEvents) {
fireValueChanged();
}
}
@Override
public com.google.gwt.user.client.Element getSubPartElement(
String subPart) {
if (subPart.equals("popup")) {
feedbackPopup.show();
return feedbackPopup.getElement();
}
return null;
}
@Override
public String getSubPartName(
com.google.gwt.user.client.Element subElement) {
if (feedbackPopup.getElement().isOrHasChild(subElement)) {
return "popup";
}
return null;
}
}
| |
/*
* Copyright (c) 2009-2010 by Bjoern Kolbeck, Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.foundation.flease.comm.tcp;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import org.xtreemfs.foundation.LifeCycleThread;
import org.xtreemfs.foundation.buffer.BufferPool;
import org.xtreemfs.foundation.buffer.ReusableBuffer;
import org.xtreemfs.foundation.flease.comm.tcp.TCPConnection.SendRequest;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
/**
*
* @author bjko
*/
public class TCPCommunicator extends LifeCycleThread {
private final int port;
/**
* the server socket
*/
private final ServerSocketChannel socket;
/**
* Selector for server socket
*/
private final Selector selector;
private final NIOServer implementation;
private final List<TCPConnection> connections;
private final Queue<TCPConnection> pendingCons;
private final AtomicInteger sendQueueSize;
/**
*
* @param implementation
* @param port, 0 to disable server mode
* @param bindAddr
* @throws IOException
*/
public TCPCommunicator(NIOServer implementation, int port, InetAddress bindAddr) throws IOException {
super("TCPcom@" + port);
this.port = port;
this.implementation = implementation;
this.connections = new LinkedList();
this.pendingCons = new ConcurrentLinkedQueue();
sendQueueSize = new AtomicInteger();
// open server socket
if (port == 0) {
socket = null;
} else {
socket = ServerSocketChannel.open();
socket.configureBlocking(false);
socket.socket().setReceiveBufferSize(256 * 1024);
socket.socket().setReuseAddress(true);
socket.socket().bind(
bindAddr == null ? new InetSocketAddress(port) : new InetSocketAddress(bindAddr, port));
}
// create a selector and register socket
selector = Selector.open();
if (socket != null)
socket.register(selector, SelectionKey.OP_ACCEPT);
}
/**
* Stop the server and close all connections.
*/
public void shutdown() {
this.interrupt();
}
/**
* sends a response.
*
* @param request
* the request
*/
public void write(TCPConnection connection, ReusableBuffer buffer, Object context) {
assert (buffer != null);
synchronized (connection) {
if (connection.getChannel().isConnected()) {
if (connection.sendQueueIsEmpty()) {
try {
int bytesWritten = connection.getChannel().write(buffer.getBuffer());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,"directly wrote %d bytes to %s",bytesWritten,connection.getChannel().socket().getRemoteSocketAddress().toString());
}
if (bytesWritten < 0) {
if (context != null)
implementation.onWriteFailed(new IOException("remote party closed connection while writing"), context);
abortConnection(connection,new IOException("remote party closed connection while writing"));
return;
}
if (!buffer.hasRemaining()) {
//we are done
BufferPool.free(buffer);
return;
}
} catch (ClosedChannelException ex) {
if (context != null)
implementation.onWriteFailed(ex, context);
abortConnection(connection,ex);
} catch (IOException ex) {
if (Logging.isDebug())
Logging.logError(Logging.LEVEL_DEBUG, this,ex);
if (context != null)
implementation.onWriteFailed(ex, context);
abortConnection(connection,ex);
}
}
synchronized (connection) {
boolean isEmpty = connection.sendQueueIsEmpty();
if (isEmpty) {
try {
SelectionKey key = connection.getChannel().keyFor(selector);
if (key != null) {
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
}
} catch (CancelledKeyException ex) {
}
}
}
sendQueueSize.incrementAndGet();
connection.addToSendQueue(new TCPConnection.SendRequest(buffer, context));
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,"enqueued write to %s",connection.getEndpoint());
}
selector.wakeup();
} else {
// ignore and free bufers
if (connection.getChannel().isConnectionPending()) {
sendQueueSize.incrementAndGet();
connection.addToSendQueue(new TCPConnection.SendRequest(buffer, context));
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,"enqueued write to %s",connection.getEndpoint());
}
} else {
BufferPool.free(buffer);
if (context != null)
implementation.onWriteFailed(new IOException("Connection already closed"), context);
}
}
}
}
public void run() {
notifyStarted();
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this, "TCP Server @%d ready", port);
}
try {
while (!isInterrupted()) {
// try to select events...
try {
final int numKeys = selector.select();
if (!pendingCons.isEmpty()) {
while (true) {
TCPConnection con = pendingCons.poll();
if (con == null) {
break;
}
try {
assert(con.getChannel() != null);
con.getChannel().register(selector,
SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE | SelectionKey.OP_READ, con);
} catch (ClosedChannelException ex) {
abortConnection(con,ex);
}
}
}
if (numKeys == 0) {
continue;
}
} catch (CancelledKeyException ex) {
// who cares
} catch (IOException ex) {
Logging.logMessage(Logging.LEVEL_WARN, Category.net, this,
"Exception while selecting: %s", ex.toString());
continue;
}
// fetch events
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator();
// process all events
while (iter.hasNext()) {
SelectionKey key = iter.next();
// remove key from the list
iter.remove();
try {
if (key.isAcceptable()) {
acceptConnection(key);
}
if (key.isConnectable()) {
connectConnection(key);
}
if (key.isReadable()) {
readConnection(key);
}
if (key.isWritable()) {
writeConnection(key);
}
} catch (CancelledKeyException ex) {
// nobody cares...
continue;
}
}
}
for (TCPConnection con : connections) {
try {
con.close(implementation,new IOException("server shutdown"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
// close socket
selector.close();
if (socket != null)
socket.close();
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"TCP Server @%d shutdown complete", port);
}
notifyStopped();
} catch (Throwable thr) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.net, this, "TPC Server @%d CRASHED!", port);
notifyCrashed(thr);
}
}
private void connectConnection(SelectionKey key) {
final TCPConnection con = (TCPConnection) key.attachment();
final SocketChannel channel = con.getChannel();
try {
if (channel.isConnectionPending()) {
channel.finishConnect();
}
synchronized (con) {
if (con.getSendBuffer() != null) {
key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ);
} else {
key.interestOps(SelectionKey.OP_READ);
}
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "connected from %s to %s", con
.getChannel().socket().getLocalSocketAddress().toString(), channel.socket().getRemoteSocketAddress()
.toString());
}
implementation.onConnect(con.getNIOConnection());
} catch (IOException ex) {
if (Logging.isDebug()) {
Logging.logError(Logging.LEVEL_DEBUG, this,ex);
}
implementation.onConnectFailed(con.getEndpoint(), ex, con.getNIOConnection().getContext());
con.close(implementation,ex);
}
}
public NIOConnection connect(InetSocketAddress server, Object context) throws IOException {
TCPConnection con = openConnection(server,context);
return con.getNIOConnection();
}
private TCPConnection openConnection(InetSocketAddress server, Object context) throws IOException {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "connect to %s", server
.toString());
}
SocketChannel channel = null;
TCPConnection con = null;
try {
channel = SocketChannel.open();
channel.configureBlocking(false);
//channel.socket().setTcpNoDelay(true);
channel.socket().setReceiveBufferSize(256 * 1024);
channel.connect(server);
con = new TCPConnection(channel, this, server);
con.getNIOConnection().setContext(context);
pendingCons.add(con);
selector.wakeup();
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "connection established");
return con;
} catch (IOException ex) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "cannot contact server %s",
server);
}
if (con != null)
con.close(implementation, ex);
throw ex;
}
}
/**
* accept a new incomming connection
*
* @param key
* the acceptable key
*/
private void acceptConnection(SelectionKey key) {
SocketChannel client = null;
TCPConnection connection = null;
// FIXME: Better exception handling!
try {
// accept connection
client = socket.accept();
connection = new TCPConnection(client,this,(InetSocketAddress)client.socket().getRemoteSocketAddress());
// and configure it to be non blocking
// IMPORTANT!
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ, connection);
//client.socket().setTcpNoDelay(true);
//numConnections.incrementAndGet();
connections.add(connection);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "connect from client at %s",
client.socket().getRemoteSocketAddress().toString());
}
implementation.onAccept(connection.getNIOConnection());
} catch (ClosedChannelException ex) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"cannot establish connection: %s", ex.toString());
}
} catch (IOException ex) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"cannot establish connection: %s", ex.toString());
}
}
}
/**
* read data from a readable connection
*
* @param key
* a readable key
*/
private void readConnection(SelectionKey key) {
final TCPConnection con = (TCPConnection) key.attachment();
final SocketChannel channel = con.getChannel();
try {
while (true) {
final ReusableBuffer readBuf = con.getReceiveBuffer();
if (readBuf == null)
return;
final int numBytesRead = channel.read(readBuf.getBuffer());
if (numBytesRead == -1) {
// connection closed
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"client closed connection (EOF): %s", channel.socket()
.getRemoteSocketAddress().toString());
}
abortConnection(con,new IOException("remote end closed connection while reading data"));
return;
} else if (numBytesRead == 0) {
return;
}
implementation.onRead(con.getNIOConnection(), readBuf);
}
} catch (ClosedChannelException ex) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"connection to %s closed by remote peer", con.getChannel().socket()
.getRemoteSocketAddress().toString());
}
abortConnection(con,ex);
} catch (IOException ex) {
// simply close the connection
if (Logging.isDebug()) {
Logging.logError(Logging.LEVEL_DEBUG, this, ex);
}
abortConnection(con,ex);
}
}
/**
* write data to a writeable connection
*
* @param key
* the writable key
*/
private void writeConnection(SelectionKey key) {
final TCPConnection con = (TCPConnection) key.attachment();
final SocketChannel channel = con.getChannel();
SendRequest srq = null;
try {
while (true) {
srq = con.getSendBuffer();
if (srq == null) {
synchronized (con) {
srq = con.getSendBuffer();
if (srq == null) {
// no more responses, stop writing...
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
return;
}
}
}
// send data
final long numBytesWritten = channel.write(srq.getData().getBuffer());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this,"wrote %d bytes to %s",numBytesWritten,channel.socket().getRemoteSocketAddress().toString());
}
if (numBytesWritten == -1) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (EOF): %s", channel.socket().getRemoteSocketAddress().toString());
}
// connection closed
abortConnection(con, new IOException("remote end closed connection while writing data"));
return;
}
if (srq.getData().hasRemaining()) {
// not enough data...
break;
}
// finished sending fragment
// clean up :-) request finished
BufferPool.free(srq.getData());
sendQueueSize.decrementAndGet();
con.nextSendBuffer();
}
} catch (ClosedChannelException ex) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"connection to %s closed by remote peer", con.getChannel().socket().getRemoteSocketAddress().toString());
}
abortConnection(con,ex);
} catch (IOException ex) {
// simply close the connection
if (Logging.isDebug()) {
Logging.logError(Logging.LEVEL_DEBUG, this, ex);
}
abortConnection(con,ex);
}
}
public int getSendQueueSize() {
return sendQueueSize.get();
}
void closeConnection(TCPConnection con) {
if (con.isClosed())
return;
con.setClosed();
final SocketChannel channel = con.getChannel();
// remove the connection from the selector and close socket
try {
synchronized (connections) {
connections.remove(con);
}
final SelectionKey key = channel.keyFor(selector);
if (key != null)
key.cancel();
con.close(null,null);
} catch (Exception ex) {
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "closing connection to %s", channel
.socket().getRemoteSocketAddress().toString());
}
}
void abortConnection(TCPConnection con, IOException exception) {
if (con.isClosed())
return;
con.setClosed();
final SocketChannel channel = con.getChannel();
// remove the connection from the selector and close socket
try {
synchronized (connections) {
connections.remove(con);
}
final SelectionKey key = channel.keyFor(selector);
if (key != null)
key.cancel();
con.close(implementation,exception);
} catch (Exception ex) {
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "closing connection to %s", channel
.socket().getRemoteSocketAddress().toString());
}
implementation.onClose(con.getNIOConnection());
}
int getPort() {
return this.port;
}
}
| |
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.inspector.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
*/
public class RemoveAttributesFromFindingsRequest extends
AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The ARNs specifying the findings that you want to remove attributes from.
* </p>
*/
private java.util.List<String> findingArns;
/**
* <p>
* The array of attribute keys that you want to remove from specified
* findings.
* </p>
*/
private java.util.List<String> attributeKeys;
/**
* <p>
* The ARNs specifying the findings that you want to remove attributes from.
* </p>
*
* @return The ARNs specifying the findings that you want to remove
* attributes from.
*/
public java.util.List<String> getFindingArns() {
return findingArns;
}
/**
* <p>
* The ARNs specifying the findings that you want to remove attributes from.
* </p>
*
* @param findingArns
* The ARNs specifying the findings that you want to remove
* attributes from.
*/
public void setFindingArns(java.util.Collection<String> findingArns) {
if (findingArns == null) {
this.findingArns = null;
return;
}
this.findingArns = new java.util.ArrayList<String>(findingArns);
}
/**
* <p>
* The ARNs specifying the findings that you want to remove attributes from.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setFindingArns(java.util.Collection)} or
* {@link #withFindingArns(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param findingArns
* The ARNs specifying the findings that you want to remove
* attributes from.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public RemoveAttributesFromFindingsRequest withFindingArns(
String... findingArns) {
if (this.findingArns == null) {
setFindingArns(new java.util.ArrayList<String>(findingArns.length));
}
for (String ele : findingArns) {
this.findingArns.add(ele);
}
return this;
}
/**
* <p>
* The ARNs specifying the findings that you want to remove attributes from.
* </p>
*
* @param findingArns
* The ARNs specifying the findings that you want to remove
* attributes from.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public RemoveAttributesFromFindingsRequest withFindingArns(
java.util.Collection<String> findingArns) {
setFindingArns(findingArns);
return this;
}
/**
* <p>
* The array of attribute keys that you want to remove from specified
* findings.
* </p>
*
* @return The array of attribute keys that you want to remove from
* specified findings.
*/
public java.util.List<String> getAttributeKeys() {
return attributeKeys;
}
/**
* <p>
* The array of attribute keys that you want to remove from specified
* findings.
* </p>
*
* @param attributeKeys
* The array of attribute keys that you want to remove from specified
* findings.
*/
public void setAttributeKeys(java.util.Collection<String> attributeKeys) {
if (attributeKeys == null) {
this.attributeKeys = null;
return;
}
this.attributeKeys = new java.util.ArrayList<String>(attributeKeys);
}
/**
* <p>
* The array of attribute keys that you want to remove from specified
* findings.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setAttributeKeys(java.util.Collection)} or
* {@link #withAttributeKeys(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param attributeKeys
* The array of attribute keys that you want to remove from specified
* findings.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public RemoveAttributesFromFindingsRequest withAttributeKeys(
String... attributeKeys) {
if (this.attributeKeys == null) {
setAttributeKeys(new java.util.ArrayList<String>(
attributeKeys.length));
}
for (String ele : attributeKeys) {
this.attributeKeys.add(ele);
}
return this;
}
/**
* <p>
* The array of attribute keys that you want to remove from specified
* findings.
* </p>
*
* @param attributeKeys
* The array of attribute keys that you want to remove from specified
* findings.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public RemoveAttributesFromFindingsRequest withAttributeKeys(
java.util.Collection<String> attributeKeys) {
setAttributeKeys(attributeKeys);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getFindingArns() != null)
sb.append("FindingArns: " + getFindingArns() + ",");
if (getAttributeKeys() != null)
sb.append("AttributeKeys: " + getAttributeKeys());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof RemoveAttributesFromFindingsRequest == false)
return false;
RemoveAttributesFromFindingsRequest other = (RemoveAttributesFromFindingsRequest) obj;
if (other.getFindingArns() == null ^ this.getFindingArns() == null)
return false;
if (other.getFindingArns() != null
&& other.getFindingArns().equals(this.getFindingArns()) == false)
return false;
if (other.getAttributeKeys() == null ^ this.getAttributeKeys() == null)
return false;
if (other.getAttributeKeys() != null
&& other.getAttributeKeys().equals(this.getAttributeKeys()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime
* hashCode
+ ((getFindingArns() == null) ? 0 : getFindingArns().hashCode());
hashCode = prime
* hashCode
+ ((getAttributeKeys() == null) ? 0 : getAttributeKeys()
.hashCode());
return hashCode;
}
@Override
public RemoveAttributesFromFindingsRequest clone() {
return (RemoveAttributesFromFindingsRequest) super.clone();
}
}
| |
/**
* JBoss, Home of Professional Open Source Copyright Red Hat, Inc., and
* individual 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 org.jboss.aerogear.android.pipe.test.loader;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import junit.framework.Assert;
import org.jboss.aerogear.android.pipe.loader.LoaderAdapter;
import org.jboss.aerogear.android.pipe.loader.ReadLoader;
import org.jboss.aerogear.android.pipe.loader.RemoveLoader;
import org.jboss.aerogear.android.pipe.loader.SaveLoader;
import org.jboss.aerogear.android.pipe.rest.RestfulPipeConfiguration;
import org.jboss.aerogear.android.pipe.rest.gson.GsonRequestBuilder;
import org.jboss.aerogear.android.pipe.rest.multipart.MultipartRequestBuilder;
import org.jboss.aerogear.android.pipe.test.MainActivity;
import org.jboss.aerogear.android.core.Callback;
import org.jboss.aerogear.android.core.Provider;
import org.jboss.aerogear.android.core.ReadFilter;
import org.jboss.aerogear.android.core.RecordId;
import org.jboss.aerogear.android.pipe.http.HeaderAndBody;
import org.jboss.aerogear.android.pipe.http.HttpProvider;
import org.jboss.aerogear.android.pipe.http.HttpProviderFactory;
import org.jboss.aerogear.android.pipe.test.helper.Data;
import org.jboss.aerogear.android.pipe.test.util.ObjectVarArgsMatcher;
import org.jboss.aerogear.android.pipe.test.util.UnitTestUtils;
import org.jboss.aerogear.android.pipe.test.http.HttpStubProvider;
import org.jboss.aerogear.android.pipe.LoaderPipe;
import org.jboss.aerogear.android.pipe.Pipe;
import org.jboss.aerogear.android.pipe.PipeHandler;
import org.json.JSONObject;
import org.mockito.Mockito;
import android.annotation.TargetApi;
import android.graphics.Point;
import android.os.Build;
import android.support.test.runner.AndroidJUnit4;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import org.jboss.aerogear.android.pipe.test.util.PatchedActivityInstrumentationTestCase;
import org.jboss.aerogear.android.pipe.callback.AbstractFragmentCallback;
import org.jboss.aerogear.android.pipe.PipeManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressWarnings({"unchecked", "rawtypes"})
@RunWith(AndroidJUnit4.class)
public class LoaderAdapterTest extends PatchedActivityInstrumentationTestCase {
public LoaderAdapterTest() {
super(MainActivity.class);
}
private static final String TAG = LoaderAdapterTest.class
.getSimpleName();
private static final String SERIALIZED_POINTS = "{\"points\":[{\"x\":0,\"y\":0},{\"x\":1,\"y\":2},{\"x\":2,\"y\":4},{\"x\":3,\"y\":6},{\"x\":4,\"y\":8},{\"x\":5,\"y\":10},{\"x\":6,\"y\":12},{\"x\":7,\"y\":14},{\"x\":8,\"y\":16},{\"x\":9,\"y\":18}],\"id\":\"1\"}";
private URL url;
private URL listUrl;
@Before
public void setUp() throws MalformedURLException, Exception {
url = new URL("http://server.com/context/");
listUrl = new URL("http://server.com/context/ListClassId");
}
@Test
public void testSingleObjectRead() throws Exception {
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(
Point.class, new PointTypeAdapter());
HeaderAndBody response = new HeaderAndBody(
SERIALIZED_POINTS.getBytes(), new HashMap<String, Object>());
final HttpStubProvider provider = new HttpStubProvider(listUrl, response);
RestfulPipeConfiguration config = PipeManager.config("ListClassId", RestfulPipeConfiguration.class);
Pipe<LoaderAdapterTest.ListClassId> restPipe = config.withUrl(listUrl)
.requestBuilder(new GsonRequestBuilder(builder.create()))
.forClass(LoaderAdapterTest.ListClassId.class);
Object restRunner = UnitTestUtils.getPrivateField(restPipe,
"restRunner");
UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory",
new Provider<HttpProvider>() {
@Override
public HttpProvider get(Object... in) {
return provider;
}
});
LoaderPipe<LoaderAdapterTest.ListClassId> adapter = PipeManager.getPipe(config.getName(), getActivity());
List<LoaderAdapterTest.ListClassId> result = runRead(adapter);
List<Point> returnedPoints = result.get(0).points;
Assert.assertEquals(10, returnedPoints.size());
}
@Test
public void testReadCallbackFailsWithIncompatibleType() throws Exception {
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(
Point.class, new PointTypeAdapter());
HeaderAndBody response = new HeaderAndBody(
SERIALIZED_POINTS.getBytes(), new HashMap<String, Object>());
final HttpStubProvider provider = new HttpStubProvider(listUrl, response);
RestfulPipeConfiguration config = PipeManager.config("ListClassId", RestfulPipeConfiguration.class);
Pipe<LoaderAdapterTest.ListClassId> restPipe = config.withUrl(listUrl)
.requestBuilder(new GsonRequestBuilder(builder.create()))
.forClass(LoaderAdapterTest.ListClassId.class);
Object restRunner = UnitTestUtils.getPrivateField(restPipe,
"restRunner");
UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory",
new Provider<HttpProvider>() {
@Override
public HttpProvider get(Object... in) {
return provider;
}
});
LoaderPipe<LoaderAdapterTest.ListClassId> adapter = PipeManager.getPipe(config.getName(), getActivity());
try {
adapter.read(new AbstractFragmentCallback<List<LoaderAdapterTest.ListClassId>>() {
private static final long serialVersionUID = 1L;
@Override
public void onSuccess(List<LoaderAdapterTest.ListClassId> data) {
}
@Override
public void onFailure(Exception e) {
}
});
} catch (Exception e) {
return;
}
fail("Incorrect callback should throw exception.");
}
@Test
public void testSaveCallbackFailsWithIncompatibleType() throws Exception {
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(
Point.class, new PointTypeAdapter());
HeaderAndBody response = new HeaderAndBody(
SERIALIZED_POINTS.getBytes(), new HashMap<String, Object>());
final HttpStubProvider provider = new HttpStubProvider(listUrl, response);
RestfulPipeConfiguration config = PipeManager.config("ListClassId", RestfulPipeConfiguration.class);
Pipe<LoaderAdapterTest.ListClassId> restPipe = config.withUrl(listUrl)
.requestBuilder(new GsonRequestBuilder(builder.create()))
.forClass(LoaderAdapterTest.ListClassId.class);
Object restRunner = UnitTestUtils.getPrivateField(restPipe,
"restRunner");
UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory",
new Provider<HttpProvider>() {
@Override
public HttpProvider get(Object... in) {
return provider;
}
});
LoaderPipe<LoaderAdapterTest.ListClassId> adapter = PipeManager.getPipe(config.getName(), getActivity());
try {
adapter.save(new ListClassId(true), new AbstractFragmentCallback<ListClassId>() {
private static final long serialVersionUID = 1L;
@Override
public void onSuccess(ListClassId data) {
}
@Override
public void onFailure(Exception e) {
}
});
} catch (Exception e) {
return;
}
fail("Incorrect callback should throw exception.");
}
@Test
public void testDeleteCallbackFailsWithIncompatibleType() throws Exception {
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(
Point.class, new PointTypeAdapter());
HeaderAndBody response = new HeaderAndBody(
SERIALIZED_POINTS.getBytes(), new HashMap<String, Object>());
final HttpStubProvider provider = new HttpStubProvider(listUrl, response);
RestfulPipeConfiguration config = PipeManager.config("ListClassId", RestfulPipeConfiguration.class);
Pipe<LoaderAdapterTest.ListClassId> restPipe = config.withUrl(listUrl)
.requestBuilder(new GsonRequestBuilder(builder.create()))
.forClass(LoaderAdapterTest.ListClassId.class);
Object restRunner = UnitTestUtils.getPrivateField(restPipe,
"restRunner");
UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory",
new Provider<HttpProvider>() {
@Override
public HttpProvider get(Object... in) {
return provider;
}
});
LoaderPipe<LoaderAdapterTest.ListClassId> adapter = PipeManager.getPipe(config.getName(), getActivity());
try {
adapter.remove("1", new AbstractFragmentCallback<Void>() {
private static final long serialVersionUID = 1L;
@Override
public void onSuccess(Void data) {
}
@Override
public void onFailure(Exception e) {
}
});
} catch (Exception e) {
return;
}
fail("Incorrect callback should throw exception.");
}
@Test
public void testSingleObjectSave() throws Exception {
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(
Point.class, new PointTypeAdapter());
final HttpStubProvider provider = mock(HttpStubProvider.class);
when(provider.getUrl()).thenReturn(listUrl);
when(provider.post((byte[]) anyObject()))
.thenReturn(new HeaderAndBody(
SERIALIZED_POINTS.getBytes(),
new HashMap<String, Object>())
);
when(provider.put(any(String.class), (byte[]) anyObject()))
.thenReturn(new HeaderAndBody(
SERIALIZED_POINTS.getBytes(),
new HashMap<String, Object>())
);
RestfulPipeConfiguration config = PipeManager.config("ListClassId", RestfulPipeConfiguration.class);
Pipe<LoaderAdapterTest.ListClassId> restPipe = config.withUrl(listUrl)
.requestBuilder(new GsonRequestBuilder(builder.create()))
.forClass(LoaderAdapterTest.ListClassId.class);
Object restRunner = UnitTestUtils.getPrivateField(restPipe,
"restRunner");
UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory",
new Provider<HttpProvider>() {
@Override
public HttpProvider get(Object... in) {
return provider;
}
});
LoaderPipe<LoaderAdapterTest.ListClassId> adapter = PipeManager.getPipe(config.getName(), getActivity());
runSave(adapter);
verify(provider).put(any(String.class), (byte[]) anyObject());
}
@Test
public void testSingleObjectMultipartSave() throws Exception {
final HttpStubProvider provider = mock(HttpStubProvider.class);
when(provider.getUrl()).thenReturn(url);
when(provider.post((byte[]) anyObject()))
.thenReturn(new HeaderAndBody(
SERIALIZED_POINTS.getBytes(),
new HashMap<String, Object>())
);
when(provider.put(any(String.class), (byte[]) anyObject()))
.thenReturn(new HeaderAndBody(
SERIALIZED_POINTS.getBytes(),
new HashMap<String, Object>())
);
RestfulPipeConfiguration config = PipeManager.config("MultiPartData", RestfulPipeConfiguration.class);
Pipe<MultiPartData> restPipe = config.withUrl(url)
.requestBuilder(new MultipartRequestBuilder())
.forClass(MultiPartData.class);
Object restRunner = UnitTestUtils.getPrivateField(restPipe,
"restRunner");
UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory",
new Provider<HttpProvider>() {
@Override
public HttpProvider get(Object... in) {
return provider;
}
});
LoaderPipe<MultiPartData> adapter = PipeManager.getPipe(config.getName(), getActivity());
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean hasException = new AtomicBoolean(false);
adapter.save(new MultiPartData(),
new Callback<MultiPartData>() {
private static final long serialVersionUID = 1L;
@Override
public void onSuccess(MultiPartData data) {
latch.countDown();
}
@Override
public void onFailure(Exception e) {
hasException.set(true);
Logger.getLogger(LoaderAdapterTest.class.getSimpleName())
.log(Level.SEVERE, e.getMessage(), e);
latch.countDown();
}
});
latch.await(2, TimeUnit.SECONDS);
Assert.assertFalse(hasException.get());
verify(provider).put(any(String.class), (byte[]) anyObject());
}
@Test
public void testSingleObjectDelete() throws Exception {
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(
Point.class, new PointTypeAdapter());
final HttpStubProvider provider = mock(HttpStubProvider.class);
when(provider.getUrl()).thenReturn(listUrl);
RestfulPipeConfiguration config = PipeManager.config("ListClassId", RestfulPipeConfiguration.class);
Pipe<LoaderAdapterTest.ListClassId> restPipe = config.withUrl(listUrl)
.requestBuilder(new GsonRequestBuilder(builder.create()))
.forClass(LoaderAdapterTest.ListClassId.class);
Object restRunner = UnitTestUtils.getPrivateField(restPipe,
"restRunner");
UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory",
new Provider<HttpProvider>() {
@Override
public HttpProvider get(Object... in) {
return provider;
}
});
LoaderPipe<LoaderAdapterTest.ListClassId> adapter = PipeManager.getPipe(config.getName(), getActivity());
runRemove(adapter, "1");
verify(provider).delete(eq("1"));
}
@Test
public void testMultipleCallsToLoadCallDeliver() {
PipeHandler handler = mock(PipeHandler.class);
final AtomicBoolean called = new AtomicBoolean(false);
when(handler.onRawReadWithFilter((ReadFilter) any(), (Pipe) any())).thenReturn(new HeaderAndBody(new byte[]{}, new HashMap<String, Object>()));
ReadLoader loader = new ReadLoader(getActivity(), null, handler, null, null) {
@Override
public void deliverResult(Object data) {
called.set(true);
return;
}
@Override
public void forceLoad() {
throw new IllegalStateException("Should not be called");
}
@Override
public void onStartLoading() {
super.onStartLoading();
}
};
loader.loadInBackground();
UnitTestUtils.callMethod(loader, "onStartLoading");
assertTrue(called.get());
}
@Test
public void testMultipleCallsToSaveCallDeliver() {
PipeHandler handler = mock(PipeHandler.class);
final AtomicBoolean called = new AtomicBoolean(false);
when(handler.onRawSave(Matchers.anyString(), (byte[]) anyObject())).thenReturn(new HeaderAndBody(new byte[]{}, new HashMap<String, Object>()));
SaveLoader loader = new SaveLoader(getActivity(), null, handler, null, null) {
@Override
public void deliverResult(Object data) {
called.set(true);
return;
}
@Override
public void forceLoad() {
throw new IllegalStateException("Should not be called");
}
@Override
public void onStartLoading() {
super.onStartLoading();
}
};
loader.loadInBackground();
UnitTestUtils.callMethod(loader, "onStartLoading");
assertTrue(called.get());
}
@Test
public void testMultipleCallsToRemoveCallDeliver() {
PipeHandler handler = mock(PipeHandler.class);
final AtomicBoolean called = new AtomicBoolean(false);
when(handler.onRawReadWithFilter((ReadFilter) any(), (Pipe) any())).thenReturn(new HeaderAndBody(new byte[]{}, new HashMap<String, Object>()));
RemoveLoader loader = new RemoveLoader(getActivity(), null, handler, null) {
@Override
public void deliverResult(Object data) {
called.set(true);
return;
}
@Override
public void forceLoad() {
throw new IllegalStateException("Should not be called");
}
@Override
public void onStartLoading() {
super.onStartLoading();
}
};
loader.loadInBackground();
UnitTestUtils.callMethod(loader, "onStartLoading");
assertTrue(called.get());
}
private <T> List<T> runRead(Pipe<T> restPipe) throws InterruptedException {
return runRead(restPipe, null);
}
/**
* Runs a read method, returns the result of the call back and makes sure no
* exceptions are thrown
*
* @param restPipe
*/
private <T> List<T> runRead(Pipe<T> restPipe, ReadFilter readFilter)
throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean hasException = new AtomicBoolean(false);
final AtomicReference<List<T>> resultRef = new AtomicReference<List<T>>();
restPipe.read(readFilter, new Callback<List<T>>() {
private static final long serialVersionUID = 1L;
@Override
public void onSuccess(List<T> data) {
resultRef.set(data);
latch.countDown();
}
@Override
public void onFailure(Exception e) {
hasException.set(true);
Logger.getLogger(LoaderAdapterTest.class.getSimpleName())
.log(Level.SEVERE, e.getMessage(), e);
latch.countDown();
}
});
latch.await(2, TimeUnit.SECONDS);
Assert.assertFalse(hasException.get());
return resultRef.get();
}
/**
* Runs a remove method, returns the result of the call back and makes sure
* no exceptions are thrown
*
*/
private <T> void runRemove(Pipe<T> restPipe, String id)
throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean hasException = new AtomicBoolean(false);
restPipe.remove(id, new Callback<Void>() {
private static final long serialVersionUID = 1L;
@Override
public void onSuccess(Void data) {
latch.countDown();
}
@Override
public void onFailure(Exception e) {
hasException.set(true);
Logger.getLogger(LoaderAdapterTest.class.getSimpleName())
.log(Level.SEVERE, e.getMessage(), e);
latch.countDown();
}
});
latch.await(2, TimeUnit.SECONDS);
Assert.assertFalse(hasException.get());
}
private void runSave(Pipe<ListClassId> restPipe)
throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean hasException = new AtomicBoolean(false);
restPipe.save(new ListClassId(true),
new Callback<ListClassId>() {
private static final long serialVersionUID = 1L;
@Override
public void onSuccess(ListClassId data) {
latch.countDown();
}
@Override
public void onFailure(Exception e) {
hasException.set(true);
Logger.getLogger(LoaderAdapterTest.class.getSimpleName())
.log(Level.SEVERE, e.getMessage(), e);
latch.countDown();
}
});
latch.await(2, TimeUnit.SECONDS);
Assert.assertFalse(hasException.get());
}
@Test
public void testRunReadWithFilter() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
HttpProviderFactory factory = mock(HttpProviderFactory.class);
when(factory.get(anyObject())).thenReturn(mock(HttpProvider.class));
RestfulPipeConfiguration config = PipeManager.config("data", RestfulPipeConfiguration.class);
Pipe<Data> pipe = config.withUrl(url)
.forClass(Data.class);
Object restRunner = UnitTestUtils.getPrivateField(pipe, "restRunner");
UnitTestUtils.setPrivateField(restRunner, "httpProviderFactory",
factory);
ReadFilter filter = new ReadFilter();
filter.setLimit(10);
filter.setWhere(new JSONObject("{\"model\":\"BMW\"}"));
LoaderAdapter<Data> adapter = (LoaderAdapter<Data>) PipeManager.getPipe("data", getActivity());
adapter.read(filter, new Callback<List<Data>>() {
private static final long serialVersionUID = 1L;
@Override
public void onSuccess(List<Data> data) {
latch.countDown();
}
@Override
public void onFailure(Exception e) {
latch.countDown();
Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE,
TAG, e);
}
});
latch.await(60, TimeUnit.SECONDS);
verify(factory).get(Mockito.argThat(new ObjectVarArgsMatcher(new URL("http://server.com/context?limit=10&model=BMW"), 60000)));
}
@Test
public void testResetWithoutPipeIds() throws NoSuchFieldException, IllegalAccessException {
RestfulPipeConfiguration config = PipeManager.config("data", RestfulPipeConfiguration.class);
Pipe<Data> pipe = config.withUrl(url).forClass(Data.class);
LoaderAdapter<Data> loaderPipe = new LoaderAdapter<Data>(getActivity(), pipe, "loaderPipeForTest");
loaderPipe.reset();
Map<String, List<Integer>> idsForNamedPipes = (Map<String, List<Integer>>) UnitTestUtils.getPrivateField(loaderPipe, "idsForNamedPipes");
Assert.assertEquals("Should be 1", 1, idsForNamedPipes.size());
Assert.assertNotNull("Should not null", idsForNamedPipes.get("loaderPipeForTest"));
Assert.assertEquals("Should be empty", 0, idsForNamedPipes.get("loaderPipeForTest").size());
}
private static class PointTypeAdapter implements InstanceCreator,
JsonSerializer, JsonDeserializer {
@Override
public Object createInstance(Type type) {
return new Point();
}
@Override
public JsonElement serialize(Object src, Type typeOfSrc,
JsonSerializationContext context) {
JsonObject object = new JsonObject();
object.addProperty("x", ((Point) src).x);
object.addProperty("y", ((Point) src).y);
return object;
}
@Override
public Object deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return new Point(json.getAsJsonObject().getAsJsonPrimitive("x")
.getAsInt(), json.getAsJsonObject().getAsJsonPrimitive("y")
.getAsInt());
}
}
public final static class ListClassId {
List<Point> points = new ArrayList<Point>(10);
@RecordId
String id = "1";
public ListClassId(boolean build) {
if (build) {
for (int i = 0; i < 10; i++) {
points.add(new Point(i, i * 2));
}
}
}
public ListClassId() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
try {
return points.equals(((ListClassId) obj).points);
} catch (Throwable ignore) {
return false;
}
}
}
public static class MultiPartData {
private byte[] byteArray = {'a', 'b', 'c', 'd', 'e', 'f'};
private InputStream inputStream = new ByteArrayInputStream(byteArray);
@RecordId
private String string = "This is a String";
public byte[] getByteArray() {
return byteArray;
}
public InputStream getInputStream() {
return inputStream;
}
public String getString() {
return string;
}
public void setByteArray(byte[] byteArray) {
this.byteArray = byteArray;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public void setString(String string) {
this.string = string;
}
}
}
| |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project 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 io.netty.buffer;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
/**
* An {@link InputStream} which reads data from a {@link ByteBuf}.
* <p>
* A read operation against this stream will occur at the {@code readerIndex}
* of its underlying buffer and the {@code readerIndex} will increase during
* the read operation. Please note that it only reads up to the number of
* readable bytes determined at the moment of construction. Therefore,
* updating {@link ByteBuf#writerIndex()} will not affect the return
* value of {@link #available()}.
* <p>
* This stream implements {@link DataInput} for your convenience.
* The endianness of the stream is not always big endian but depends on
* the endianness of the underlying buffer.
*
* @see ByteBufOutputStream
*/
public class ByteBufInputStream extends InputStream implements DataInput {
private final ByteBuf buffer;
private final int startIndex;
private final int endIndex;
/**
* Creates a new stream which reads data from the specified {@code buffer}
* starting at the current {@code readerIndex} and ending at the current
* {@code writerIndex}.
*/
public ByteBufInputStream(ByteBuf buffer) {
this(buffer, buffer.readableBytes());
}
/**
* Creates a new stream which reads data from the specified {@code buffer}
* starting at the current {@code readerIndex} and ending at
* {@code readerIndex + length}.
*
* @throws IndexOutOfBoundsException
* if {@code readerIndex + length} is greater than
* {@code writerIndex}
*/
public ByteBufInputStream(ByteBuf buffer, int length) {
if (buffer == null) {
throw new NullPointerException("buffer");
}
if (length < 0) {
throw new IllegalArgumentException("length: " + length);
}
if (length > buffer.readableBytes()) {
throw new IndexOutOfBoundsException("Too many bytes to be read - Needs "
+ length + ", maximum is " + buffer.readableBytes());
}
this.buffer = buffer;
startIndex = buffer.readerIndex();
endIndex = startIndex + length;
buffer.markReaderIndex();
}
/**
* Returns the number of read bytes by this stream so far.
*/
public int readBytes() {
return buffer.readerIndex() - startIndex;
}
@Override
public int available() throws IOException {
return endIndex - buffer.readerIndex();
}
@Override
public void mark(int readlimit) {
buffer.markReaderIndex();
}
@Override
public boolean markSupported() {
return true;
}
@Override
public int read() throws IOException {
if (!buffer.isReadable()) {
return -1;
}
return buffer.readByte() & 0xff;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int available = available();
if (available == 0) {
return -1;
}
len = Math.min(available, len);
buffer.readBytes(b, off, len);
return len;
}
@Override
public void reset() throws IOException {
buffer.resetReaderIndex();
}
@Override
public long skip(long n) throws IOException {
if (n > Integer.MAX_VALUE) {
return skipBytes(Integer.MAX_VALUE);
} else {
return skipBytes((int) n);
}
}
@Override
public boolean readBoolean() throws IOException {
checkAvailable(1);
return read() != 0;
}
@Override
public byte readByte() throws IOException {
if (!buffer.isReadable()) {
throw new EOFException();
}
return buffer.readByte();
}
@Override
public char readChar() throws IOException {
return (char) readShort();
}
@Override
public double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
@Override
public float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
@Override
public void readFully(byte[] b) throws IOException {
readFully(b, 0, b.length);
}
@Override
public void readFully(byte[] b, int off, int len) throws IOException {
checkAvailable(len);
buffer.readBytes(b, off, len);
}
@Override
public int readInt() throws IOException {
checkAvailable(4);
return buffer.readInt();
}
private final StringBuilder lineBuf = new StringBuilder();
@Override
public String readLine() throws IOException {
lineBuf.setLength(0);
loop: while (true) {
if (!buffer.isReadable()) {
return lineBuf.length() > 0 ? lineBuf.toString() : null;
}
int c = buffer.readUnsignedByte();
switch (c) {
case '\n':
break loop;
case '\r':
if (buffer.isReadable() && (char) buffer.getUnsignedByte(buffer.readerIndex()) == '\n') {
buffer.skipBytes(1);
}
break loop;
default:
lineBuf.append((char) c);
}
}
return lineBuf.toString();
}
@Override
public long readLong() throws IOException {
checkAvailable(8);
return buffer.readLong();
}
@Override
public short readShort() throws IOException {
checkAvailable(2);
return buffer.readShort();
}
@Override
public String readUTF() throws IOException {
return DataInputStream.readUTF(this);
}
@Override
public int readUnsignedByte() throws IOException {
return readByte() & 0xff;
}
@Override
public int readUnsignedShort() throws IOException {
return readShort() & 0xffff;
}
@Override
public int skipBytes(int n) throws IOException {
int nBytes = Math.min(available(), n);
buffer.skipBytes(nBytes);
return nBytes;
}
private void checkAvailable(int fieldSize) throws IOException {
if (fieldSize < 0) {
throw new IndexOutOfBoundsException("fieldSize cannot be a negative number");
}
if (fieldSize > available()) {
throw new EOFException("fieldSize is too long! Length is " + fieldSize
+ ", but maximum is " + available());
}
}
}
| |
package us.dot.its.jpo.ode.plugin.j2735.builders;
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 java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import mockit.Capturing;
import mockit.Expectations;
import us.dot.its.jpo.ode.plugin.j2735.J2735BsmPart2Content;
import us.dot.its.jpo.ode.plugin.j2735.J2735DisabledVehicle;
import us.dot.its.jpo.ode.plugin.j2735.J2735ObstacleDetection;
import us.dot.its.jpo.ode.plugin.j2735.J2735RTCMPackage;
import us.dot.its.jpo.ode.plugin.j2735.J2735SpeedProfile;
import us.dot.its.jpo.ode.plugin.j2735.J2735SupplementalVehicleExtensions;
import us.dot.its.jpo.ode.plugin.j2735.J2735VehicleClassification;
import us.dot.its.jpo.ode.plugin.j2735.J2735VehicleData;
import us.dot.its.jpo.ode.plugin.j2735.J2735WeatherProbe;
import us.dot.its.jpo.ode.plugin.j2735.J2735WeatherReport;
import us.dot.its.jpo.ode.util.CodecUtils;
import us.dot.its.jpo.ode.util.JsonUtils;
public class SupplementalVehicleExtensionsBuilderTest {
@Test
public void testClassification() {
ObjectNode testInput = JsonUtils.newNode();
testInput.put("classification", 1);
J2735BsmPart2Content outputContent = new J2735BsmPart2Content();
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(outputContent, testInput);
assertEquals(Integer.valueOf(1), result.getClassification());
}
@Test
public void testVehicleClass(@Capturing VehicleClassificationBuilder capturingVehicleClassificationBuilder) {
new Expectations() {
{
VehicleClassificationBuilder.genericVehicleClassification((JsonNode) any);
result = new J2735VehicleClassification();
}
};
ObjectNode testInput = JsonUtils.newNode();
testInput.put("classDetails", "something");
J2735BsmPart2Content outputContent = new J2735BsmPart2Content();
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(outputContent, testInput);
assertNotNull(result.getClassDetails());
}
@Test
public void testVehicleData(@Capturing VehicleDataBuilder capturingVehicleDataBuilder) {
new Expectations() {
{
VehicleDataBuilder.genericVehicleData((JsonNode) any);
result = new J2735VehicleData();
}
};
ObjectNode testInput = JsonUtils.newNode();
testInput.put("vehicleData", "something");
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(new J2735BsmPart2Content(), testInput);
assertNotNull(result.getVehicleData());
}
@Test
public void testWeatherReport(@Capturing WeatherReportBuilder capturingWeatherReportBuilder) {
new Expectations() {
{
WeatherReportBuilder.genericWeatherReport((JsonNode) any);
result = new J2735WeatherReport();
}
};
ObjectNode testInput = JsonUtils.newNode();
testInput.put("weatherReport", "something");
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(new J2735BsmPart2Content(), testInput);
assertNotNull(result.getWeatherReport());
}
@Test
public void testWeatherProbe(@Capturing WeatherProbeBuilder capturingWeatherProbeBuilder) {
new Expectations() {
{
WeatherProbeBuilder.genericWeatherProbe((JsonNode) any);
result = new J2735WeatherProbe();
}
};
ObjectNode testInput = JsonUtils.newNode();
testInput.put("weatherProbe", "something");
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(new J2735BsmPart2Content(), testInput);
assertNotNull(result.getWeatherProbe());
}
@Test
public void testObstacle(@Capturing ObstacleDetectionBuilder capturingObstacleDetectionBuilder) {
new Expectations() {
{
ObstacleDetectionBuilder.genericObstacleDetection((JsonNode) any);
result = new J2735ObstacleDetection();
}
};
ObjectNode testInput = JsonUtils.newNode();
testInput.put("obstacle", "something");
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(new J2735BsmPart2Content(), testInput);
assertNotNull(result.getObstacle());
}
@Test
public void testStatus(@Capturing DisabledVehicleBuilder capturingDisabledVehicleBuilder) {
new Expectations() {
{
DisabledVehicleBuilder.genericDisabledVehicle((JsonNode) any);
result = new J2735DisabledVehicle();
}
};
ObjectNode testInput = JsonUtils.newNode();
testInput.put("status", "something");
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(new J2735BsmPart2Content(), testInput);
assertNotNull(result.getStatus());
}
@Test
public void testSpeedProfile(@Capturing SpeedProfileBuilder capturingSpeedProfileBuilder) {
new Expectations() {
{
SpeedProfileBuilder.genericSpeedProfile((JsonNode) any);
result = new J2735SpeedProfile();
}
};
ObjectNode testInput = JsonUtils.newNode();
testInput.put("speedProfile", "something");
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(new J2735BsmPart2Content(), testInput);
assertNotNull(result.getSpeedProfile());
}
@Test
public void testRtcmPackage(@Capturing RTCMPackageBuilder capturingRTCMPackageBuilder) {
new Expectations() {
{
RTCMPackageBuilder.genericRTCMPackage((JsonNode) any);
result = new J2735RTCMPackage();
}
};
ObjectNode testInput = JsonUtils.newNode();
testInput.put("theRTCM", "something");
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(new J2735BsmPart2Content(), testInput);
assertNotNull(result.getTheRTCM());
}
@Test
public void testEmptyRegional() {
ObjectNode testInput = JsonUtils.newNode();
testInput.set("regional", JsonUtils.newNode());
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(new J2735BsmPart2Content(), testInput);
assertNotNull(result.getRegional());
}
@Test
public void test1Regional(@Capturing CodecUtils capturingCodecUtils) {
ObjectNode testRegionalNode = JsonUtils.newNode();
testRegionalNode.put("regionId", 1);
testRegionalNode.put("regExtValue", "something");
ObjectNode testInput = JsonUtils.newNode();
testInput.set("regional", JsonUtils.newArrayNode().add(testRegionalNode));
J2735SupplementalVehicleExtensions result = SupplementalVehicleExtensionsBuilder
.evaluateSupplementalVehicleExtensions(new J2735BsmPart2Content(), testInput);
assertNotNull(result.getRegional());
}
@Test
public void testConstructorIsPrivate()
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<SupplementalVehicleExtensionsBuilder> constructor = SupplementalVehicleExtensionsBuilder.class
.getDeclaredConstructor();
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
try {
constructor.newInstance();
fail("Expected IllegalAccessException.class");
} catch (Exception e) {
assertEquals(InvocationTargetException.class, e.getClass());
}
}
}
| |
package com.google.rolecall.services;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.Collections;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;
import com.google.rolecall.jsonobjects.UserInfo;
import com.google.rolecall.models.CastMember;
import com.google.rolecall.models.User;
import com.google.rolecall.repos.CastMemberRepository;
import com.google.rolecall.repos.UserRepository;
import com.google.rolecall.restcontrollers.exceptionhandling.RequestExceptions.EntityNotFoundException;
import com.google.rolecall.restcontrollers.exceptionhandling.RequestExceptions.InvalidParameterException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
public class UserServiceTests {
private UserRepository userRepo;
private CastMemberRepository castMemberRepo;
private UserServices userService;
private User user;
private int invalidId = 30;
private int id = 1;
private String firstName = "Jared";
private String middleName = "";
private String lastName = "Hirsch";
private String suffix = "";
private String email = "goodemail@gmail.com";
private String notificationEmail = "jhnotifications@gmail.com";
private String pictureFile = "Jared_Hirsh";
private String phoneNumber = "123-456-7890";
private Calendar dateJoined = (new Calendar.Builder()).setDate(1, 1, 1).build();
private Boolean isAdmin = true;
private Boolean isChoreographer = true;
private Boolean isDancer = true;
private Boolean isOther = true;
private Boolean canLogin = true;
private Boolean notifications = false;
private Boolean managePerformances = true;
private Boolean manageCasts = false;
private Boolean managePieces = true;
private Boolean manageRoles = false;
private Boolean manageRules = true;
private String emergencyContactName = "Mom";
private String emergencyContactNumber = "333-333-3333";
private String comments = "A good boi.";
private Boolean isActive = true;
@BeforeEach
public void init() {
userRepo = mock(UserRepository.class);
castMemberRepo = mock(CastMemberRepository.class);
userService = new UserServices(userRepo, castMemberRepo, null);
User.Builder builder = User.newBuilder()
.setFirstName(firstName)
.setMiddleName(middleName)
.setLastName(lastName)
.setSuffix(suffix)
.setEmail(email)
.setNotificationEmail(notificationEmail)
.setPictureFile(pictureFile)
.setPhoneNumber(phoneNumber)
.setDateJoined(dateJoined)
.setIsAdmin(isAdmin)
.setIsChoreographer(isChoreographer)
.setIsDancer(isDancer)
.setIsOther(isOther)
.setCanLogin(canLogin)
.setRecievesNotifications(notifications)
.setManagePerformances(managePerformances)
.setManageCasts(manageCasts)
.setManagePieces(managePieces)
.setManageRoles(manageRoles)
.setManageRules(manageRules)
.setEmergencyContactName(emergencyContactName)
.setEmergencyContactNumber(emergencyContactNumber)
.setComments(comments)
.setIsActive(isActive)
;
try {
user = builder.build();
} catch(InvalidParameterException e) {
throw new Error("Unable to creat User");
}
lenient().doReturn(Optional.of(user)).when(userRepo).findById(id);
lenient().doReturn(Collections.singletonList(user)).when(userRepo).findAll();
lenient().doReturn(Optional.empty()).when(userRepo).findById(invalidId);
lenient().doReturn(Optional.of(user)).when(userRepo).findByEmailIgnoreCase(email);
lenient().when(userRepo.save(any(User.class))).thenAnswer(new Answer<User>() {
@Override
public User answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (User) args[0];
}
});
}
@Test
public void getAllUsers_success() throws Exception {
// Execute
List<User> response = userService.getAllUsers();
// Assert
assertThat(response).containsExactly(user);
}
@Test
public void getUserById_success() throws Exception {
// Execute
User response = userService.getUser(id);
//
assertThat(response).isEqualTo(user);
assertThat(response.getFirstName()).isEqualTo(firstName);
assertThat(response.getLastName()).isEqualTo(lastName);
assertThat(response.getEmail()).isEqualTo(email);
assertThat(response.getPhoneNumber()).isEqualTo(phoneNumber);
assertThat(response.getDateJoined().get()).isEqualTo(dateJoined);
assertThat(response.isAdmin()).isEqualTo(isAdmin.booleanValue());
assertThat(response.isChoreographer()).isEqualTo(isChoreographer.booleanValue());
assertThat(response.isDancer()).isEqualTo(isDancer.booleanValue());
assertThat(response.isOther()).isEqualTo(isOther.booleanValue());
assertThat(response.canLogin()).isEqualTo(canLogin.booleanValue());
assertThat(response.getEmergencyContactName()).isEqualTo(emergencyContactName);
assertThat(response.getEmergencyContactNumber()).isEqualTo(emergencyContactNumber);
assertThat(response.getComments()).isEqualTo(comments);
assertThat(response.isActive()).isEqualTo(isActive.booleanValue());
}
@Test
public void getInvalidUserById_failure() throws Exception {
// Execute
EntityNotFoundException exception = assertThrows(EntityNotFoundException.class,
() -> { userService.getUser(invalidId); });
// Assert
assertThat(exception).hasMessageThat().contains(Integer.toString(invalidId));
}
@Test
public void createNewUserAllProperties_success() throws Exception {
// Setup
Calendar newdateJoined = (new Calendar.Builder()).setDate(2, 2, 2).build();
UserInfo newUser = UserInfo.newBuilder()
.setFirstName("Logan")
.setLastName("Hirsch")
.setEmail("email@gmail.com")
.setPhoneNumber("123-456-7890")
.setDateJoined(newdateJoined)
.setIsAdmin(true)
.setIsChoreographer(true)
.setIsDancer(true)
.setIsOther(false)
.setCanLogin(false)
.setNotifications(false)
.setManagePerformances(true)
.setManageCasts(true)
.setManagePieces(true)
.setManageRoles(true)
.setManageRules(true)
.setEmergencyContactName("Mem")
.setEmergencyContactNumber("6")
.setComments("5")
.build();
// Mock
lenient().doReturn(Optional.empty()).when(userRepo).findByEmailIgnoreCase("email@gmail.com");
// Execute
User userOut = userService.createUser(newUser);
// Assert
verify(userRepo, times(1)).save(any(User.class));
assertThat(userOut.getFirstName()).isEqualTo("Logan");
assertThat(userOut.getLastName()).isEqualTo("Hirsch");
assertThat(userOut.getEmail()).isEqualTo("email@gmail.com");
assertThat(userOut.getPhoneNumber()).isEqualTo("123-456-7890");
assertThat(userOut.getDateJoined().get()).isEqualTo(newdateJoined);
assertThat(userOut.isAdmin()).isTrue();
assertThat(userOut.isChoreographer()).isTrue();
assertThat(userOut.isDancer()).isTrue();
assertThat(userOut.isOther()).isFalse();
assertThat(userOut.canLogin()).isFalse();
assertThat(userOut.recievesNotifications()).isFalse();
assertThat(userOut.canManagePerformances()).isTrue();
assertThat(userOut.canManageCasts()).isTrue();
assertThat(userOut.canManagePieces()).isTrue();
assertThat(userOut.canManageRoles()).isTrue();
assertThat(userOut.canManageRules()).isTrue();
assertThat(userOut.getEmergencyContactName()).isEqualTo("Mem");
assertThat(userOut.getEmergencyContactNumber()).isEqualTo("6");
assertThat(userOut.getComments()).isEqualTo("5");
assertThat(userOut.isActive()).isTrue();
}
@Test
public void createNewUserMinimumProperties_success() throws Exception {
// Setup
UserInfo newUser = UserInfo.newBuilder()
.setFirstName("Logan")
.setLastName("Hirsch")
.setEmail("email@gmail.com")
.setPhoneNumber("123-456-7890")
.build();
// Mock
lenient().doReturn(Optional.empty()).when(userRepo).findByEmailIgnoreCase("email@gmail.com");
// Execute
User userOut = userService.createUser(newUser);
// Assert
verify(userRepo, times(1)).save(any(User.class));
assertThat(userOut.getFirstName()).isEqualTo("Logan");
assertThat(userOut.getLastName()).isEqualTo("Hirsch");
assertThat(userOut.getEmail()).isEqualTo("email@gmail.com");
assertThat(userOut.getPhoneNumber()).isEqualTo("123-456-7890");
assertThat(userOut.getDateJoined().isEmpty()).isTrue();
assertThat(userOut.isAdmin()).isFalse();
assertThat(userOut.isChoreographer()).isFalse();
assertThat(userOut.isDancer()).isFalse();
assertThat(userOut.isOther()).isFalse();
assertThat(userOut.canLogin()).isFalse();
assertThat(userOut.recievesNotifications()).isTrue();
assertThat(userOut.canManagePerformances()).isFalse();
assertThat(userOut.canManageCasts()).isFalse();
assertThat(userOut.canManagePieces()).isFalse();
assertThat(userOut.canManageRoles()).isFalse();
assertThat(userOut.canManageRules()).isFalse();
assertThat(userOut.getEmergencyContactName()).isEqualTo("");
assertThat(userOut.getEmergencyContactNumber()).isEqualTo("");
assertThat(userOut.getComments()).isEqualTo("");
assertThat(userOut.isActive()).isTrue();
}
@Test
public void createNewUserMissingEmail_failure() throws Exception {
// Setup
UserInfo newUser = UserInfo.newBuilder().build();
// Execute
InvalidParameterException exception = assertThrows(InvalidParameterException.class,
() -> { userService.createUser(newUser); });
// Assert
verify(userRepo, never()).save(any(User.class));
assertThat(exception).hasMessageThat().contains("email");
}
@Test
public void createNewUserMissingAllPropertiesButEmail_failure() throws Exception {
// Setup
UserInfo newUser = UserInfo.newBuilder().setEmail("email@email.com").build();
// Execute
InvalidParameterException exception = assertThrows(InvalidParameterException.class,
() -> { userService.createUser(newUser); });
// Assert
verify(userRepo, never()).save(any(User.class));
assertThat(exception).hasMessageThat().contains("firstName");
assertThat(exception).hasMessageThat().contains("lastName");
}
@Test
public void createNewUserBadEmail_failure() throws Exception {
// Setup
UserInfo newUser = UserInfo.newBuilder()
.setFirstName("Logan")
.setLastName("Hirsch")
.setEmail("badEmail")
.build();
// Mock
lenient().doReturn(Optional.empty()).when(userRepo).findByEmailIgnoreCase("badEmail");
// Execute
InvalidParameterException exception = assertThrows(InvalidParameterException.class,
() -> { userService.createUser(newUser); });
// Assert
verify(userRepo, never()).save(any(User.class));
assertThat(exception).hasMessageThat().contains("valid email address");
}
@Test
public void createNewUserEmailExists_failure() throws Exception {
// Setup
UserInfo newUser = UserInfo.newBuilder()
.setFirstName("Logan")
.setLastName("Hirsch")
.setEmail(email)
.build();
// Execute
InvalidParameterException exception = assertThrows(InvalidParameterException.class,
() -> { userService.createUser(newUser); });
// Assert
verify(userRepo, never()).save(any(User.class));
assertThat(exception).hasMessageThat().contains(email);
}
@Test
public void editAllUserProperties_success() throws Exception {
// Setup
Calendar newdateJoined = (new Calendar.Builder()).setDate(2, 2, 2).build();
UserInfo newUser = UserInfo.newBuilder()
.setId(id)
.setFirstName("Logan")
.setLastName("taco")
// TODO: verify that this should be ignored
.setEmail("email@gmail.com") // Should be ignored
.setPhoneNumber("098-765-4321")
.setDateJoined(newdateJoined)
.setIsAdmin(false)
.setIsChoreographer(false)
.setIsDancer(false)
.setIsOther(true)
.setCanLogin(false)
.setNotifications(true)
.setManagePerformances(false)
.setManageCasts(true)
.setManagePieces(false)
.setManageRoles(true)
.setManageRules(false)
.setEmergencyContactName("Mem")
.setEmergencyContactNumber("5")
.setComments("lit")
.setIsActive(false)
.build();
// Execute
User userOut = userService.editUser(newUser);
// Assert
verify(userRepo, times(1)).save(any(User.class));
assertThat(userOut.getFirstName()).isEqualTo("Logan");
assertThat(userOut.getLastName()).isEqualTo("taco");
// TODO: Figure out if this is supposed to work (that updating the email field is
// blocked on the server. It is blocked on the frontennd)
// assertThat(userOut.getEmail()).isEqualTo(email);
assertThat(userOut.getPhoneNumber()).isEqualTo("098-765-4321");
assertThat(userOut.getDateJoined().get()).isEqualTo(newdateJoined);
assertThat(userOut.isAdmin()).isFalse();
assertThat(userOut.isChoreographer()).isFalse();
assertThat(userOut.isDancer()).isFalse();
assertThat(userOut.isOther()).isTrue();
assertThat(userOut.canLogin()).isFalse();
assertThat(userOut.recievesNotifications()).isTrue();
assertThat(userOut.canManagePerformances()).isFalse();
assertThat(userOut.canManageCasts()).isTrue();
assertThat(userOut.canManagePieces()).isFalse();
assertThat(userOut.canManageRoles()).isTrue();
assertThat(userOut.canManageRules()).isFalse();
assertThat(userOut.getEmergencyContactName()).isEqualTo("Mem");
assertThat(userOut.getEmergencyContactNumber()).isEqualTo("5");
assertThat(userOut.getComments()).isEqualTo("lit");
assertThat(userOut.isActive()).isFalse();
}
@Test
public void editUserFirstNameOnly_success() throws Exception {
// Setup
UserInfo newUser = UserInfo.newBuilder()
.setId(id)
.setFirstName("Logan")
.build();
// Execute
User userOut = userService.editUser(newUser);
// Assert
verify(userRepo, times(1)).save(any(User.class));
assertThat(userOut.getFirstName()).isEqualTo("Logan");
assertThat(userOut.getLastName()).isEqualTo(lastName);
assertThat(userOut.getEmail()).isEqualTo(email);
assertThat(userOut.getPhoneNumber()).isEqualTo(phoneNumber);
assertThat(userOut.getDateJoined().get()).isEqualTo(dateJoined);
assertThat(userOut.isAdmin()).isTrue();
assertThat(userOut.isChoreographer()).isTrue();
assertThat(userOut.isDancer()).isTrue();
assertThat(userOut.isOther()).isTrue();
assertThat(userOut.canLogin()).isTrue();
assertThat(userOut.recievesNotifications()).isFalse();
assertThat(userOut.canManagePerformances()).isTrue();
assertThat(userOut.canManageCasts()).isFalse();
assertThat(userOut.canManagePieces()).isTrue();
assertThat(userOut.canManageRoles()).isFalse();
assertThat(userOut.canManageRules()).isTrue();
assertThat(userOut.getEmergencyContactName()).isEqualTo(emergencyContactName);
assertThat(userOut.getEmergencyContactNumber()).isEqualTo(emergencyContactNumber);
assertThat(userOut.getComments()).isEqualTo(comments);
assertThat(userOut.isActive()).isTrue();
}
@Test
public void editUserFirstNoChanges_success() throws Exception {
// Setup
UserInfo newUser = UserInfo.newBuilder()
.setId(id)
.build();
// Execute
User userOut = userService.editUser(newUser);
// Assert
verify(userRepo, times(1)).save(any(User.class));
assertThat(userOut.getFirstName()).isEqualTo(firstName);
assertThat(userOut.getLastName()).isEqualTo(lastName);
assertThat(userOut.getEmail()).isEqualTo(email);
assertThat(userOut.getPhoneNumber()).isEqualTo(phoneNumber);
assertThat(userOut.getDateJoined().get()).isEqualTo(dateJoined);
assertThat(userOut.isAdmin()).isTrue();
assertThat(userOut.isChoreographer()).isTrue();
assertThat(userOut.isDancer()).isTrue();
assertThat(userOut.isOther()).isTrue();
assertThat(userOut.canLogin()).isTrue();
assertThat(userOut.recievesNotifications()).isFalse();
assertThat(userOut.canManagePerformances()).isTrue();
assertThat(userOut.canManageCasts()).isFalse();
assertThat(userOut.canManagePieces()).isTrue();
assertThat(userOut.canManageRoles()).isFalse();
assertThat(userOut.canManageRules()).isTrue();
assertThat(userOut.getEmergencyContactName()).isEqualTo(emergencyContactName);
assertThat(userOut.getEmergencyContactNumber()).isEqualTo(emergencyContactNumber);
assertThat(userOut.getComments()).isEqualTo(comments);
assertThat(userOut.isActive()).isTrue();
}
@Test
public void editInvalidUser_failure() throws Exception {
// Setup
UserInfo newUser = UserInfo.newBuilder()
.setId(invalidId)
.build();
// Execute
EntityNotFoundException exception = assertThrows(EntityNotFoundException.class,
() -> { userService.editUser(newUser); });
// Assert
verify(userRepo, never()).save(any(User.class));
assertThat(exception).hasMessageThat().contains(Integer.toString(invalidId));
}
@Test
public void deleteUser_success() throws Exception {
// Mock
lenient().doNothing().when(userRepo).deleteById(id);
lenient().doReturn(Optional.of(new CastMember())).when(castMemberRepo).findFirstByUser(any(User.class));
// Execute
// TODO: fixe below code
// The below code breaks because user with ID = 1 is part an existing Cast of Performance.
// This is not the case as far as I can tell, but I don't know how to debug the
// findFirstByUser queries.
// userService.deleteUser(id);
// Assert
// verify(userRepo, times(1)).deleteById(id);
}
@Test
public void deleteUserBadId_failure() throws Exception {
// Execute
EntityNotFoundException exception = assertThrows(EntityNotFoundException.class,
() -> { userService.deleteUser(invalidId); });
// Assert
verify(userRepo, never()).deleteById(any(Integer.class));
assertThat(exception).hasMessageThat().contains(Integer.toString(invalidId));
}
}
| |
// Copyright (C) 2009 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.gerrit.httpd.rpc.patch;
import com.google.gerrit.common.data.CommentDetail;
import com.google.gerrit.common.data.PatchScript;
import com.google.gerrit.common.data.PatchScript.DisplayMethod;
import com.google.gerrit.prettify.common.EditList;
import com.google.gerrit.prettify.common.SparseFileContent;
import com.google.gerrit.reviewdb.AccountDiffPreference;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.Patch;
import com.google.gerrit.reviewdb.PatchLineComment;
import com.google.gerrit.reviewdb.AccountDiffPreference.Whitespace;
import com.google.gerrit.reviewdb.Patch.PatchType;
import com.google.gerrit.server.FileTypeRegistry;
import com.google.gerrit.server.patch.PatchListEntry;
import com.google.gerrit.server.patch.Text;
import com.google.inject.Inject;
import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil2;
import org.eclipse.jgit.diff.Edit;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class PatchScriptBuilder {
static final int MAX_CONTEXT = 5000000;
static final int BIG_FILE = 9000;
private static final Comparator<Edit> EDIT_SORT = new Comparator<Edit>() {
@Override
public int compare(final Edit o1, final Edit o2) {
return o1.getBeginA() - o2.getBeginA();
}
};
private Repository db;
private Change change;
private AccountDiffPreference diffPrefs;
private boolean againstParent;
private ObjectId aId;
private ObjectId bId;
private final Side a;
private final Side b;
private List<Edit> edits;
private final FileTypeRegistry registry;
private int context;
@Inject
PatchScriptBuilder(final FileTypeRegistry ftr) {
a = new Side();
b = new Side();
registry = ftr;
}
void setRepository(final Repository r) {
db = r;
}
void setChange(final Change c) {
this.change = c;
}
void setDiffPrefs(final AccountDiffPreference dp) {
diffPrefs = dp;
context = diffPrefs.getContext();
if (context == AccountDiffPreference.WHOLE_FILE_CONTEXT) {
context = MAX_CONTEXT;
} else if (context > MAX_CONTEXT) {
context = MAX_CONTEXT;
}
}
void setTrees(final boolean ap, final ObjectId a, final ObjectId b) {
againstParent = ap;
aId = a;
bId = b;
}
PatchScript toPatchScript(final PatchListEntry content,
final boolean intralineDifference, final CommentDetail comments,
final List<Patch> history) throws IOException {
if (content.getPatchType() == PatchType.N_WAY) {
// For a diff --cc format we don't support converting it into
// a patch script. Instead treat everything as a file header.
//
return new PatchScript(change.getKey(), content.getChangeType(), content
.getOldName(), content.getNewName(), content.getHeaderLines(),
diffPrefs, a.dst, b.dst, Collections.<Edit> emptyList(),
a.displayMethod, b.displayMethod, comments, history, false, false);
}
a.path = oldName(content);
b.path = newName(content);
a.resolve(null, aId);
b.resolve(a, bId);
edits = new ArrayList<Edit>(content.getEdits());
ensureCommentsVisible(comments);
boolean hugeFile = false;
if (a.mode == FileMode.GITLINK || b.mode == FileMode.GITLINK) {
} else if (a.src == b.src && a.size() <= context
&& content.getEdits().isEmpty()) {
// Odd special case; the files are identical (100% rename or copy)
// and the user has asked for context that is larger than the file.
// Send them the entire file, with an empty edit after the last line.
//
for (int i = 0; i < a.size(); i++) {
a.addLine(i);
}
edits = new ArrayList<Edit>(1);
edits.add(new Edit(a.size(), a.size()));
} else {
if (BIG_FILE < Math.max(a.size(), b.size())) {
// IF the file is really large, we disable things to avoid choking
// the browser client.
//
diffPrefs.setContext((short) Math.min(25, context));
diffPrefs.setSyntaxHighlighting(false);
context = diffPrefs.getContext();
hugeFile = true;
} else if (diffPrefs.isSyntaxHighlighting()) {
// In order to syntax highlight the file properly we need to
// give the client the complete file contents. So force our
// context temporarily to the complete file size.
//
context = MAX_CONTEXT;
}
packContent(diffPrefs.getIgnoreWhitespace() != Whitespace.IGNORE_NONE);
}
return new PatchScript(change.getKey(), content.getChangeType(), content
.getOldName(), content.getNewName(), content.getHeaderLines(),
diffPrefs, a.dst, b.dst, edits, a.displayMethod, b.displayMethod,
comments, history, hugeFile, intralineDifference);
}
private static String oldName(final PatchListEntry entry) {
switch (entry.getChangeType()) {
case ADDED:
return null;
case DELETED:
case MODIFIED:
return entry.getNewName();
case COPIED:
case RENAMED:
default:
return entry.getOldName();
}
}
private static String newName(final PatchListEntry entry) {
switch (entry.getChangeType()) {
case DELETED:
return null;
case ADDED:
case MODIFIED:
case COPIED:
case RENAMED:
default:
return entry.getNewName();
}
}
private void ensureCommentsVisible(final CommentDetail comments) {
if (comments.getCommentsA().isEmpty() && comments.getCommentsB().isEmpty()) {
// No comments, no additional dummy edits are required.
//
return;
}
// Construct empty Edit blocks around each location where a comment is.
// This will force the later packContent method to include the regions
// containing comments, potentially combining those regions together if
// they have overlapping contexts. UI renders will also be able to make
// correct hunks from this, but because the Edit is empty they will not
// style it specially.
//
final List<Edit> empty = new ArrayList<Edit>();
int lastLine;
lastLine = -1;
for (PatchLineComment plc : comments.getCommentsA()) {
final int a = plc.getLine();
if (lastLine != a) {
final int b = mapA2B(a - 1);
if (0 <= b) {
safeAdd(empty, new Edit(a - 1, b));
}
lastLine = a;
}
}
lastLine = -1;
for (PatchLineComment plc : comments.getCommentsB()) {
final int b = plc.getLine();
if (lastLine != b) {
final int a = mapB2A(b - 1);
if (0 <= a) {
safeAdd(empty, new Edit(a, b - 1));
}
lastLine = b;
}
}
// Sort the final list by the index in A, so packContent can combine
// them correctly later.
//
edits.addAll(empty);
Collections.sort(edits, EDIT_SORT);
}
private void safeAdd(final List<Edit> empty, final Edit toAdd) {
final int a = toAdd.getBeginA();
final int b = toAdd.getBeginB();
for (final Edit e : edits) {
if (e.getBeginA() <= a && a <= e.getEndA()) {
return;
}
if (e.getBeginB() <= b && b <= e.getEndB()) {
return;
}
}
empty.add(toAdd);
}
private int mapA2B(final int a) {
if (edits.isEmpty()) {
// Magic special case of an unmodified file.
//
return a;
}
for (int i = 0; i < edits.size(); i++) {
final Edit e = edits.get(i);
if (a < e.getBeginA()) {
if (i == 0) {
// Special case of context at start of file.
//
return a;
}
return e.getBeginB() - (e.getBeginA() - a);
}
if (e.getBeginA() <= a && a <= e.getEndA()) {
return -1;
}
}
final Edit last = edits.get(edits.size() - 1);
return last.getBeginB() + (a - last.getEndA());
}
private int mapB2A(final int b) {
if (edits.isEmpty()) {
// Magic special case of an unmodified file.
//
return b;
}
for (int i = 0; i < edits.size(); i++) {
final Edit e = edits.get(i);
if (b < e.getBeginB()) {
if (i == 0) {
// Special case of context at start of file.
//
return b;
}
return e.getBeginA() - (e.getBeginB() - b);
}
if (e.getBeginB() <= b && b <= e.getEndB()) {
return -1;
}
}
final Edit last = edits.get(edits.size() - 1);
return last.getBeginA() + (b - last.getEndB());
}
private void packContent(boolean ignoredWhitespace) {
EditList list = new EditList(edits, context, a.size(), b.size());
for (final EditList.Hunk hunk : list.getHunks()) {
while (hunk.next()) {
if (hunk.isContextLine()) {
final String lineA = a.src.getLine(hunk.getCurA());
a.dst.addLine(hunk.getCurA(), lineA);
if (ignoredWhitespace) {
// If we ignored whitespace in some form, also get the line
// from b when it does not exactly match the line from a.
//
final String lineB = b.src.getLine(hunk.getCurB());
if (!lineA.equals(lineB)) {
b.dst.addLine(hunk.getCurB(), lineB);
}
}
hunk.incBoth();
continue;
}
if (hunk.isDeletedA()) {
a.addLine(hunk.getCurA());
hunk.incA();
}
if (hunk.isInsertedB()) {
b.addLine(hunk.getCurB());
hunk.incB();
}
}
}
}
private class Side {
String path;
ObjectId id;
FileMode mode;
byte[] srcContent;
Text src;
MimeType mimeType = MimeUtil2.UNKNOWN_MIME_TYPE;
DisplayMethod displayMethod = DisplayMethod.DIFF;
final SparseFileContent dst = new SparseFileContent();
int size() {
return src != null ? src.size() : 0;
}
void addLine(int line) {
dst.addLine(line, src.getLine(line));
}
void resolve(final Side other, final ObjectId within) throws IOException {
try {
final boolean reuse;
if (Patch.COMMIT_MSG.equals(path)) {
if (againstParent && (aId == within || within.equals(aId))) {
id = ObjectId.zeroId();
src = Text.EMPTY;
srcContent = Text.NO_BYTES;
mode = FileMode.MISSING;
displayMethod = DisplayMethod.NONE;
} else {
id = within;
src = Text.forCommit(db, within);
srcContent = src.getContent();
if (src == Text.EMPTY) {
mode = FileMode.MISSING;
displayMethod = DisplayMethod.NONE;
} else {
mode = FileMode.REGULAR_FILE;
}
}
reuse = false;
} else {
final TreeWalk tw = find(within);
id = tw != null ? tw.getObjectId(0) : ObjectId.zeroId();
mode = tw != null ? tw.getFileMode(0) : FileMode.MISSING;
reuse = other != null && other.id.equals(id) && other.mode == mode;
if (reuse) {
srcContent = other.srcContent;
} else if (mode.getObjectType() == Constants.OBJ_BLOB) {
final ObjectLoader ldr = db.openObject(id);
if (ldr == null) {
throw new MissingObjectException(id, Constants.TYPE_BLOB);
}
srcContent = ldr.getCachedBytes();
if (ldr.getType() != Constants.OBJ_BLOB) {
throw new IncorrectObjectTypeException(id, Constants.TYPE_BLOB);
}
} else {
srcContent = Text.NO_BYTES;
}
if (reuse) {
mimeType = other.mimeType;
displayMethod = other.displayMethod;
src = other.src;
} else if (srcContent.length > 0 && FileMode.SYMLINK != mode) {
mimeType = registry.getMimeType(path, srcContent);
if ("image".equals(mimeType.getMediaType())
&& registry.isSafeInline(mimeType)) {
displayMethod = DisplayMethod.IMG;
}
}
}
if (mode == FileMode.MISSING) {
displayMethod = DisplayMethod.NONE;
}
if (!reuse) {
if (srcContent == Text.NO_BYTES) {
src = Text.EMPTY;
} else {
src = new Text(srcContent);
}
}
if (srcContent.length > 0 && srcContent[srcContent.length - 1] != '\n') {
dst.setMissingNewlineAtEnd(true);
}
dst.setSize(size());
dst.setPath(path);
} catch (IOException err) {
throw new IOException("Cannot read " + within.name() + ":" + path, err);
}
}
private TreeWalk find(final ObjectId within) throws MissingObjectException,
IncorrectObjectTypeException, CorruptObjectException, IOException {
if (path == null) {
return null;
}
final RevWalk rw = new RevWalk(db);
final RevTree tree = rw.parseTree(within);
return TreeWalk.forPath(db, path, tree);
}
}
}
| |
/*
* Javassist, a Java-bytecode translator toolkit.
* Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. Alternatively, the contents of this file may be used under
* the terms of the GNU Lesser General Public License Version 2.1 or later,
* or the Apache License Version 2.0.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/
package javassist.tools.reflect;
import java.lang.reflect.Method;
import java.io.Serializable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* A runtime metaobject.
*
* <p>A <code>Metaobject</code> is created for
* every object at the base level. A different reflective object is
* associated with a different metaobject.
*
* <p>The metaobject intercepts method calls
* on the reflective object at the base-level. To change the behavior
* of the method calls, a subclass of <code>Metaobject</code>
* should be defined.
*
* <p>To obtain a metaobject, calls <code>_getMetaobject()</code>
* on a reflective object. For example,
*
* <ul><pre>Metaobject m = ((Metalevel)reflectiveObject)._getMetaobject();
* </pre></ul>
*
* @see javassist.tools.reflect.ClassMetaobject
* @see javassist.tools.reflect.Metalevel
*/
public class Metaobject implements Serializable {
protected ClassMetaobject classmetaobject;
protected Metalevel baseobject;
protected Method[] methods;
/**
* Constructs a <code>Metaobject</code>. The metaobject is
* constructed before the constructor is called on the base-level
* object.
*
* @param self the object that this metaobject is associated with.
* @param args the parameters passed to the constructor of
* <code>self</code>.
*/
public Metaobject(Object self, Object[] args) {
baseobject = (Metalevel)self;
classmetaobject = baseobject._getClass();
methods = classmetaobject.getReflectiveMethods();
}
/**
* Constructs a <code>Metaobject</code> without initialization.
* If calling this constructor, a subclass should be responsible
* for initialization.
*/
protected Metaobject() {
baseobject = null;
classmetaobject = null;
methods = null;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(baseobject);
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
baseobject = (Metalevel)in.readObject();
classmetaobject = baseobject._getClass();
methods = classmetaobject.getReflectiveMethods();
}
/**
* Obtains the class metaobject associated with this metaobject.
*
* @see javassist.tools.reflect.ClassMetaobject
*/
public final ClassMetaobject getClassMetaobject() {
return classmetaobject;
}
/**
* Obtains the object controlled by this metaobject.
*/
public final Object getObject() {
return baseobject;
}
/**
* Changes the object controlled by this metaobject.
*
* @param self the object
*/
public final void setObject(Object self) {
baseobject = (Metalevel)self;
classmetaobject = baseobject._getClass();
methods = classmetaobject.getReflectiveMethods();
// call _setMetaobject() after the metaobject is settled.
baseobject._setMetaobject(this);
}
/**
* Returns the name of the method specified
* by <code>identifier</code>.
*/
public final String getMethodName(int identifier) {
String mname = methods[identifier].getName();
int j = ClassMetaobject.methodPrefixLen;
for (;;) {
char c = mname.charAt(j++);
if (c < '0' || '9' < c)
break;
}
return mname.substring(j);
}
/**
* Returns an array of <code>Class</code> objects representing the
* formal parameter types of the method specified
* by <code>identifier</code>.
*/
public final Class[] getParameterTypes(int identifier) {
return methods[identifier].getParameterTypes();
}
/**
* Returns a <code>Class</code> objects representing the
* return type of the method specified by <code>identifier</code>.
*/
public final Class getReturnType(int identifier) {
return methods[identifier].getReturnType();
}
/**
* Is invoked when public fields of the base-level
* class are read and the runtime system intercepts it.
* This method simply returns the value of the field.
*
* <p>Every subclass of this class should redefine this method.
*/
public Object trapFieldRead(String name) {
Class jc = getClassMetaobject().getJavaClass();
try {
return jc.getField(name).get(getObject());
}
catch (NoSuchFieldException e) {
throw new RuntimeException(e.toString());
}
catch (IllegalAccessException e) {
throw new RuntimeException(e.toString());
}
}
/**
* Is invoked when public fields of the base-level
* class are modified and the runtime system intercepts it.
* This method simply sets the field to the given value.
*
* <p>Every subclass of this class should redefine this method.
*/
public void trapFieldWrite(String name, Object value) {
Class jc = getClassMetaobject().getJavaClass();
try {
jc.getField(name).set(getObject(), value);
}
catch (NoSuchFieldException e) {
throw new RuntimeException(e.toString());
}
catch (IllegalAccessException e) {
throw new RuntimeException(e.toString());
}
}
/**
* Is invoked when base-level method invocation is intercepted.
* This method simply executes the intercepted method invocation
* with the original parameters and returns the resulting value.
*
* <p>Every subclass of this class should redefine this method.
*
* <p>Note: this method is not invoked if the base-level method
* is invoked by a constructor in the super class. For example,
*
* <ul><pre>abstract class A {
* abstract void initialize();
* A() {
* initialize(); // not intercepted
* }
* }
*
* class B extends A {
* void initialize() { System.out.println("initialize()"); }
* B() {
* super();
* initialize(); // intercepted
* }
* }</pre></ul>
*
* <p>if an instance of B is created,
* the invocation of initialize() in B is intercepted only once.
* The first invocation by the constructor in A is not intercepted.
* This is because the link between a base-level object and a
* metaobject is not created until the execution of a
* constructor of the super class finishes.
*/
public Object trapMethodcall(int identifier, Object[] args)
throws Throwable
{
try {
return methods[identifier].invoke(getObject(), args);
}
catch (java.lang.reflect.InvocationTargetException e) {
throw e.getTargetException();
}
catch (java.lang.IllegalAccessException e) {
throw new CannotInvokeException(e);
}
}
}
| |
/*
* 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.fontbox.cff;
/**
* This is specialized CFFEncoding. It's used if the EncodingId of a font is set to 1.
*
* @author Villu Ruusmann
*/
public final class CFFExpertEncoding extends CFFEncoding
{
private static final int CHAR_CODE = 0;
private static final int CHAR_SID = 1;
private CFFExpertEncoding()
{
// Table of character codes and their corresponding sid.
int[][] cffExpertEncodingTable = {
{0, 0},
{1, 0},
{2, 0},
{3, 0},
{4, 0},
{5, 0},
{6, 0},
{7, 0},
{8, 0},
{9, 0},
{10, 0},
{11, 0},
{12, 0},
{13, 0},
{14, 0},
{15, 0},
{16, 0},
{17, 0},
{18, 0},
{19, 0},
{20, 0},
{21, 0},
{22, 0},
{23, 0},
{24, 0},
{25, 0},
{26, 0},
{27, 0},
{28, 0},
{29, 0},
{30, 0},
{31, 0},
{32, 1},
{33, 229},
{34, 230},
{35, 0},
{36, 231},
{37, 232},
{38, 233},
{39, 234},
{40, 235},
{41, 236},
{42, 237},
{43, 238},
{44, 13},
{45, 14},
{46, 15},
{47, 99},
{48, 239},
{49, 240},
{50, 241},
{51, 242},
{52, 243},
{53, 244},
{54, 245},
{55, 246},
{56, 247},
{57, 248},
{58, 27},
{59, 28},
{60, 249},
{61, 250},
{62, 251},
{63, 252},
{64, 0},
{65, 253},
{66, 254},
{67, 255},
{68, 256},
{69, 257},
{70, 0},
{71, 0},
{72, 0},
{73, 258},
{74, 0},
{75, 0},
{76, 259},
{77, 260},
{78, 261},
{79, 262},
{80, 0},
{81, 0},
{82, 263},
{83, 264},
{84, 265},
{85, 0},
{86, 266},
{87, 109},
{88, 110},
{89, 267},
{90, 268},
{91, 269},
{92, 0},
{93, 270},
{94, 271},
{95, 272},
{96, 273},
{97, 274},
{98, 275},
{99, 276},
{100, 277},
{101, 278},
{102, 279},
{103, 280},
{104, 281},
{105, 282},
{106, 283},
{107, 284},
{108, 285},
{109, 286},
{110, 287},
{111, 288},
{112, 289},
{113, 290},
{114, 291},
{115, 292},
{116, 293},
{117, 294},
{118, 295},
{119, 296},
{120, 297},
{121, 298},
{122, 299},
{123, 300},
{124, 301},
{125, 302},
{126, 303},
{127, 0},
{128, 0},
{129, 0},
{130, 0},
{131, 0},
{132, 0},
{133, 0},
{134, 0},
{135, 0},
{136, 0},
{137, 0},
{138, 0},
{139, 0},
{140, 0},
{141, 0},
{142, 0},
{143, 0},
{144, 0},
{145, 0},
{146, 0},
{147, 0},
{148, 0},
{149, 0},
{150, 0},
{151, 0},
{152, 0},
{153, 0},
{154, 0},
{155, 0},
{156, 0},
{157, 0},
{158, 0},
{159, 0},
{160, 0},
{161, 304},
{162, 305},
{163, 306},
{164, 0},
{165, 0},
{166, 307},
{167, 308},
{168, 309},
{169, 310},
{170, 311},
{171, 0},
{172, 312},
{173, 0},
{174, 0},
{175, 313},
{176, 0},
{177, 0},
{178, 314},
{179, 315},
{180, 0},
{181, 0},
{182, 316},
{183, 317},
{184, 318},
{185, 0},
{186, 0},
{187, 0},
{188, 158},
{189, 155},
{190, 163},
{191, 319},
{192, 320},
{193, 321},
{194, 322},
{195, 323},
{196, 324},
{197, 325},
{198, 0},
{199, 0},
{200, 326},
{201, 150},
{202, 164},
{203, 169},
{204, 327},
{205, 328},
{206, 329},
{207, 330},
{208, 331},
{209, 332},
{210, 333},
{211, 334},
{212, 335},
{213, 336},
{214, 337},
{215, 338},
{216, 339},
{217, 340},
{218, 341},
{219, 342},
{220, 343},
{221, 344},
{222, 345},
{223, 346},
{224, 347},
{225, 348},
{226, 349},
{227, 350},
{228, 351},
{229, 352},
{230, 353},
{231, 354},
{232, 355},
{233, 356},
{234, 357},
{235, 358},
{236, 359},
{237, 360},
{238, 361},
{239, 362},
{240, 363},
{241, 364},
{242, 365},
{243, 366},
{244, 367},
{245, 368},
{246, 369},
{247, 370},
{248, 371},
{249, 372},
{250, 373},
{251, 374},
{252, 375},
{253, 376},
{254, 377},
{255, 378}
};
for (int[] encodingEntry : cffExpertEncodingTable)
{
add(encodingEntry[CHAR_CODE], encodingEntry[CHAR_SID]);
}
}
/**
* Returns an instance of the CFFExportEncoding class.
* @return an instance of CFFExportEncoding
*/
public static CFFExpertEncoding getInstance()
{
return CFFExpertEncoding.INSTANCE;
}
private static final CFFExpertEncoding INSTANCE = new CFFExpertEncoding();
}
| |
/*
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.engine;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import org.apache.cordova.CordovaDialogsHelper;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
/**
* This class is the WebChromeClient that implements callbacks for our web view.
* The kind of callbacks that happen here are on the chrome outside the document,
* such as onCreateWindow(), onConsoleMessage(), onProgressChanged(), etc. Related
* to but different than CordovaWebViewClient.
*/
public class SystemWebChromeClient extends WebChromeClient {
private static final int FILECHOOSER_RESULTCODE = 5173;
private static final String LOG_TAG = "SystemWebChromeClient";
private long MAX_QUOTA = 100 * 1024 * 1024;
protected final SystemWebViewEngine parentEngine;
// the video progress view
private View mVideoProgressView;
private CordovaDialogsHelper dialogsHelper;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private View mCustomView;
public SystemWebChromeClient(SystemWebViewEngine parentEngine) {
this.parentEngine = parentEngine;
dialogsHelper = new CordovaDialogsHelper(parentEngine.webView.getContext());
}
/**
* Tell the client to display a javascript alert dialog.
*/
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
dialogsHelper.showAlert(message, new CordovaDialogsHelper.Result() {
@Override public void gotResult(boolean success, String value) {
if (success) {
result.confirm();
} else {
result.cancel();
}
}
});
return true;
}
/**
* Tell the client to display a confirm dialog to the user.
*/
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
dialogsHelper.showConfirm(message, new CordovaDialogsHelper.Result() {
@Override
public void gotResult(boolean success, String value) {
if (success) {
result.confirm();
} else {
result.cancel();
}
}
});
return true;
}
/**
* Tell the client to display a prompt dialog to the user.
* If the client returns true, WebView will assume that the client will
* handle the prompt dialog and call the appropriate JsPromptResult method.
*
* Since we are hacking prompts for our own purposes, we should not be using them for
* this purpose, perhaps we should hack console.log to do this instead!
*/
@Override
public boolean onJsPrompt(WebView view, String origin, String message, String defaultValue, final JsPromptResult result) {
// Unlike the @JavascriptInterface bridge, this method is always called on the UI thread.
String handledRet = parentEngine.bridge.promptOnJsPrompt(origin, message, defaultValue);
if (handledRet != null) {
result.confirm(handledRet);
} else {
dialogsHelper.showPrompt(message, defaultValue, new CordovaDialogsHelper.Result() {
@Override
public void gotResult(boolean success, String value) {
if (success) {
result.confirm(value);
} else {
result.cancel();
}
}
});
}
return true;
}
/**
* Handle database quota exceeded notification.
*/
@Override
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
{
LOG.d(LOG_TAG, "onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
quotaUpdater.updateQuota(MAX_QUOTA);
}
// console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html
// Expect this to not compile in a future Android release!
@SuppressWarnings("deprecation")
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID)
{
//This is only for Android 2.1
if(android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.ECLAIR_MR1)
{
LOG.d(LOG_TAG, "%s: Line %d : %s", sourceID, lineNumber, message);
super.onConsoleMessage(message, lineNumber, sourceID);
}
}
@TargetApi(8)
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{
if (consoleMessage.message() != null)
LOG.d(LOG_TAG, "%s: Line %d : %s" , consoleMessage.sourceId() , consoleMessage.lineNumber(), consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
@Override
/**
* Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
*
* @param origin
* @param callback
*/
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
// API level 7 is required for this, see if we could lower this using something else
@Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
parentEngine.getCordovaWebView().showCustomView(view, callback);
}
@Override
public void onHideCustomView() {
parentEngine.getCordovaWebView().hideCustomView();
}
@Override
/**
* Ask the host application for a custom progress view to show while
* a <video> is loading.
* @return View The progress view.
*/
public View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
// Create a new Loading view programmatically.
// create the linear layout
LinearLayout layout = new LinearLayout(parentEngine.getView().getContext());
layout.setOrientation(LinearLayout.VERTICAL);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.setLayoutParams(layoutParams);
// the proress bar
ProgressBar bar = new ProgressBar(parentEngine.getView().getContext());
LinearLayout.LayoutParams barLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
barLayoutParams.gravity = Gravity.CENTER;
bar.setLayoutParams(barLayoutParams);
layout.addView(bar);
mVideoProgressView = layout;
}
return mVideoProgressView;
}
// <input type=file> support:
// openFileChooser() is for pre KitKat and in KitKat mr1 (it's known broken in KitKat).
// For Lollipop, we use onShowFileChooser().
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
this.openFileChooser(uploadMsg, "*/*");
}
public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) {
this.openFileChooser(uploadMsg, acceptType, null);
}
public void openFileChooser(final ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
parentEngine.cordova.startActivityForResult(new CordovaPlugin() {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
Log.d(LOG_TAG, "Receive file chooser URL: " + result);
uploadMsg.onReceiveValue(result);
}
}, intent, FILECHOOSER_RESULTCODE);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean onShowFileChooser(WebView webView, final ValueCallback<Uri[]> filePathsCallback, final WebChromeClient.FileChooserParams fileChooserParams) {
Intent intent = fileChooserParams.createIntent();
try {
parentEngine.cordova.startActivityForResult(new CordovaPlugin() {
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
Uri[] result = WebChromeClient.FileChooserParams.parseResult(resultCode, intent);
Log.d(LOG_TAG, "Receive file chooser URL: " + result);
filePathsCallback.onReceiveValue(result);
}
}, intent, FILECHOOSER_RESULTCODE);
} catch (ActivityNotFoundException e) {
Log.w("No activity found to handle file chooser intent.", e);
filePathsCallback.onReceiveValue(null);
}
return true;
}
public void destroyLastDialog(){
dialogsHelper.destroyLastDialog();
}
}
| |
package org.apache.taverna.scufl2.rdfxml;
/*
*
* 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.
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import org.apache.taverna.scufl2.api.activity.Activity;
import org.apache.taverna.scufl2.api.common.Configurable;
import org.apache.taverna.scufl2.api.container.WorkflowBundle;
import org.apache.taverna.scufl2.api.core.Processor;
import org.apache.taverna.scufl2.api.io.ReaderException;
import org.apache.taverna.scufl2.api.port.InputActivityPort;
import org.apache.taverna.scufl2.api.port.InputProcessorPort;
import org.apache.taverna.scufl2.api.port.OutputActivityPort;
import org.apache.taverna.scufl2.api.port.OutputProcessorPort;
import org.apache.taverna.scufl2.api.profiles.ProcessorBinding;
import org.apache.taverna.scufl2.api.profiles.ProcessorInputPortBinding;
import org.apache.taverna.scufl2.api.profiles.ProcessorOutputPortBinding;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.apache.taverna.scufl2.rdfxml.jaxb.Configuration;
import org.apache.taverna.scufl2.rdfxml.jaxb.ProcessorBinding.InputPortBinding;
import org.apache.taverna.scufl2.rdfxml.jaxb.ProcessorBinding.OutputPortBinding;
import org.apache.taverna.scufl2.rdfxml.jaxb.Profile;
import org.apache.taverna.scufl2.rdfxml.jaxb.ProfileDocument;
public class ProfileParser extends AbstractParser {
private static Logger logger = Logger.getLogger(ProfileParser.class
.getCanonicalName());
public ProfileParser() {
super();
}
public ProfileParser(ThreadLocal<ParserState> parserState) {
super(parserState);
}
@SuppressWarnings("unused")
private Element getChildElement(Element element) {
for (Node node : nodeIterable(element.getChildNodes()))
if (node instanceof Element)
return (Element) node;
return null;
}
private Iterable<Node> nodeIterable(final NodeList childNodes) {
return new Iterable<Node>() {
@Override
public Iterator<Node> iterator() {
return new Iterator<Node>() {
int position = 0;
@Override
public boolean hasNext() {
return childNodes.getLength() > position;
}
@Override
public Node next() {
return childNodes.item(position++);
}
@Override
public void remove() {
Node node = childNodes.item(position);
node.getParentNode().removeChild(node);
}
};
}
};
}
protected void parseActivity(
org.apache.taverna.scufl2.rdfxml.jaxb.Activity original) {
Activity activity = new Activity();
getParserState().push(activity);
try {
mapBean(original.getAbout(), activity);
if (original.getName() != null)
activity.setName(original.getName());
activity.setParent(getParserState().getCurrent(
org.apache.taverna.scufl2.api.profiles.Profile.class));
if (original.getType() != null)
activity.setType(resolve(original.getType().getResource()));
for (org.apache.taverna.scufl2.rdfxml.jaxb.Activity.InputActivityPort inputActivityPort : original
.getInputActivityPort())
parseInputActivityPort(inputActivityPort.getInputActivityPort());
for (org.apache.taverna.scufl2.rdfxml.jaxb.Activity.OutputActivityPort outputActivityPort : original
.getOutputActivityPort())
parseOutputActivityPort(outputActivityPort
.getOutputActivityPort());
} finally {
getParserState().pop();
}
}
private static final URI INTERNAL_DISPATCH_PREFIX = URI.create("http://ns.taverna.org.uk/2010/scufl2/taverna/dispatchlayer/");
protected void parseConfiguration(Configuration original)
throws ReaderException {
org.apache.taverna.scufl2.api.configurations.Configuration config = new org.apache.taverna.scufl2.api.configurations.Configuration();
boolean ignoreConfig = false;
if (original.getType() != null) {
URI type = resolve(original.getType().getResource());
if (! INTERNAL_DISPATCH_PREFIX.relativize(type).isAbsolute()) {
logger.fine("Ignoring unsupported Dispatch stack configuration (SCUFL2-130)");
logger.finest(original.getAbout());
ignoreConfig = true;
}
config.setType(type);
}
if (original.getName() != null)
config.setName(original.getName());
if (!ignoreConfig) {
mapBean(original.getAbout(), config);
if (original.getConfigure() != null) {
Configurable configurable = resolveBeanUri(original
.getConfigure().getResource(), Configurable.class);
config.setConfigures(configurable);
}
config.setParent(getParserState().getCurrent(
org.apache.taverna.scufl2.api.profiles.Profile.class));
}
getParserState().push(config);
if (original.getSeeAlso() != null) {
String about = original.getSeeAlso().getResource();
if (about != null) {
URI resource = resolve(about);
URI bundleBase = parserState .get().getLocation();
URI path = uriTools.relativePath(bundleBase, resource);
if (ignoreConfig) {
logger.finest("Deleting " + path + " (SCUFL2-130)");
parserState.get().getUcfPackage().removeResource(path.getRawPath());
} else {
try {
// TODO: Should the path in the UCF Package be %-escaped or not?
// See TestRDFXMLWriter.awkwardFilenames
config.setJson(parserState.get().getUcfPackage().getResourceAsString(path.getRawPath()));
} catch (IllegalArgumentException e) {
logger.log(Level.WARNING, "Could not parse JSON configuration " + path, e);
} catch (IOException e) {
logger.log(Level.WARNING, "Could not load JSON configuration " + path, e);
}
}
}
}
for (Object o : original.getAny()) {
// Legacy SCUFL2 <= 0.11.0 PropertyResource configuration
// Just ignoring it for now :(
//
// TODO: Parse and represent as JSON-LD?
logger.warning("Ignoring unsupported PropertyResource (from wfbundle 0.2.0 or older) for " + config + " " + o);
}
getParserState().pop();
}
protected void parseInputActivityPort(
org.apache.taverna.scufl2.rdfxml.jaxb.InputActivityPort original) {
InputActivityPort port = new InputActivityPort();
mapBean(original.getAbout(), port);
port.setParent(getParserState().getCurrent(Activity.class));
port.setName(original.getName());
if (original.getPortDepth() != null)
port.setDepth(original.getPortDepth().getValue());
}
protected void parseInputPortBinding(
org.apache.taverna.scufl2.rdfxml.jaxb.InputPortBinding original)
throws ReaderException {
ProcessorInputPortBinding binding = new ProcessorInputPortBinding();
mapBean(original.getAbout(), binding);
binding.setBoundActivityPort(resolveBeanUri(original
.getBindInputActivityPort().getResource(),
InputActivityPort.class));
binding.setBoundProcessorPort(resolveBeanUri(original
.getBindInputProcessorPort().getResource(),
InputProcessorPort.class));
binding.setParent(getParserState().getCurrent(ProcessorBinding.class));
}
protected void parseOutputActivityPort(
org.apache.taverna.scufl2.rdfxml.jaxb.OutputActivityPort original) {
OutputActivityPort port = new OutputActivityPort();
mapBean(original.getAbout(), port);
port.setParent(getParserState().getCurrent(Activity.class));
port.setName(original.getName());
if (original.getPortDepth() != null)
port.setDepth(original.getPortDepth().getValue());
if (original.getGranularPortDepth() != null)
port.setGranularDepth(original.getGranularPortDepth().getValue());
}
protected void parseOutputPortBinding(
org.apache.taverna.scufl2.rdfxml.jaxb.OutputPortBinding original)
throws ReaderException {
ProcessorOutputPortBinding binding = new ProcessorOutputPortBinding();
mapBean(original.getAbout(), binding);
binding.setBoundActivityPort(resolveBeanUri(original
.getBindOutputActivityPort().getResource(),
OutputActivityPort.class));
binding.setBoundProcessorPort(resolveBeanUri(original
.getBindOutputProcessorPort().getResource(),
OutputProcessorPort.class));
binding.setParent(getParserState().getCurrent(ProcessorBinding.class));
}
protected void parseProcessorBinding(
org.apache.taverna.scufl2.rdfxml.jaxb.ProcessorBinding original)
throws ReaderException {
org.apache.taverna.scufl2.api.profiles.ProcessorBinding binding = new org.apache.taverna.scufl2.api.profiles.ProcessorBinding();
binding.setParent(getParserState().getCurrent(
org.apache.taverna.scufl2.api.profiles.Profile.class));
mapBean(original.getAbout(), binding);
getParserState().push(binding);
if (original.getName() != null)
binding.setName(original.getName());
if (original.getActivityPosition() != null)
binding.setActivityPosition(original.getActivityPosition()
.getValue());
URI processorUri = resolve(original.getBindProcessor().getResource());
URI activityUri = resolve(original.getBindActivity().getResource());
binding.setBoundProcessor((Processor) resolveBeanUri(processorUri));
binding.setBoundActivity((Activity) resolveBeanUri(activityUri));
for (InputPortBinding inputPortBinding : original.getInputPortBinding())
parseInputPortBinding(inputPortBinding.getInputPortBinding());
for (OutputPortBinding outputPortBinding : original
.getOutputPortBinding())
parseOutputPortBinding(outputPortBinding.getOutputPortBinding());
getParserState().pop();
}
protected void parseProfile(Profile original, URI profileUri) {
org.apache.taverna.scufl2.api.profiles.Profile p = new org.apache.taverna.scufl2.api.profiles.Profile();
p.setParent(getParserState().getCurrent(WorkflowBundle.class));
getParserState().push(p);
if (original.getAbout() != null) {
URI about = getParserState().getCurrentBase().resolve(
original.getAbout());
mapBean(about, p);
} else
mapBean(profileUri, p);
if (original.getName() != null)
p.setName(original.getName());
// Note - we'll pop() in profileSecond() instead
}
protected void parseProfileSecond(Profile profileElem) {
// TODO: Parse activates config etc.
getParserState().pop();
}
protected void readProfile(URI profileUri, URI source)
throws ReaderException, IOException {
if (source.isAbsolute())
throw new ReaderException("Can't read external profile source "
+ source);
InputStream bundleStream = getParserState().getUcfPackage()
.getResourceAsInputStream(source.getRawPath());
if (bundleStream == null)
throw new ReaderException("Can't find profile " + source.getPath());
readProfile(profileUri, source, bundleStream);
}
@SuppressWarnings("unchecked")
protected void readProfile(URI profileUri, URI source,
InputStream bundleStream) throws ReaderException, IOException {
JAXBElement<ProfileDocument> elem;
try {
elem = (JAXBElement<ProfileDocument>) unmarshaller
.unmarshal(bundleStream);
} catch (JAXBException e) {
throw new ReaderException("Can't parse profile document " + source,
e);
}
URI base = getParserState().getLocation().resolve(source);
if (elem.getValue().getBase() != null)
base = base.resolve(elem.getValue().getBase());
getParserState().setCurrentBase(base);
org.apache.taverna.scufl2.rdfxml.jaxb.Profile profileElem = null;
for (Object any : elem.getValue().getAny())
if (any instanceof org.apache.taverna.scufl2.rdfxml.jaxb.Profile) {
if (profileElem != null)
throw new ReaderException("More than one <Profile> found");
profileElem = (org.apache.taverna.scufl2.rdfxml.jaxb.Profile) any;
parseProfile(profileElem, profileUri);
} else if (any instanceof org.apache.taverna.scufl2.rdfxml.jaxb.Activity) {
if (profileElem == null)
throw new ReaderException("No <Profile> found");
parseActivity((org.apache.taverna.scufl2.rdfxml.jaxb.Activity) any);
} else if (any instanceof org.apache.taverna.scufl2.rdfxml.jaxb.ProcessorBinding) {
if (profileElem == null)
throw new ReaderException("No <Profile> found");
parseProcessorBinding((org.apache.taverna.scufl2.rdfxml.jaxb.ProcessorBinding) any);
} else if (any instanceof org.apache.taverna.scufl2.rdfxml.jaxb.Configuration) {
if (profileElem == null)
throw new ReaderException("No <Profile> found");
parseConfiguration((org.apache.taverna.scufl2.rdfxml.jaxb.Configuration) any);
}
parseProfileSecond(profileElem);
}
}
| |
/*
* 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.struts2.jasper.compiler;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.struts2.el.ExpressionFactoryImpl;
import org.apache.struts2.jasper.Constants;
import org.apache.struts2.jasper.JasperException;
import org.apache.struts2.jasper.JspCompilationContext;
import org.apache.struts2.jasper.el.ExpressionEvaluatorImpl;
import org.xml.sax.Attributes;
import javax.el.FunctionMapper;
import javax.servlet.jsp.el.ExpressionEvaluator;
import java.io.*;
import java.util.Vector;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
/**
* This class has all the utility method(s).
* Ideally should move all the bean containers here.
*
* @author Mandar Raje.
* @author Rajiv Mordani.
* @author Danno Ferrin
* @author Pierre Delisle
* @author Shawn Bayern
* @author Mark Roth
*/
public class JspUtil {
private static final String WEB_INF_TAGS = "/WEB-INF/tags/";
private static final String META_INF_TAGS = "/META-INF/tags/";
// Delimiters for request-time expressions (JSP and XML syntax)
private static final String OPEN_EXPR = "<%=";
private static final String CLOSE_EXPR = "%>";
private static final String OPEN_EXPR_XML = "%=";
private static final String CLOSE_EXPR_XML = "%";
private static int tempSequenceNumber = 0;
//private static ExpressionEvaluatorImpl expressionEvaluator
//= new ExpressionEvaluatorImpl();
//tc6
private final static ExpressionEvaluator expressionEvaluator =
new ExpressionEvaluatorImpl(new ExpressionFactoryImpl());
private static final String javaKeywords[] = {
"abstract", "assert", "boolean", "break", "byte", "case",
"catch", "char", "class", "const", "continue",
"default", "do", "double", "else", "enum", "extends",
"final", "finally", "float", "for", "goto",
"if", "implements", "import", "instanceof", "int",
"interface", "long", "native", "new", "package",
"private", "protected", "public", "return", "short",
"static", "strictfp", "super", "switch", "synchronized",
"this", "throws", "transient", "try", "void",
"volatile", "while"};
public static final int CHUNKSIZE = 1024;
public static char[] removeQuotes(char[] chars) {
CharArrayWriter caw = new CharArrayWriter();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '%' && chars[i + 1] == '\\' &&
chars[i + 2] == '>') {
caw.write('%');
caw.write('>');
i = i + 2;
} else {
caw.write(chars[i]);
}
}
return caw.toCharArray();
}
public static char[] escapeQuotes(char[] chars) {
// Prescan to convert %\> to %>
String s = new String(chars);
while (true) {
int n = s.indexOf("%\\>");
if (n < 0)
break;
StringBuffer sb = new StringBuffer(s.substring(0, n));
sb.append("%>");
sb.append(s.substring(n + 3));
s = sb.toString();
}
chars = s.toCharArray();
return (chars);
// Escape all backslashes not inside a Java string literal
/*
CharArrayWriter caw = new CharArrayWriter();
boolean inJavaString = false;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '"') inJavaString = !inJavaString;
// escape out the escape character
if (!inJavaString && (chars[i] == '\\')) caw.write('\\');
caw.write(chars[i]);
}
return caw.toCharArray();
*/
}
/**
* Checks if the token is a runtime expression.
* In standard JSP syntax, a runtime expression starts with '<%' and
* ends with '%>'. When the JSP document is in XML syntax, a runtime
* expression starts with '%=' and ends with '%'.
*
* @param token The token to be checked
* @param isXml is xml syntax
* @return whether the token is a runtime expression or not.
*/
public static boolean isExpression(String token, boolean isXml) {
String openExpr;
String closeExpr;
if (isXml) {
openExpr = OPEN_EXPR_XML;
closeExpr = CLOSE_EXPR_XML;
} else {
openExpr = OPEN_EXPR;
closeExpr = CLOSE_EXPR;
}
if (token.startsWith(openExpr) && token.endsWith(closeExpr)) {
return true;
} else {
return false;
}
}
/**
* @param expression expression string
* @param isXml is xml
* @return the "expression" part of a runtime expression,
* taking the delimiters out.
*/
public static String getExpr(String expression, boolean isXml) {
String returnString;
String openExpr;
String closeExpr;
if (isXml) {
openExpr = OPEN_EXPR_XML;
closeExpr = CLOSE_EXPR_XML;
} else {
openExpr = OPEN_EXPR;
closeExpr = CLOSE_EXPR;
}
int length = expression.length();
if (expression.startsWith(openExpr) &&
expression.endsWith(closeExpr)) {
returnString = expression.substring(
openExpr.length(), length - closeExpr.length());
} else {
returnString = "";
}
return returnString;
}
/**
* Takes a potential expression and converts it into XML form
*
* @param expression expression string
* @return expressions as xml
*/
public static String getExprInXml(String expression) {
String returnString;
int length = expression.length();
if (expression.startsWith(OPEN_EXPR)
&& expression.endsWith(CLOSE_EXPR)) {
returnString = expression.substring(1, length - 1);
} else {
returnString = expression;
}
return escapeXml(returnString.replace(Constants.ESC, '$'));
}
/**
* Checks to see if the given scope is valid.
*
* @param scope The scope to be checked
* @param n The Node containing the 'scope' attribute whose value is to be
* checked
* @param err error dispatcher
* @throws JasperException if scope is not null and different from
* "page", "request", "session", and
* "application"
*/
public static void checkScope(String scope, Node n, ErrorDispatcher err)
throws JasperException {
if (scope != null && !scope.equals("page") && !scope.equals("request")
&& !scope.equals("session") && !scope.equals("application")) {
err.jspError(n, "jsp.error.invalid.scope", scope);
}
}
/**
* Checks if all mandatory attributes are present and if all attributes
* present have valid names. Checks attributes specified as XML-style
* attributes as well as attributes specified using the jsp:attribute
* standard action.
*
* @param typeOfTag type of tag
* @param n node
* @param validAttributes valid attributes
* @param err error dispatcher
* @throws JasperException in case of Jasper errors
*/
public static void checkAttributes(String typeOfTag,
Node n,
ValidAttribute[] validAttributes,
ErrorDispatcher err)
throws JasperException {
Attributes attrs = n.getAttributes();
Mark start = n.getStart();
boolean valid = true;
// AttributesImpl.removeAttribute is broken, so we do this...
int tempLength = (attrs == null) ? 0 : attrs.getLength();
Vector temp = new Vector(tempLength, 1);
for (int i = 0; i < tempLength; i++) {
String qName = attrs.getQName(i);
if ((!qName.equals("xmlns")) && (!qName.startsWith("xmlns:")))
temp.addElement(qName);
}
// Add names of attributes specified using jsp:attribute
Node.Nodes tagBody = n.getBody();
if (tagBody != null) {
int numSubElements = tagBody.size();
for (int i = 0; i < numSubElements; i++) {
Node node = tagBody.getNode(i);
if (node instanceof Node.NamedAttribute) {
String attrName = node.getAttributeValue("name");
temp.addElement(attrName);
// Check if this value appear in the attribute of the node
if (n.getAttributeValue(attrName) != null) {
err.jspError(n, "jsp.error.duplicate.name.jspattribute",
attrName);
}
} else {
// Nothing can come before jsp:attribute, and only
// jsp:body can come after it.
break;
}
}
}
/*
* First check to see if all the mandatory attributes are present.
* If so only then proceed to see if the other attributes are valid
* for the particular tag.
*/
String missingAttribute = null;
for (ValidAttribute validAttribute : validAttributes) {
int attrPos;
if (validAttribute.mandatory) {
attrPos = temp.indexOf(validAttribute.name);
if (attrPos != -1) {
temp.remove(attrPos);
valid = true;
} else {
valid = false;
missingAttribute = validAttribute.name;
break;
}
}
}
// If mandatory attribute is missing then the exception is thrown
if (!valid)
err.jspError(start, "jsp.error.mandatory.attribute", typeOfTag,
missingAttribute);
// Check to see if there are any more attributes for the specified tag.
int attrLeftLength = temp.size();
if (attrLeftLength == 0)
return;
// Now check to see if the rest of the attributes are valid too.
String attribute = null;
for (int j = 0; j < attrLeftLength; j++) {
valid = false;
attribute = (String) temp.elementAt(j);
for (ValidAttribute validAttribute : validAttributes) {
if (attribute.equals(validAttribute.name)) {
valid = true;
break;
}
}
if (!valid)
err.jspError(start, "jsp.error.invalid.attribute", typeOfTag,
attribute);
}
// XXX *could* move EL-syntax validation here... (sb)
}
public static String escapeQueryString(String unescString) {
if (unescString == null)
return null;
String escString = "";
String shellSpChars = "\\\"";
for (int index = 0; index < unescString.length(); index++) {
char nextChar = unescString.charAt(index);
if (shellSpChars.indexOf(nextChar) != -1)
escString += "\\";
escString += nextChar;
}
return escString;
}
/**
* Escape the 5 entities defined by XML.
*
* @param s xml string to escape
* @return escaped xml string
*/
public static String escapeXml(String s) {
if (s == null) return null;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '<') {
sb.append("<");
} else if (c == '>') {
sb.append(">");
} else if (c == '\'') {
sb.append("'");
} else if (c == '&') {
sb.append("&");
} else if (c == '"') {
sb.append(""");
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* Replaces any occurrences of the character <tt>replace</tt> with the
* string <tt>with</tt>.
*
* @param name string
* @param replace char to replace
* @param with replace with
*
* @return replaced string
*/
public static String replace(String name, char replace, String with) {
StringBuilder buf = new StringBuilder();
int begin = 0;
int end;
int last = name.length();
while (true) {
end = name.indexOf(replace, begin);
if (end < 0) {
end = last;
}
buf.append(name.substring(begin, end));
if (end == last) {
break;
}
buf.append(with);
begin = end + 1;
}
return buf.toString();
}
public static class ValidAttribute {
String name;
boolean mandatory;
boolean rtexprvalue; // not used now
public ValidAttribute(String name, boolean mandatory,
boolean rtexprvalue) {
this.name = name;
this.mandatory = mandatory;
this.rtexprvalue = rtexprvalue;
}
public ValidAttribute(String name, boolean mandatory) {
this(name, mandatory, false);
}
public ValidAttribute(String name) {
this(name, false);
}
}
/**
* Convert a String value to 'boolean'.
* Besides the standard conversions done by
* Boolean.valueOf(s).booleanValue(), the value "yes"
* (ignore case) is also converted to 'true'.
* If 's' is null, then 'false' is returned.
*
* @param s the string to be converted
* @return the boolean value associated with the string s
*/
public static boolean booleanValue(String s) {
return BooleanUtils.toBoolean(s);
}
/**
* <p> The <tt>Class</tt> object is determined by passing the given string
* name to the <tt>Class.forName()</tt> method, unless the given string
* name represents a primitive type, in which case it is converted to a
* <tt>Class</tt> object by appending ".class" to it (e.g., "int.class").
*
* @param type type
* @param loader class loader
*
* @return the <tt>Class</tt> object associated with the class or
* interface with the given string name.
*
* @throws ClassNotFoundException if call was not found
*/
public static Class toClass(String type, ClassLoader loader)
throws ClassNotFoundException {
Class c = null;
int i0 = type.indexOf('[');
int dims = 0;
if (i0 > 0) {
// This is an array. Count the dimensions
for (int i = 0; i < type.length(); i++) {
if (type.charAt(i) == '[')
dims++;
}
type = type.substring(0, i0);
}
if ("boolean".equals(type))
c = boolean.class;
else if ("char".equals(type))
c = char.class;
else if ("byte".equals(type))
c = byte.class;
else if ("short".equals(type))
c = short.class;
else if ("int".equals(type))
c = int.class;
else if ("long".equals(type))
c = long.class;
else if ("float".equals(type))
c = float.class;
else if ("double".equals(type))
c = double.class;
else if (type.indexOf('[') < 0)
c = loader.loadClass(type);
if (dims == 0)
return c;
if (dims == 1)
return java.lang.reflect.Array.newInstance(c, 1).getClass();
// Array of more than i dimension
return java.lang.reflect.Array.newInstance(c, new int[dims]).getClass();
}
/**
* Produces a String representing a call to the EL interpreter.
*
* @param isTagFile is a tag file
* @param expression a String containing zero or more "${}" expressions
* @param expectedType the expected type of the interpreted result
* @param fnmapvar Variable pointing to a function map.
* @param XmlEscape True if the result should do XML escaping
* @return a String representing a call to the EL interpreter.
*/
public static String interpreterCall(boolean isTagFile,
String expression,
Class expectedType,
String fnmapvar,
boolean XmlEscape) {
/*
* Determine which context object to use.
*/
String jspCtxt = null;
if (isTagFile)
jspCtxt = "this.getJspContext()";
else
jspCtxt = "_jspx_page_context";
/*
* Determine whether to use the expected type's textual name
* or, if it's a primitive, the name of its correspondent boxed
* type.
*/
String targetType = expectedType.getName();
String primitiveConverterMethod = null;
if (expectedType.isPrimitive()) {
if (expectedType.equals(Boolean.TYPE)) {
targetType = Boolean.class.getName();
primitiveConverterMethod = "booleanValue";
} else if (expectedType.equals(Byte.TYPE)) {
targetType = Byte.class.getName();
primitiveConverterMethod = "byteValue";
} else if (expectedType.equals(Character.TYPE)) {
targetType = Character.class.getName();
primitiveConverterMethod = "charValue";
} else if (expectedType.equals(Short.TYPE)) {
targetType = Short.class.getName();
primitiveConverterMethod = "shortValue";
} else if (expectedType.equals(Integer.TYPE)) {
targetType = Integer.class.getName();
primitiveConverterMethod = "intValue";
} else if (expectedType.equals(Long.TYPE)) {
targetType = Long.class.getName();
primitiveConverterMethod = "longValue";
} else if (expectedType.equals(Float.TYPE)) {
targetType = Float.class.getName();
primitiveConverterMethod = "floatValue";
} else if (expectedType.equals(Double.TYPE)) {
targetType = Double.class.getName();
primitiveConverterMethod = "doubleValue";
}
}
if (primitiveConverterMethod != null) {
XmlEscape = false;
}
/*
* Build up the base call to the interpreter.
*/
// XXX - We use a proprietary call to the interpreter for now
// as the current standard machinery is inefficient and requires
// lots of wrappers and adapters. This should all clear up once
// the EL interpreter moves out of JSTL and into its own project.
// In the future, this should be replaced by code that calls
// ExpressionEvaluator.parseExpression() and then cache the resulting
// expression objects. The interpreterCall would simply select
// one of the pre-cached expressions and evaluate it.
// Note that PageContextImpl implements VariableResolver and
// the generated Servlet/SimpleTag implements FunctionMapper, so
// that machinery is already in place (mroth).
targetType = toJavaSourceType(targetType);
StringBuilder call = new StringBuilder(
"(" + targetType + ") "
+ "org.apache.struts2.jasper.runtime.PageContextImpl.proprietaryEvaluate"
+ "(" + Generator.quote(expression) + ", "
+ targetType + ".class, "
+ "(PageContext)" + jspCtxt
+ ", " + fnmapvar
+ ", " + XmlEscape
+ ")");
/*
* Add the primitive converter method if we need to.
*/
if (primitiveConverterMethod != null) {
call.insert(0, "(");
call.append(")." + primitiveConverterMethod + "()");
}
return call.toString();
}
/**
* Validates the syntax of all ${} expressions within the given string.
*
* @param where the approximate location of the expressions in the JSP page
* @param expressions a string containing zero or more "${}" expressions
* @param expectedType expected class type
* @param functionMapper function mapper
* @param err an error dispatcher to use
* @throws JasperException in case of Jasper errors
* @deprecated now delegated to the org.apache.el Package
*/
public static void validateExpressions(Mark where,
String expressions,
Class expectedType,
FunctionMapper functionMapper,
ErrorDispatcher err)
throws JasperException {
}
/**
* Resets the temporary variable name.
* (not thread-safe)
*
* @deprecated
*/
public static void resetTemporaryVariableName() {
tempSequenceNumber = 0;
}
/**
* @return Generates a new temporary variable name.
* (not thread-safe)
* @deprecated
*/
public static String nextTemporaryVariableName() {
return Constants.TEMP_VARIABLE_NAME_PREFIX + (tempSequenceNumber++);
}
public static String coerceToPrimitiveBoolean(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerceToBoolean(" + s + ")";
} else {
if (s == null || s.length() == 0)
return "false";
else
return Boolean.valueOf(s).toString();
}
}
public static String coerceToBoolean(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(Boolean) org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Boolean.class)";
} else {
if (s == null || s.length() == 0) {
return "new Boolean(false)";
} else {
// Detect format error at translation time
return "new Boolean(" + Boolean.valueOf(s).toString() + ")";
}
}
}
public static String coerceToPrimitiveByte(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerceToByte(" + s + ")";
} else {
if (s == null || s.length() == 0)
return "(byte) 0";
else
return "((byte)" + Byte.valueOf(s).toString() + ")";
}
}
public static String coerceToByte(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(Byte) org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Byte.class)";
} else {
if (s == null || s.length() == 0) {
return "new Byte((byte) 0)";
} else {
// Detect format error at translation time
return "new Byte((byte)" + Byte.valueOf(s).toString() + ")";
}
}
}
public static String coerceToChar(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerceToChar(" + s + ")";
} else {
if (s == null || s.length() == 0) {
return "(char) 0";
} else {
char ch = s.charAt(0);
// this trick avoids escaping issues
return "((char) " + (int) ch + ")";
}
}
}
public static String coerceToCharacter(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(Character) org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Character.class)";
} else {
if (s == null || s.length() == 0) {
return "new Character((char) 0)";
} else {
char ch = s.charAt(0);
// this trick avoids escaping issues
return "new Character((char) " + (int) ch + ")";
}
}
}
public static String coerceToPrimitiveDouble(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerceToDouble(" + s + ")";
} else {
if (s == null || s.length() == 0)
return "(double) 0";
else
return Double.valueOf(s).toString();
}
}
public static String coerceToDouble(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(Double) org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Double.class)";
} else {
if (s == null || s.length() == 0) {
return "new Double(0)";
} else {
// Detect format error at translation time
return "new Double(" + Double.valueOf(s).toString() + ")";
}
}
}
public static String coerceToPrimitiveFloat(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerceToFloat(" + s + ")";
} else {
if (s == null || s.length() == 0)
return "(float) 0";
else
return Float.valueOf(s).toString() + "f";
}
}
public static String coerceToFloat(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(Float) org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Float.class)";
} else {
if (s == null || s.length() == 0) {
return "new Float(0)";
} else {
// Detect format error at translation time
return "new Float(" + Float.valueOf(s).toString() + "f)";
}
}
}
public static String coerceToInt(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerceToInt(" + s + ")";
} else {
if (s == null || s.length() == 0)
return "0";
else
return Integer.valueOf(s).toString();
}
}
public static String coerceToInteger(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(Integer) org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Integer.class)";
} else {
if (s == null || s.length() == 0) {
return "new Integer(0)";
} else {
// Detect format error at translation time
return "new Integer(" + Integer.valueOf(s).toString() + ")";
}
}
}
public static String coerceToPrimitiveShort(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerceToShort(" + s + ")";
} else {
if (s == null || s.length() == 0)
return "(short) 0";
else
return "((short) " + Short.valueOf(s).toString() + ")";
}
}
public static String coerceToShort(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(Short) org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Short.class)";
} else {
if (s == null || s.length() == 0) {
return "new Short((short) 0)";
} else {
// Detect format error at translation time
return "new Short(\"" + Short.valueOf(s).toString() + "\")";
}
}
}
public static String coerceToPrimitiveLong(String s,
boolean isNamedAttribute) {
if (isNamedAttribute) {
return "org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerceToLong(" + s + ")";
} else {
if (s == null || s.length() == 0)
return "(long) 0";
else
return Long.valueOf(s).toString() + "l";
}
}
public static String coerceToLong(String s, boolean isNamedAttribute) {
if (isNamedAttribute) {
return "(Long) org.apache.struts2.jasper.runtime.JspRuntimeLibrary.coerce(" + s + ", Long.class)";
} else {
if (s == null || s.length() == 0) {
return "new Long(0)";
} else {
// Detect format error at translation time
return "new Long(" + Long.valueOf(s).toString() + "l)";
}
}
}
public static InputStream getInputStream(String fname, JarFile jarFile,
JspCompilationContext ctxt,
ErrorDispatcher err)
throws JasperException, IOException {
InputStream in = null;
if (jarFile != null) {
String jarEntryName = fname.substring(1, fname.length());
ZipEntry jarEntry = jarFile.getEntry(jarEntryName);
if (jarEntry == null) {
err.jspError("jsp.error.file.not.found", fname);
}
in = jarFile.getInputStream(jarEntry);
} else {
in = ctxt.getResourceAsStream(fname);
}
if (in == null) {
err.jspError("jsp.error.file.not.found", fname);
}
return in;
}
/**
* Gets the fully-qualified class name of the tag handler corresponding to
* the given tag file path.
*
* @param path Tag file path
* @param err Error dispatcher
* @return Fully-qualified class name of the tag handler corresponding to
* the given tag file path
* @throws JasperException in case of Jasper errors
* @deprecated Use {@link #getTagHandlerClassName(String, String, ErrorDispatcher)}
* See https://issues.apache.org/bugzilla/show_bug.cgi?id=46471
*/
public static String getTagHandlerClassName(String path,
ErrorDispatcher err)
throws JasperException {
return getTagHandlerClassName(path, null, err);
}
/**
* Gets the fully-qualified class name of the tag handler corresponding to
* the given tag file path.
*
* @param path Tag file path
* @param urn urn
* @param err Error dispatcher
* @return Fully-qualified class name of the tag handler corresponding to
* the given tag file path
* @throws JasperException in case of Jasper errors
*/
public static String getTagHandlerClassName(String path, String urn,
ErrorDispatcher err) throws JasperException {
String className = null;
int begin = 0;
int index;
index = path.lastIndexOf(".tag");
if (index == -1) {
err.jspError("jsp.error.tagfile.badSuffix", path);
}
//It's tempting to remove the ".tag" suffix here, but we can't.
//If we remove it, the fully-qualified class name of this tag
//could conflict with the package name of other tags.
//For instance, the tag file
// /WEB-INF/tags/foo.tag
//would have fully-qualified class name
// org.apache.jsp.tag.web.foo
//which would conflict with the package name of the tag file
// /WEB-INF/tags/foo/bar.tag
index = path.indexOf(WEB_INF_TAGS);
if (index != -1) {
className = "org.apache.jsp.tag.web.";
begin = index + WEB_INF_TAGS.length();
} else {
index = path.indexOf(META_INF_TAGS);
if (index != -1) {
className = getClassNameBase(urn);
begin = index + META_INF_TAGS.length();
} else {
err.jspError("jsp.error.tagfile.illegalPath", path);
}
}
className += makeJavaPackage(path.substring(begin));
return className;
}
private static String getClassNameBase(String urn) {
StringBuffer base = new StringBuffer("org.apache.jsp.tag.meta.");
if (urn != null) {
base.append(makeJavaPackage(urn));
base.append('.');
}
return base.toString();
}
/**
* Converts the given path to a Java package or fully-qualified class name
*
* @param path Path to convert
* @return Java package corresponding to the given path
*/
public static final String makeJavaPackage(String path) {
String classNameComponents[] = split(path, "/");
StringBuffer legalClassNames = new StringBuffer();
for (int i = 0; i < classNameComponents.length; i++) {
legalClassNames.append(makeJavaIdentifier(classNameComponents[i]));
if (i < classNameComponents.length - 1) {
legalClassNames.append('.');
}
}
return legalClassNames.toString();
}
/**
* Splits a string into it's components.
*
* @param path String to split
* @param pat Pattern to split at
* @return the components of the path
*/
private static final String[] split(String path, String pat) {
Vector comps = new Vector();
int pos = path.indexOf(pat);
int start = 0;
while (pos >= 0) {
if (pos > start) {
String comp = path.substring(start, pos);
comps.add(comp);
}
start = pos + pat.length();
pos = path.indexOf(pat, start);
}
if (start < path.length()) {
comps.add(path.substring(start));
}
String[] result = new String[comps.size()];
for (int i = 0; i < comps.size(); i++) {
result[i] = (String) comps.elementAt(i);
}
return result;
}
/**
* Converts the given identifier to a legal Java identifier
*
* @param identifier Identifier to convert
* @return Legal Java identifier corresponding to the given identifier
*/
public static final String makeJavaIdentifier(String identifier) {
StringBuffer modifiedIdentifier =
new StringBuffer(identifier.length());
if (!Character.isJavaIdentifierStart(identifier.charAt(0))) {
modifiedIdentifier.append('_');
}
for (int i = 0; i < identifier.length(); i++) {
char ch = identifier.charAt(i);
if (Character.isJavaIdentifierPart(ch) && ch != '_') {
modifiedIdentifier.append(ch);
} else if (ch == '.') {
modifiedIdentifier.append('_');
} else {
modifiedIdentifier.append(mangleChar(ch));
}
}
if (isJavaKeyword(modifiedIdentifier.toString())) {
modifiedIdentifier.append('_');
}
return modifiedIdentifier.toString();
}
/**
* Mangle the specified character to create a legal Java class name.
* @param ch character
* @return new string
*/
public static final String mangleChar(char ch) {
char[] result = new char[5];
result[0] = '_';
result[1] = Character.forDigit((ch >> 12) & 0xf, 16);
result[2] = Character.forDigit((ch >> 8) & 0xf, 16);
result[3] = Character.forDigit((ch >> 4) & 0xf, 16);
result[4] = Character.forDigit(ch & 0xf, 16);
return new String(result);
}
/**
* @param key string to check
*
* @return Test whether the argument is a Java keyword
*/
public static boolean isJavaKeyword(String key) {
int i = 0;
int j = javaKeywords.length;
while (i < j) {
int k = (i + j) / 2;
int result = javaKeywords[k].compareTo(key);
if (result == 0) {
return true;
}
if (result < 0) {
i = k + 1;
} else {
j = k;
}
}
return false;
}
/**
* Converts the given Xml name to a legal Java identifier. This is
* slightly more efficient than makeJavaIdentifier in that we only need
* to worry about '.', '-', and ':' in the string. We also assume that
* the resultant string is further concatenated with some prefix string
* so that we don't have to worry about it being a Java key word.
*
* @param name Identifier to convert
* @return Legal Java identifier corresponding to the given identifier
*/
public static final String makeXmlJavaIdentifier(String name) {
if (name.indexOf('-') >= 0)
name = replace(name, '-', "$1");
if (name.indexOf('.') >= 0)
name = replace(name, '.', "$2");
if (name.indexOf(':') >= 0)
name = replace(name, ':', "$3");
return name;
}
static InputStreamReader getReader(String fname, String encoding,
JarFile jarFile,
JspCompilationContext ctxt,
ErrorDispatcher err)
throws JasperException, IOException {
return getReader(fname, encoding, jarFile, ctxt, err, 0);
}
static InputStreamReader getReader(String fname, String encoding,
JarFile jarFile,
JspCompilationContext ctxt,
ErrorDispatcher err, int skip)
throws JasperException, IOException {
InputStreamReader reader = null;
InputStream in = getInputStream(fname, jarFile, ctxt, err);
for (int i = 0; i < skip; i++) {
in.read();
}
try {
reader = new InputStreamReader(in, encoding);
} catch (UnsupportedEncodingException ex) {
err.jspError("jsp.error.unsupported.encoding", encoding);
}
return reader;
}
/**
* Handles taking input from TLDs
* 'java.lang.Object' -> 'java.lang.Object.class'
* 'int' -> 'int.class'
* 'void' -> 'Void.TYPE'
* 'int[]' -> 'int[].class'
*
* @param type java source type
* @return type
*/
public static String toJavaSourceTypeFromTld(String type) {
if (type == null || "void".equals(type)) {
return "Void.TYPE";
}
return type + ".class";
}
/**
* Class.getName() return arrays in the form "[[[<et>", where et,
* the element type can be one of ZBCDFIJS or L<classname>;
* It is converted into forms that can be understood by javac.
*
* @param type source type
* @return java source type
*/
public static String toJavaSourceType(String type) {
if (type.charAt(0) != '[') {
return type;
}
int dims = 1;
String t = null;
for (int i = 1; i < type.length(); i++) {
if (type.charAt(i) == '[') {
dims++;
} else {
switch (type.charAt(i)) {
case 'Z':
t = "boolean";
break;
case 'B':
t = "byte";
break;
case 'C':
t = "char";
break;
case 'D':
t = "double";
break;
case 'F':
t = "float";
break;
case 'I':
t = "int";
break;
case 'J':
t = "long";
break;
case 'S':
t = "short";
break;
case 'L':
t = type.substring(i + 1, type.indexOf(';'));
break;
}
break;
}
}
StringBuilder resultType = new StringBuilder(t);
for (; dims > 0; dims--) {
resultType.append("[]");
}
return resultType.toString();
}
/**
* Compute the canonical name from a Class instance. Note that a
* simple replacement of '$' with '.' of a binary name would not work,
* as '$' is a legal Java Identifier character.
*
* @param c A instance of java.lang.Class
* @return The canonical name of c.
*/
public static String getCanonicalName(Class c) {
String binaryName = c.getName();
c = c.getDeclaringClass();
if (c == null) {
return binaryName;
}
StringBuilder buf = new StringBuilder(binaryName);
do {
buf.setCharAt(c.getName().length(), '.');
c = c.getDeclaringClass();
} while (c != null);
return buf.toString();
}
}
| |
package com.hazelcast.simulator;
import com.hazelcast.simulator.common.AgentsFile;
import com.hazelcast.simulator.utils.FileUtils;
import com.hazelcast.simulator.utils.TestUtils;
import com.hazelcast.simulator.utils.UncheckedIOException;
import com.hazelcast.simulator.utils.helper.ExitExceptionSecurityManager;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
import static com.hazelcast.simulator.utils.FileUtils.USER_HOME;
import static com.hazelcast.simulator.utils.FileUtils.appendText;
import static com.hazelcast.simulator.utils.FileUtils.deleteQuiet;
import static com.hazelcast.simulator.utils.FileUtils.ensureExistingFile;
import static com.hazelcast.simulator.utils.FileUtils.getUserDir;
import static com.hazelcast.simulator.utils.FileUtils.newFile;
public class TestEnvironmentUtils {
private static final Logger LOGGER = Logger.getLogger(TestEnvironmentUtils.class);
private static final Logger ROOT_LOGGER = Logger.getRootLogger();
private static final AtomicReference<Level> LOGGER_LEVEL = new AtomicReference<Level>();
private static SecurityManager originalSecurityManager;
private static String originalSimulatorHome;
private static File agentsFile;
private static File cloudIdentity;
private static File cloudCredential;
private static File publicKeyFile;
private static File privateKeyFile;
private static boolean deleteCloudIdentity;
private static boolean deleteCloudCredential;
private static boolean deletePublicKey;
private static boolean deletePrivateKey;
public static File setupFakeEnvironment() {
File dist = internalDistDirectory();
File simulatorHome = TestUtils.createTmpDirectory();
try {
copyDirectory(dist, simulatorHome);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
System.setProperty("user.dir.test", simulatorHome.getAbsolutePath());
LOGGER.info("Fake SIMULATOR_HOME:" + simulatorHome.getAbsolutePath());
originalSimulatorHome = System.getProperty("SIMULATOR_HOME");
System.setProperty("SIMULATOR_HOME", simulatorHome.getAbsolutePath());
System.setProperty("DRIVER","fake");
return simulatorHome;
}
private static void copyDirectory(File source, File destination) throws IOException {
if (source.isDirectory()) {
if (!destination.exists()) {
destination.mkdirs();
}
String fileNames[] = source.list();
for (String fileName : fileNames) {
File srcFile = new File(source, fileName);
File destFile = new File(destination, fileName);
copyDirectory(srcFile, destFile);
}
} else {
FileUtils.copy(source,destination);
if (source.canExecute()) {
destination.setExecutable(true);
}
}
}
public static File setupFakeUserDir() {
File dir = TestUtils.createTmpDirectory();
System.setProperty("user.dir.test", dir.getAbsolutePath());
return dir;
}
public static void teardownFakeUserDir() {
System.clearProperty("user.dir.test");
}
public static void tearDownFakeEnvironment() {
if (originalSimulatorHome == null) {
System.clearProperty("SIMULATOR_HOME");
} else {
System.setProperty("SIMULATOR_HOME", originalSimulatorHome);
}
System.clearProperty("user.dir.test");
}
public static void setLogLevel(Level level) {
if (LOGGER_LEVEL.compareAndSet(null, ROOT_LOGGER.getLevel())) {
ROOT_LOGGER.setLevel(level);
}
}
public static void resetLogLevel() {
Level level = LOGGER_LEVEL.get();
if (level != null && LOGGER_LEVEL.compareAndSet(level, null)) {
ROOT_LOGGER.setLevel(level);
}
}
public static void setExitExceptionSecurityManager() {
originalSecurityManager = System.getSecurityManager();
System.setSecurityManager(new ExitExceptionSecurityManager());
}
public static void setExitExceptionSecurityManagerWithStatusZero() {
originalSecurityManager = System.getSecurityManager();
System.setSecurityManager(new ExitExceptionSecurityManager(true));
}
public static void resetSecurityManager() {
System.setSecurityManager(originalSecurityManager);
}
public static File internalDistDirectory() {
File localResourceDir = localResourceDirectory();
File projectRoot = localResourceDir.getParentFile().getParentFile().getParentFile();
return new File(projectRoot, "dist/src/main/dist");
}
public static String internalDistPath() {
return internalDistDirectory().getAbsolutePath();
}
public static File localResourceDirectory() {
ClassLoader classLoader = TestEnvironmentUtils.class.getClassLoader();
File f = new File(classLoader.getResource("hazelcast.xml").getFile());
return f.getParentFile().getAbsoluteFile();
}
public static void createAgentsFileWithLocalhost() {
agentsFile = new File(getUserDir(), AgentsFile.NAME);
appendText("127.0.0.1", agentsFile);
}
public static void deleteAgentsFile() {
deleteQuiet(agentsFile);
}
public static void createCloudCredentialFiles() {
String userHome = USER_HOME;
cloudIdentity = new File(userHome, "ec2.identity").getAbsoluteFile();
cloudCredential = new File(userHome, "ec2.credential").getAbsoluteFile();
if (!cloudIdentity.exists()) {
deleteCloudIdentity = true;
ensureExistingFile(cloudIdentity);
}
if (!cloudCredential.exists()) {
deleteCloudCredential = true;
ensureExistingFile(cloudCredential);
}
}
public static void deleteCloudCredentialFiles() {
if (deleteCloudIdentity) {
deleteQuiet(cloudIdentity);
}
if (deleteCloudCredential) {
deleteQuiet(cloudCredential);
}
}
public static void createPublicPrivateKeyFiles() {
publicKeyFile = newFile("~", ".ssh", "id_rsa.pub");
privateKeyFile = newFile("~", ".ssh", "id_rsa");
if (!publicKeyFile.exists()) {
deletePublicKey = true;
ensureExistingFile(publicKeyFile);
}
if (!privateKeyFile.exists()) {
deletePrivateKey = true;
ensureExistingFile(privateKeyFile);
}
}
public static void deletePublicPrivateKeyFiles() {
if (deletePublicKey) {
deleteQuiet(publicKeyFile);
}
if (deletePrivateKey) {
deleteQuiet(privateKeyFile);
}
}
public static File getPublicKeyFile() {
return publicKeyFile;
}
public static File getPrivateKeyFile() {
return privateKeyFile;
}
}
| |
package com.atlassian.plugin.webresource;
import static java.util.Arrays.asList;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.atlassian.plugin.ModuleDescriptor;
import com.atlassian.plugin.Plugin;
import com.atlassian.plugin.PluginAccessor;
import com.atlassian.plugin.elements.ResourceDescriptor;
import org.dom4j.DocumentException;
import com.google.common.base.Supplier;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import junit.framework.TestCase;
public class TestWebResourceManagerImpl extends TestCase
{
private WebResourceIntegration mockWebResourceIntegration = mock(WebResourceIntegration.class);
private PluginAccessor mockPluginAccessor = mock(PluginAccessor.class);
private final WebResourceUrlProvider mockUrlProvider = mock(WebResourceUrlProvider.class);
private ResourceBatchingConfiguration mockBatchingConfiguration = mock(ResourceBatchingConfiguration.class);
private PluginResourceLocator pluginResourceLocator;
private WebResourceManagerImpl webResourceManager;
private Plugin testPlugin;
private static final String BASEURL = "http://www.foo.com";
private static final String SYSTEM_COUNTER = "123";
private static final String SYSTEM_BUILD_NUMBER = "650";
@Override
protected void setUp() throws Exception
{
super.setUp();
when(mockWebResourceIntegration.getPluginAccessor()).thenReturn(mockPluginAccessor);
when(mockWebResourceIntegration.getSuperBatchVersion()).thenReturn(SYSTEM_BUILD_NUMBER);
when(mockWebResourceIntegration.getTemporaryDirectory()).thenReturn(new File(System.getProperty("java.io.tmpdir"),"test"));
when(mockWebResourceIntegration.getStaticResourceLocale()).thenReturn("en");
pluginResourceLocator = new PluginResourceLocatorImpl(mockWebResourceIntegration, null, mockUrlProvider, mockBatchingConfiguration);
webResourceManager = new WebResourceManagerImpl(pluginResourceLocator, mockWebResourceIntegration, mockUrlProvider, mockBatchingConfiguration);
when(mockUrlProvider.getBaseUrl()).thenReturn(BASEURL);
when(mockUrlProvider.getBaseUrl(UrlMode.ABSOLUTE)).thenReturn(BASEURL);
when(mockUrlProvider.getBaseUrl(UrlMode.AUTO)).thenReturn("");
when(mockUrlProvider.getBaseUrl(UrlMode.RELATIVE)).thenReturn("");
when(mockBatchingConfiguration.isPluginWebResourceBatchingEnabled()).thenReturn(true);
testPlugin = TestUtils.createTestPlugin();
}
@Override
protected void tearDown() throws Exception
{
webResourceManager = null;
mockPluginAccessor = null;
mockWebResourceIntegration = null;
testPlugin = null;
mockBatchingConfiguration = null;
super.tearDown();
}
private void mockEnabledPluginModule(final String key)
{
final ModuleDescriptor md = TestUtils.createWebResourceModuleDescriptor(key, testPlugin);
mockEnabledPluginModule(key, md);
}
private void mockEnabledPluginModule(final String key, final ModuleDescriptor md)
{
when(mockPluginAccessor.getEnabledPluginModule(key)).thenReturn(md);
}
public void testRequireResources()
{
final String resource1 = "test.atlassian:cool-stuff";
final String resource2 = "test.atlassian:hot-stuff";
mockEnabledPluginModule(resource1);
mockEnabledPluginModule(resource2);
final Map<String, Object> requestCache = setupRequestCache();
webResourceManager.requireResource(resource1);
webResourceManager.requireResource(resource2);
webResourceManager.requireResource(resource1); // require again to test it only gets included once
final Collection<?> resources = (Collection<?>) requestCache.get(WebResourceManagerImpl.REQUEST_CACHE_RESOURCE_KEY);
assertEquals(2, resources.size());
assertTrue(resources.contains(resource1));
assertTrue(resources.contains(resource2));
}
public void testRequireResourcesWithCondition() throws ClassNotFoundException
{
final String resource1 = "test.atlassian:cool-stuff";
final String resource2 = "test.atlassian:hot-stuff";
final Plugin plugin = TestUtils.createTestPlugin("test.atlassian", "1", AlwaysTrueCondition.class, AlwaysFalseCondition.class);
mockEnabledPluginModule(resource1,
new WebResourceModuleDescriptorBuilder(plugin, "cool-stuff").setCondition(AlwaysTrueCondition.class).addDescriptor("cool.js").build());
mockEnabledPluginModule(resource2,
new WebResourceModuleDescriptorBuilder(plugin, "hot-stuff").setCondition(AlwaysFalseCondition.class).addDescriptor("hot.js").build());
setupRequestCache();
webResourceManager.requireResource(resource1);
webResourceManager.requireResource(resource2);
final String tags = webResourceManager.getRequiredResources(UrlMode.AUTO);
assertTrue(tags.contains(resource1));
assertFalse(tags.contains(resource2));
}
public void testRequireResourcesWithDependencies()
{
final String resource = "test.atlassian:cool-stuff";
final String dependencyResource = "test.atlassian:hot-stuff";
// cool-stuff depends on hot-stuff
mockEnabledPluginModule(resource, TestUtils.createWebResourceModuleDescriptor(resource, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Collections.singletonList(dependencyResource)));
mockEnabledPluginModule(dependencyResource, TestUtils.createWebResourceModuleDescriptor(dependencyResource, testPlugin));
final Map<String, Object> requestCache = setupRequestCache();
webResourceManager.requireResource(resource);
final Collection<?> resources = (Collection<?>) requestCache.get(WebResourceManagerImpl.REQUEST_CACHE_RESOURCE_KEY);
assertEquals(2, resources.size());
final Object[] resourceArray = resources.toArray();
assertEquals(dependencyResource, resourceArray[0]);
assertEquals(resource, resourceArray[1]);
}
public void testRequireResourcesWithDependencyHiddenByCondition() throws ClassNotFoundException
{
final String resource1 = "test.atlassian:cool-stuff";
final String resource2 = "test.atlassian:hot-stuff";
final Plugin plugin = TestUtils.createTestPlugin("test.atlassian", "1", AlwaysTrueCondition.class, AlwaysFalseCondition.class);
mockEnabledPluginModule(
resource1,
new WebResourceModuleDescriptorBuilder(plugin, "cool-stuff").setCondition(AlwaysTrueCondition.class).addDependency(resource2).addDescriptor(
"cool.js").build());
mockEnabledPluginModule(resource2,
new WebResourceModuleDescriptorBuilder(plugin, "hot-stuff").setCondition(AlwaysFalseCondition.class).addDescriptor("hot.js").build());
setupRequestCache();
webResourceManager.requireResource(resource1);
final String tags = webResourceManager.getRequiredResources(UrlMode.AUTO);
assertTrue(tags.contains(resource1));
assertFalse(tags.contains(resource2));
}
public void testRequireResourcesWithCyclicDependency()
{
final String resource1 = "test.atlassian:cool-stuff";
final String resource2 = "test.atlassian:hot-stuff";
// cool-stuff and hot-stuff depend on each other
mockEnabledPluginModule(resource1, TestUtils.createWebResourceModuleDescriptor(resource1, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Collections.singletonList(resource2)));
mockEnabledPluginModule(resource2, TestUtils.createWebResourceModuleDescriptor(resource2, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Collections.singletonList(resource1)));
final Map<String, Object> requestCache = setupRequestCache();
webResourceManager.requireResource(resource1);
final Collection<?> resources = (Collection<?>) requestCache.get(WebResourceManagerImpl.REQUEST_CACHE_RESOURCE_KEY);
assertEquals(2, resources.size());
final Object[] resourceArray = resources.toArray();
assertEquals(resource2, resourceArray[0]);
assertEquals(resource1, resourceArray[1]);
}
public void testRequireResourcesWithComplexCyclicDependency()
{
final String resourceA = "test.atlassian:a";
final String resourceB = "test.atlassian:b";
final String resourceC = "test.atlassian:c";
final String resourceD = "test.atlassian:d";
final String resourceE = "test.atlassian:e";
// A depends on B, C
mockEnabledPluginModule(resourceA, TestUtils.createWebResourceModuleDescriptor(resourceA, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Arrays.asList(resourceB, resourceC)));
// B depends on D
mockEnabledPluginModule(resourceB, TestUtils.createWebResourceModuleDescriptor(resourceB, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Collections.singletonList(resourceD)));
// C has no dependencies
mockEnabledPluginModule(resourceC, TestUtils.createWebResourceModuleDescriptor(resourceC, testPlugin));
// D depends on E, A (cyclic dependency)
mockEnabledPluginModule(resourceD, TestUtils.createWebResourceModuleDescriptor(resourceD, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Arrays.asList(resourceE, resourceA)));
// E has no dependencies
mockEnabledPluginModule(resourceE, TestUtils.createWebResourceModuleDescriptor(resourceE, testPlugin));
final Map<String, Object> requestCache = setupRequestCache();
webResourceManager.requireResource(resourceA);
// requiring a resource already included by A's dependencies shouldn't change the order
webResourceManager.requireResource(resourceD);
final Collection<?> resources = (Collection<?>) requestCache.get(WebResourceManagerImpl.REQUEST_CACHE_RESOURCE_KEY);
assertEquals(5, resources.size());
final Object[] resourceArray = resources.toArray();
assertEquals(resourceE, resourceArray[0]);
assertEquals(resourceD, resourceArray[1]);
assertEquals(resourceB, resourceArray[2]);
assertEquals(resourceC, resourceArray[3]);
assertEquals(resourceA, resourceArray[4]);
}
public void testGetResourceContext() throws Exception
{
when(mockBatchingConfiguration.isContextBatchingEnabled()).thenReturn(true);
final String resourceA = "test.atlassian:a";
final String resourceB = "test.atlassian:b";
final String resourceC = "test.atlassian:c";
final WebResourceModuleDescriptor descriptor1 = TestUtils.createWebResourceModuleDescriptor(resourceA, testPlugin,
TestUtils.createResourceDescriptors("resourceA.css"), Collections.<String> emptyList(), Collections.<String> emptySet());
final WebResourceModuleDescriptor descriptor2 = TestUtils.createWebResourceModuleDescriptor(resourceB, testPlugin,
TestUtils.createResourceDescriptors("resourceB.css"), Collections.<String> emptyList(), new HashSet<String>()
{
{
add("foo");
}
});
final WebResourceModuleDescriptor descriptor3 = TestUtils.createWebResourceModuleDescriptor(resourceC, testPlugin,
TestUtils.createResourceDescriptors("resourceC.css"), Collections.<String> emptyList(), new HashSet<String>()
{
{
add("foo");
add("bar");
}
});
final List<WebResourceModuleDescriptor> descriptors = Arrays.asList(descriptor1, descriptor2, descriptor3);
when(mockPluginAccessor.getEnabledModuleDescriptorsByClass(WebResourceModuleDescriptor.class)).thenReturn(descriptors);
mockEnabledPluginModule(resourceA, descriptor1);
mockEnabledPluginModule(resourceB, descriptor2);
mockEnabledPluginModule(resourceC, descriptor3);
setupRequestCache();
// write includes for all resources for "foo":
webResourceManager.requireResourcesForContext("foo");
StringWriter writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
String resources = writer.toString();
assertFalse(resources.contains(resourceA + ".css"));
assertFalse(resources.contains(resourceB + ".css"));
assertFalse(resources.contains(resourceC + ".css"));
assertTrue(resources.contains("/download/contextbatch/css/en/dc265b6ded947cfb59087ea613a33790/foo/foo.css"));
assertFalse(resources.contains("/download/contextbatch/css/en/7fa81fc2e4036ae7656775874fe6401c/bar/bar.css"));
// write includes for all resources for "bar":
webResourceManager.requireResourcesForContext("bar");
writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
resources = writer.toString();
assertFalse(resources.contains(resourceA + ".css"));
assertFalse(resources.contains(resourceB + ".css"));
assertFalse(resources.contains(resourceC + ".css"));
assertFalse(resources.contains("/download/contextbatch/css/en/dc265b6ded947cfb59087ea613a33790/foo/foo.css"));
assertTrue(resources.contains("/download/contextbatch/css/en/7fa81fc2e4036ae7656775874fe6401c/bar/bar.css"));
}
public void testGetResourceContextWithCondition() throws ClassNotFoundException, DocumentException
{
when(mockBatchingConfiguration.isContextBatchingEnabled()).thenReturn(true);
final String resource1 = "test.atlassian:cool-stuff";
final String resource2 = "test.atlassian:hot-stuff";
final Plugin plugin = TestUtils.createTestPlugin("test.atlassian", "1", AlwaysTrueCondition.class, AlwaysFalseCondition.class);
final WebResourceModuleDescriptor resource1Descriptor = new WebResourceModuleDescriptorBuilder(plugin, "cool-stuff").setCondition(
AlwaysTrueCondition.class).addDescriptor("cool.js").addContext("foo").build();
mockEnabledPluginModule(resource1, resource1Descriptor);
final WebResourceModuleDescriptor resource2Descriptor = new WebResourceModuleDescriptorBuilder(plugin, "hot-stuff").setCondition(
AlwaysFalseCondition.class).addDescriptor("hot.js").addContext("foo").build();
mockEnabledPluginModule(resource2, resource2Descriptor);
final String resource3 = "test.atlassian:warm-stuff";
final WebResourceModuleDescriptor resourceDescriptor3 = TestUtils.createWebResourceModuleDescriptor(resource3, testPlugin,
TestUtils.createResourceDescriptors("warm.js"), Collections.<String> emptyList(), new HashSet<String>()
{
{
add("foo");
}
});
mockEnabledPluginModule(resource3, resourceDescriptor3);
when(mockPluginAccessor.getEnabledModuleDescriptorsByClass(WebResourceModuleDescriptor.class)).thenReturn(
asList(resource1Descriptor, resource2Descriptor, resourceDescriptor3));
setupRequestCache();
webResourceManager.requireResourcesForContext("foo");
final String tags = webResourceManager.getRequiredResources(UrlMode.AUTO);
assertTrue(tags.contains(resource1));
assertFalse(tags.contains(resource2));
assertTrue(tags.contains("foo/foo.js"));
}
private Map<String, Object> setupRequestCache()
{
final Map<String, Object> requestCache = new HashMap<String, Object>();
when(mockWebResourceIntegration.getRequestCache()).thenReturn(requestCache);
return requestCache;
}
public void testRequireResourceWithDuplicateDependencies()
{
final String resourceA = "test.atlassian:a";
final String resourceB = "test.atlassian:b";
final String resourceC = "test.atlassian:c";
final String resourceD = "test.atlassian:d";
final String resourceE = "test.atlassian:e";
// A depends on B, C
mockEnabledPluginModule(resourceA, TestUtils.createWebResourceModuleDescriptor(resourceA, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Arrays.asList(resourceB, resourceC)));
// B depends on D
mockEnabledPluginModule(resourceB, TestUtils.createWebResourceModuleDescriptor(resourceB, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Collections.singletonList(resourceD)));
// C depends on E
mockEnabledPluginModule(resourceC, TestUtils.createWebResourceModuleDescriptor(resourceC, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Collections.singletonList(resourceE)));
// D depends on C
mockEnabledPluginModule(resourceD, TestUtils.createWebResourceModuleDescriptor(resourceD, testPlugin,
Collections.<ResourceDescriptor> emptyList(), Collections.singletonList(resourceC)));
// E has no dependencies
mockEnabledPluginModule(resourceE, TestUtils.createWebResourceModuleDescriptor(resourceE, testPlugin));
final Map<String, Object> requestCache = setupRequestCache();
webResourceManager.requireResource(resourceA);
final Collection<?> resources = (Collection<?>) requestCache.get(WebResourceManagerImpl.REQUEST_CACHE_RESOURCE_KEY);
assertEquals(5, resources.size());
final Object[] resourceArray = resources.toArray();
assertEquals(resourceE, resourceArray[0]);
assertEquals(resourceC, resourceArray[1]);
assertEquals(resourceD, resourceArray[2]);
assertEquals(resourceB, resourceArray[3]);
assertEquals(resourceA, resourceArray[4]);
}
public void testRequireSingleResourceGetsDeps() throws Exception
{
final String resourceA = "test.atlassian:a";
final String resourceB = "test.atlassian:b";
final List<ResourceDescriptor> resourceDescriptorsA = TestUtils.createResourceDescriptors("resourceA.css");
final List<ResourceDescriptor> resourceDescriptorsB = TestUtils.createResourceDescriptors("resourceB.css", "resourceB-more.css");
// A depends on B
mockEnabledPluginModule(resourceA, TestUtils.createWebResourceModuleDescriptor(resourceA, testPlugin, resourceDescriptorsA,
Collections.singletonList(resourceB)));
mockEnabledPluginModule(resourceB, TestUtils.createWebResourceModuleDescriptor(resourceB, testPlugin, resourceDescriptorsB,
Collections.<String> emptyList()));
final String s = webResourceManager.getResourceTags(resourceA, UrlMode.AUTO);
final int indexA = s.indexOf(resourceA);
final int indexB = s.indexOf(resourceB);
assertNotSame(-1, indexA);
assertNotSame(-1, indexB);
assertTrue(indexB < indexA);
}
public void testIncludeResourcesWithResourceList() throws Exception
{
final String resourceA = "test.atlassian:a";
final List<ResourceDescriptor> resourceDescriptorsA = TestUtils.createResourceDescriptors("resourceA.css");
mockEnabledPluginModule(resourceA, TestUtils.createWebResourceModuleDescriptor(resourceA, testPlugin, resourceDescriptorsA,
Collections.<String> emptyList()));
final StringWriter requiredResourceWriter = new StringWriter();
webResourceManager.includeResources(Arrays.<String> asList(resourceA), requiredResourceWriter, UrlMode.ABSOLUTE);
final String result = requiredResourceWriter.toString();
assertTrue(result.contains(resourceA));
}
public void testIncludeResourcesWithResourceListIgnoresRequireResource() throws Exception
{
final String resourceA = "test.atlassian:a";
final String resourceB = "test.atlassian:b";
final List<ResourceDescriptor> resourceDescriptorsA = TestUtils.createResourceDescriptors("resourceA.css");
final List<ResourceDescriptor> resourceDescriptorsB = TestUtils.createResourceDescriptors("resourceB.css", "resourceB-more.css");
final Map<String, Object> requestCache = new HashMap<String, Object>();
when(mockWebResourceIntegration.getRequestCache()).thenReturn(requestCache);
mockEnabledPluginModule(resourceA, TestUtils.createWebResourceModuleDescriptor(resourceA, testPlugin, resourceDescriptorsA,
Collections.<String> emptyList()));
mockEnabledPluginModule(resourceB, TestUtils.createWebResourceModuleDescriptor(resourceB, testPlugin, resourceDescriptorsB,
Collections.<String> emptyList()));
final StringWriter requiredResourceWriter = new StringWriter();
webResourceManager.requireResource(resourceB);
webResourceManager.includeResources(Arrays.<String> asList(resourceA), requiredResourceWriter, UrlMode.ABSOLUTE);
final String result = requiredResourceWriter.toString();
assertFalse(result.contains(resourceB));
}
public void testIncludeResourcesWithResourceListIncludesDependences() throws Exception
{
final String resourceA = "test.atlassian:a";
final String resourceB = "test.atlassian:b";
final List<ResourceDescriptor> resourceDescriptorsA = TestUtils.createResourceDescriptors("resourceA.css");
final List<ResourceDescriptor> resourceDescriptorsB = TestUtils.createResourceDescriptors("resourceB.css", "resourceB-more.css");
// A depends on B
mockEnabledPluginModule(resourceA, TestUtils.createWebResourceModuleDescriptor(resourceA, testPlugin, resourceDescriptorsA,
Collections.singletonList(resourceB)));
mockEnabledPluginModule(resourceB, TestUtils.createWebResourceModuleDescriptor(resourceB, testPlugin, resourceDescriptorsB,
Collections.<String> emptyList()));
final StringWriter requiredResourceWriter = new StringWriter();
webResourceManager.includeResources(Arrays.<String> asList(resourceA), requiredResourceWriter, UrlMode.ABSOLUTE);
final String result = requiredResourceWriter.toString();
assertTrue(result.contains(resourceB));
}
public void testIncludeResourcesWithResourceListIncludesDependencesFromSuperBatch() throws Exception
{
final String resourceA = "test.atlassian:a";
final String resourceB = "test.atlassian:b";
final ResourceBatchingConfiguration mockBatchingConfiguration = mock(ResourceBatchingConfiguration.class);
when(mockBatchingConfiguration.isSuperBatchingEnabled()).thenReturn(true);
when(mockBatchingConfiguration.getSuperBatchModuleCompleteKeys()).thenReturn(Arrays.asList(resourceB));
webResourceManager = new WebResourceManagerImpl(pluginResourceLocator, mockWebResourceIntegration, mockUrlProvider, mockBatchingConfiguration);
final List<ResourceDescriptor> resourceDescriptorsA = TestUtils.createResourceDescriptors("resourceA.css");
final List<ResourceDescriptor> resourceDescriptorsB = TestUtils.createResourceDescriptors("resourceB.css");
// A depends on B
mockEnabledPluginModule(resourceA, TestUtils.createWebResourceModuleDescriptor(resourceA, testPlugin, resourceDescriptorsA,
Collections.singletonList(resourceB)));
mockEnabledPluginModule(resourceB, TestUtils.createWebResourceModuleDescriptor(resourceB, testPlugin, resourceDescriptorsB,
Collections.<String> emptyList()));
final StringWriter requiredResourceWriter = new StringWriter();
webResourceManager.includeResources(Arrays.<String> asList(resourceA), requiredResourceWriter, UrlMode.ABSOLUTE);
final String result = requiredResourceWriter.toString();
assertTrue(result.contains(resourceB));
}
public void testIncludeResourcesWithSharedDependencies() throws Exception
{
final String resourceA = "test.atlassian:a";
final String resourceB = "test.atlassian:b";
final String resourceShared = "test.atlassian:c";
when(mockBatchingConfiguration.getSuperBatchModuleCompleteKeys()).thenReturn(Arrays.asList(resourceB));
webResourceManager = new WebResourceManagerImpl(pluginResourceLocator, mockWebResourceIntegration, mockUrlProvider, mockBatchingConfiguration);
final List<ResourceDescriptor> resourceDescriptorsA = TestUtils.createResourceDescriptors("resourceA.css");
final List<ResourceDescriptor> resourceDescriptorsB = TestUtils.createResourceDescriptors("resourceB.css");
final List<ResourceDescriptor> resourceDescriptorsShared = TestUtils.createResourceDescriptors("resourceC.css");
// A depends on C
mockEnabledPluginModule(resourceA, TestUtils.createWebResourceModuleDescriptor(resourceA, testPlugin, resourceDescriptorsA,
Collections.singletonList(resourceShared)));
// B depends on C
mockEnabledPluginModule(resourceB, TestUtils.createWebResourceModuleDescriptor(resourceB, testPlugin, resourceDescriptorsB,
Collections.singletonList(resourceShared)));
mockEnabledPluginModule(resourceShared, TestUtils.createWebResourceModuleDescriptor(resourceShared, testPlugin, resourceDescriptorsShared,
Collections.<String> emptyList()));
final StringWriter requiredResourceWriter = new StringWriter();
webResourceManager.includeResources(Arrays.<String> asList(resourceA, resourceB), requiredResourceWriter, UrlMode.ABSOLUTE);
final String result = requiredResourceWriter.toString();
assertTrue(result.contains(resourceA));
assertTrue(result.contains(resourceB));
Pattern resourceCount = Pattern.compile("/download/batch/en/1/test\\.atlassian:c/test\\.atlassian:c.css");
Matcher m = resourceCount.matcher(result);
assertTrue(m.find());
assertFalse(m.find(m.end()));
}
public void testRequireResourcesAreClearedAfterIncludesResourcesIsCalled() throws Exception
{
final String moduleKey = "cool-resources";
final String completeModuleKey = "test.atlassian:" + moduleKey;
final List<ResourceDescriptor> resourceDescriptors1 = TestUtils.createResourceDescriptors("cool.css", "more-cool.css", "cool.js");
setupRequestCache();
mockEnabledPluginModule(completeModuleKey, TestUtils.createWebResourceModuleDescriptor(completeModuleKey, testPlugin, resourceDescriptors1));
// test requireResource() methods
webResourceManager.requireResource(completeModuleKey);
webResourceManager.includeResources(new StringWriter(), UrlMode.RELATIVE);
final StringWriter requiredResourceWriter = new StringWriter();
webResourceManager.includeResources(requiredResourceWriter, UrlMode.RELATIVE);
assertEquals("", requiredResourceWriter.toString());
}
// testRequireResourceAndResourceTagMethods
public void testRequireResourceAndResourceTagMethods() throws Exception
{
final String completeModuleKey = "test.atlassian:cool-resources";
final String staticBase = setupRequireResourceAndResourceTagMethods(false, completeModuleKey);
// test requireResource() methods
final StringWriter requiredResourceWriter = new StringWriter();
webResourceManager.requireResource(completeModuleKey);
final String requiredResourceResult = webResourceManager.getRequiredResources(UrlMode.RELATIVE);
webResourceManager.includeResources(requiredResourceWriter, UrlMode.RELATIVE);
assertEquals(requiredResourceResult, requiredResourceWriter.toString());
assertTrue(requiredResourceResult.contains("href=\"" + staticBase + "en/1/" + completeModuleKey + "/" + completeModuleKey + ".css"));
assertTrue(requiredResourceResult.contains("src=\"" + staticBase + "en/1/" + completeModuleKey + "/" + completeModuleKey + ".js"));
// test resourceTag() methods
final StringWriter resourceTagsWriter = new StringWriter();
webResourceManager.requireResource(completeModuleKey, resourceTagsWriter, UrlMode.RELATIVE);
final String resourceTagsResult = webResourceManager.getResourceTags(completeModuleKey, UrlMode.RELATIVE);
assertEquals(resourceTagsResult, resourceTagsWriter.toString());
// calling requireResource() or resourceTag() on a single webresource should be the same
assertEquals(requiredResourceResult, resourceTagsResult);
}
public void testRequireResourceAndResourceTagMethodsWithAbsoluteUrlMode() throws Exception
{
testRequireResourceAndResourceTagMethods(UrlMode.ABSOLUTE, true);
}
public void testRequireResourceAndResourceTagMethodsWithRelativeUrlMode() throws Exception
{
testRequireResourceAndResourceTagMethods(UrlMode.RELATIVE, false);
}
public void testRequireResourceAndResourceTagMethodsWithAutoUrlMode() throws Exception
{
testRequireResourceAndResourceTagMethods(UrlMode.AUTO, false);
}
private void testRequireResourceAndResourceTagMethods(final UrlMode urlMode, final boolean baseUrlExpected) throws Exception
{
final String completeModuleKey = "test.atlassian:cool-resources";
final String staticBase = setupRequireResourceAndResourceTagMethods(baseUrlExpected, completeModuleKey);
// test requireResource() methods
final StringWriter requiredResourceWriter = new StringWriter();
webResourceManager.requireResource(completeModuleKey);
final String requiredResourceResult = webResourceManager.getRequiredResources(urlMode);
webResourceManager.includeResources(requiredResourceWriter, urlMode);
assertEquals(requiredResourceResult, requiredResourceWriter.toString());
assertTrue(requiredResourceResult.contains("href=\"" + staticBase + "en/1/" + completeModuleKey + "/" + completeModuleKey + ".css"));
assertTrue(requiredResourceResult.contains("src=\"" + staticBase + "en/1/" + completeModuleKey + "/" + completeModuleKey + ".js"));
// test resourceTag() methods
final StringWriter resourceTagsWriter = new StringWriter();
webResourceManager.requireResource(completeModuleKey, resourceTagsWriter, urlMode);
final String resourceTagsResult = webResourceManager.getResourceTags(completeModuleKey, urlMode);
assertEquals(resourceTagsResult, resourceTagsWriter.toString());
// calling requireResource() or resourceTag() on a single webresource should be the same
assertEquals(requiredResourceResult, resourceTagsResult);
}
private String setupRequireResourceAndResourceTagMethods(final boolean baseUrlExpected, final String completeModuleKey) throws DocumentException
{
final List<ResourceDescriptor> descriptors = TestUtils.createResourceDescriptors("cool.css", "more-cool.css", "cool.js");
final Map<String, Object> requestCache = new HashMap<String, Object>();
when(mockWebResourceIntegration.getRequestCache()).thenReturn(requestCache);
mockEnabledPluginModule(completeModuleKey, TestUtils.createWebResourceModuleDescriptor(completeModuleKey, testPlugin, descriptors));
final String staticPrefix = (baseUrlExpected ? BASEURL : "") + "/" + WebResourceManagerImpl.STATIC_RESOURCE_PREFIX + "/" + SYSTEM_BUILD_NUMBER + "/" + SYSTEM_COUNTER + "/" + testPlugin.getPluginInformation().getVersion() + "/" + WebResourceManagerImpl.STATIC_RESOURCE_SUFFIX;
when(mockUrlProvider.getStaticResourcePrefix(eq("1"), isA(UrlMode.class))).thenReturn(staticPrefix);
return staticPrefix + BatchPluginResource.URL_PREFIX;
}
// testRequireResourceWithCacheParameter
public void testRequireResourceWithCacheParameter() throws Exception
{
final String completeModuleKey = "test.atlassian:no-cache-resources";
final String expectedResult = setupRequireResourceWithCacheParameter(false, completeModuleKey);
assertTrue(webResourceManager.getResourceTags(completeModuleKey, UrlMode.AUTO).contains(expectedResult));
}
public void testRequireResourceWithCacheParameterAndAbsoluteUrlMode() throws Exception
{
testRequireResourceWithCacheParameter(UrlMode.ABSOLUTE, true);
}
public void testRequireResourceWithCacheParameterAndRelativeUrlMode() throws Exception
{
testRequireResourceWithCacheParameter(UrlMode.RELATIVE, false);
}
public void testRequireResourceWithCacheParameterAndAutoUrlMode() throws Exception
{
testRequireResourceWithCacheParameter(UrlMode.AUTO, false);
}
private void testRequireResourceWithCacheParameter(final UrlMode urlMode, final boolean baseUrlExpected) throws Exception
{
final String completeModuleKey = "test.atlassian:no-cache-resources";
final String expectedResult = setupRequireResourceWithCacheParameter(baseUrlExpected, completeModuleKey);
assertTrue(webResourceManager.getResourceTags(completeModuleKey, urlMode).contains(expectedResult));
}
private String setupRequireResourceWithCacheParameter(final boolean baseUrlExpected, final String completeModuleKey) throws DocumentException
{
final Map<String, String> params = new HashMap<String, String>();
params.put("cache", "false");
final ResourceDescriptor resourceDescriptor = TestUtils.createResourceDescriptor("no-cache.js", params);
mockEnabledPluginModule(completeModuleKey, TestUtils.createWebResourceModuleDescriptor(completeModuleKey, testPlugin,
Collections.singletonList(resourceDescriptor)));
return "src=\"" + (baseUrlExpected ? BASEURL : "") + BatchPluginResource.URL_PREFIX + "en/1/" + completeModuleKey + "/" + completeModuleKey + ".js?cache=false";
}
public void testGetRequiredResourcesWithFilter() throws Exception
{
final String moduleKey = "cool-resources";
final String completeModuleKey = "test.atlassian:" + moduleKey;
final List<ResourceDescriptor> resourceDescriptors1 = TestUtils.createResourceDescriptors("cool.css", "cool.js", "more-cool.css");
setupRequestCache();
mockEnabledPluginModule(completeModuleKey, TestUtils.createWebResourceModuleDescriptor(completeModuleKey, testPlugin, resourceDescriptors1));
// test includeResources(writer, type) method
webResourceManager.requireResource(completeModuleKey);
final String staticPrefix = BASEURL + "/" + WebResourceManagerImpl.STATIC_RESOURCE_PREFIX + "/" + SYSTEM_BUILD_NUMBER + "/" + SYSTEM_COUNTER + "/" + testPlugin.getPluginInformation().getVersion() + "/" + WebResourceManagerImpl.STATIC_RESOURCE_SUFFIX;
when(mockUrlProvider.getStaticResourcePrefix("1", UrlMode.ABSOLUTE)).thenReturn(staticPrefix);
final String staticBase = staticPrefix + BatchPluginResource.URL_PREFIX;
final String cssRef = "href=\"" + staticBase + "en/1/" + completeModuleKey + "/" + completeModuleKey + ".css";
final String jsRef = "src=\"" + staticBase + "en/1/" + completeModuleKey + "/" + completeModuleKey + ".js";
// CSS
String requiredResourceResult = webResourceManager.getRequiredResources(UrlMode.ABSOLUTE, new CssWebResource());
assertTrue(requiredResourceResult.contains(cssRef));
assertFalse(requiredResourceResult.contains(jsRef));
// JS
requiredResourceResult = webResourceManager.getRequiredResources(UrlMode.ABSOLUTE, new JavascriptWebResource());
assertFalse(requiredResourceResult.contains(cssRef));
assertTrue(requiredResourceResult.contains(jsRef));
// BOTH
requiredResourceResult = webResourceManager.getRequiredResources(UrlMode.ABSOLUTE);
assertTrue(requiredResourceResult.contains(cssRef));
assertTrue(requiredResourceResult.contains(jsRef));
}
public void testGetRequiredResourcesWithCustomFilters() throws Exception
{
final WebResourceFilter atlassianFilter = new WebResourceFilter()
{
public boolean matches(final String resourceName)
{
return resourceName.contains("atlassian");
}
};
final WebResourceFilter bogusFilter = new WebResourceFilter()
{
public boolean matches(final String resourceName)
{
return true;
}
};
final String moduleKey = "cool-resources";
final String completeModuleKey = "test.atlassian:" + moduleKey;
final List<ResourceDescriptor> resources = TestUtils.createResourceDescriptors("foo.css", "foo-bar.js", "atlassian.css",
"atlassian-plugins.js");
setupRequestCache();
mockEnabledPluginModule(completeModuleKey, TestUtils.createWebResourceModuleDescriptor(completeModuleKey, testPlugin, resources));
// easier to test which resources were included by the filter with batching turned off
when(mockBatchingConfiguration.isPluginWebResourceBatchingEnabled()).thenReturn(false);
webResourceManager.requireResource(completeModuleKey);
final String atlassianResources = webResourceManager.getRequiredResources(UrlMode.RELATIVE, atlassianFilter);
assertEquals(-1, atlassianResources.indexOf("foo"));
assertTrue(atlassianResources.contains("atlassian.css"));
assertTrue(atlassianResources.contains("atlassian-plugins.js"));
final String allResources = webResourceManager.getRequiredResources(UrlMode.RELATIVE, bogusFilter);
for (final ResourceDescriptor resource : resources)
{
assertTrue(allResources.contains(resource.getName()));
}
}
public void testGetRequiredResourcesOrdersByType() throws Exception
{
final String moduleKey1 = "cool-resources";
final String moduleKey2 = "hot-resources";
final String completeModuleKey1 = "test.atlassian:" + moduleKey1;
final String completeModuleKey2 = "test.atlassian:" + moduleKey2;
final List<ResourceDescriptor> resourceDescriptors1 = TestUtils.createResourceDescriptors("cool.js", "cool.css", "more-cool.css");
final List<ResourceDescriptor> resourceDescriptors2 = TestUtils.createResourceDescriptors("hot.js", "hot.css", "more-hot.css");
final Plugin plugin = TestUtils.createTestPlugin();
setupRequestCache();
mockEnabledPluginModule(completeModuleKey1, TestUtils.createWebResourceModuleDescriptor(completeModuleKey1, plugin, resourceDescriptors1));
mockEnabledPluginModule(completeModuleKey2, TestUtils.createWebResourceModuleDescriptor(completeModuleKey2, plugin, resourceDescriptors2));
// test includeResources(writer, type) method
webResourceManager.requireResource(completeModuleKey1);
webResourceManager.requireResource(completeModuleKey2);
final String staticPrefix = BASEURL + "/" + WebResourceManagerImpl.STATIC_RESOURCE_PREFIX + "/" + SYSTEM_BUILD_NUMBER + "/" + SYSTEM_COUNTER + "/" + plugin.getPluginInformation().getVersion() + "/" + WebResourceManagerImpl.STATIC_RESOURCE_SUFFIX;
when(mockUrlProvider.getStaticResourcePrefix("1", UrlMode.ABSOLUTE)).thenReturn(staticPrefix);
final String staticBase = staticPrefix + BatchPluginResource.URL_PREFIX;
final String cssRef1 = "href=\"" + staticBase + "en/1/" + completeModuleKey1 + "/" + completeModuleKey1 + ".css";
final String cssRef2 = "href=\"" + staticBase + "en/1/" + completeModuleKey2 + "/" + completeModuleKey2 + ".css";
final String jsRef1 = "src=\"" + staticBase + "en/1/" + completeModuleKey1 + "/" + completeModuleKey1 + ".js";
final String jsRef2 = "src=\"" + staticBase + "en/1/" + completeModuleKey2 + "/" + completeModuleKey2 + ".js";
final String requiredResourceResult = webResourceManager.getRequiredResources(UrlMode.ABSOLUTE);
assertTrue(requiredResourceResult.contains(cssRef1));
assertTrue(requiredResourceResult.contains(cssRef2));
assertTrue(requiredResourceResult.contains(jsRef1));
assertTrue(requiredResourceResult.contains(jsRef2));
final int cssRef1Index = requiredResourceResult.indexOf(cssRef1);
final int cssRef2Index = requiredResourceResult.indexOf(cssRef2);
final int jsRef1Index = requiredResourceResult.indexOf(jsRef1);
final int jsRef2Index = requiredResourceResult.indexOf(jsRef2);
assertTrue(cssRef1Index < jsRef1Index);
assertTrue(cssRef2Index < jsRef2Index);
assertTrue(cssRef2Index < jsRef1Index);
}
public void testRequireResourceInSuperbatch() throws ClassNotFoundException
{
setupSuperBatch();
final Map<String, Object> requestCache = setupRequestCache();
mockOutSuperbatchPluginAccesses();
webResourceManager.requireResource("test.atlassian:superbatch");
final Collection<?> resources = (Collection<?>) requestCache.get(WebResourceManagerImpl.REQUEST_CACHE_RESOURCE_KEY);
assertEquals(0, resources.size());
}
public void testRequireResourceWithDependencyInSuperbatch() throws DocumentException, ClassNotFoundException
{
setupSuperBatch();
mockOutSuperbatchPluginAccesses();
final Map<String, Object> requestCache = setupRequestCache();
mockEnabledPluginModule("test.atlassian:included-resource", TestUtils.createWebResourceModuleDescriptor("test.atlassian:included-resource",
testPlugin, Collections.<ResourceDescriptor> emptyList(), Collections.singletonList("test.atlassian:superbatch")));
webResourceManager.requireResource("test.atlassian:included-resource");
final Collection<?> resources = (Collection<?>) requestCache.get(WebResourceManagerImpl.REQUEST_CACHE_RESOURCE_KEY);
assertEquals(1, resources.size());
assertEquals("test.atlassian:included-resource", resources.iterator().next());
}
public void testSuperBatchResolution() throws DocumentException, ClassNotFoundException
{
setupSuperBatch();
TestUtils.setupSuperbatchTestContent(mockPluginAccessor, testPlugin);
final List<PluginResource> cssResources = webResourceManager.getSuperBatchResources(CssWebResource.FORMATTER);
assertEquals(2, cssResources.size());
final SuperBatchPluginResource superBatch1 = (SuperBatchPluginResource) cssResources.get(0);
assertEquals("batch.css", superBatch1.getResourceName());
assertTrue(superBatch1.getParams().isEmpty());
final SuperBatchPluginResource superBatch2 = (SuperBatchPluginResource) cssResources.get(1);
assertEquals("batch.css", superBatch2.getResourceName());
assertEquals("true", superBatch2.getParams().get("ieonly"));
final List<PluginResource> jsResources = webResourceManager.getSuperBatchResources(JavascriptWebResource.FORMATTER);
assertEquals(1, jsResources.size());
assertEquals("batch.js", jsResources.get(0).getResourceName());
assertEquals(0, jsResources.get(0).getParams().size());
}
// First part: execute some WRM code on in a new context on top of a non-empty context and write out.
// Check that the expected resources are included in the inner write out and that the outer resources aren't included
// Second part: after the inner execution is completed, write the outer resources out, checking that we didn't get the inner resources and that we did get
// the resources which were in the context before the inner execution.
public void testNestedContextExclusivity() throws Exception
{
final String moduleKey1 = "cool-resources";
final String moduleKey2 = "hot-resources";
final String completeModuleKey1 = "test.atlassian:" + moduleKey1;
final String completeModuleKey2 = "test.atlassian:" + moduleKey2;
final List<ResourceDescriptor> resourceDescriptors1 = TestUtils.createResourceDescriptors("cool.js", "cool.css", "more-cool.css");
final List<ResourceDescriptor> resourceDescriptors2 = TestUtils.createResourceDescriptors("hot.js", "hot.css", "more-hot.css");
final Plugin plugin = TestUtils.createTestPlugin();
setupRequestCache();
mockEnabledPluginModule(completeModuleKey1, TestUtils.createWebResourceModuleDescriptor(completeModuleKey1, plugin, resourceDescriptors1));
mockEnabledPluginModule(completeModuleKey2, TestUtils.createWebResourceModuleDescriptor(completeModuleKey2, plugin, resourceDescriptors2));
final String cssRef1 = completeModuleKey1 + "/" + completeModuleKey1 + ".css";
final String cssRef2 = completeModuleKey2 + "/" + completeModuleKey2 + ".css";
final String jsRef1 = completeModuleKey1 + "/" + completeModuleKey1 + ".js";
final String jsRef2 = completeModuleKey2 + "/" + completeModuleKey2 + ".js";
// test includeResources(writer, type) method
webResourceManager.requireResource(completeModuleKey1);
webResourceManager.executeInNewContext(new Supplier<Void>()
{
public Void get()
{
webResourceManager.requireResource(completeModuleKey2);
final StringWriter writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
final String resources = writer.toString();
assertFalse(resources.contains(cssRef1));
assertTrue(resources.contains(cssRef2));
assertFalse(resources.contains(jsRef1));
assertTrue(resources.contains(jsRef2));
return null;
}
});
final StringWriter writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
final String resources = writer.toString();
assertTrue(resources.contains(cssRef1));
assertFalse(resources.contains(cssRef2));
assertTrue(resources.contains(jsRef1));
assertFalse(resources.contains(jsRef2));
}
// Require and include some resource in an inner context with an empty outer context. Check that the inner context gets the expected resources.
// After the inner code is executed, check that we didn't get any resources in the outer context
public void testNestedContextOnEmptyBase() throws Exception
{
final String moduleKey1 = "cool-resources";
final String completeModuleKey1 = "test.atlassian:" + moduleKey1;
final List<ResourceDescriptor> resourceDescriptors1 = TestUtils.createResourceDescriptors("cool.js", "cool.css", "more-cool.css");
final Plugin plugin = TestUtils.createTestPlugin();
setupRequestCache();
mockEnabledPluginModule(completeModuleKey1, TestUtils.createWebResourceModuleDescriptor(completeModuleKey1, plugin, resourceDescriptors1));
final String cssRef1 = completeModuleKey1 + "/" + completeModuleKey1 + ".css";
final String jsRef1 = completeModuleKey1 + "/" + completeModuleKey1 + ".js";
// test includeResources(writer, type) method
webResourceManager.executeInNewContext(new Supplier<Void>()
{
public Void get()
{
webResourceManager.requireResource(completeModuleKey1);
final StringWriter writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
final String resources = writer.toString();
assertTrue(resources.contains(cssRef1));
assertTrue(resources.contains(jsRef1));
return null;
}
});
final StringWriter writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
final String resources = writer.toString();
assertFalse(resources.contains(cssRef1));
assertFalse(resources.contains(jsRef1));
}
// Require (but not include) some resource in an inner context with an empty outer context. After the inner code is executed,
// check that we didn't get any resources in the outer context
public void testNestedContextWithoutWriting() throws Exception
{
final String moduleKey1 = "cool-resources";
final String completeModuleKey1 = "test.atlassian:" + moduleKey1;
final List<ResourceDescriptor> resourceDescriptors1 = TestUtils.createResourceDescriptors("cool.js", "cool.css", "more-cool.css");
final Plugin plugin = TestUtils.createTestPlugin();
setupRequestCache();
mockEnabledPluginModule(completeModuleKey1, TestUtils.createWebResourceModuleDescriptor(completeModuleKey1, plugin, resourceDescriptors1));
final String cssRef1 = completeModuleKey1 + "/" + completeModuleKey1 + ".css";
final String jsRef1 = completeModuleKey1 + "/" + completeModuleKey1 + ".js";
// test includeResources(writer, type) method
webResourceManager.executeInNewContext(new Supplier<Void>()
{
public Void get()
{
webResourceManager.requireResource(completeModuleKey1);
return null;
}
});
final StringWriter writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
final String resources = writer.toString();
// check that we didn't get these resources (meaning that the require resources call never caused the module to be included)
assertFalse(resources.contains(cssRef1));
assertFalse(resources.contains(jsRef1));
}
// push content into the outer-most context, nest multiple non-empty executeInNewContext calls, ensuring that the expected content is
// written in each context
public void testMultipleNestedContexts() throws Exception
{
final String moduleKey1 = "cool-resources";
final String moduleKey2 = "hot-resources";
final String moduleKey3 = "warm-resources";
final String completeModuleKey1 = "test.atlassian:" + moduleKey1;
final String completeModuleKey2 = "test.atlassian:" + moduleKey2;
final String completeModuleKey3 = "test.atlassian:" + moduleKey3;
final List<ResourceDescriptor> resourceDescriptors1 = TestUtils.createResourceDescriptors("cool.js", "cool.css", "more-cool.css");
final List<ResourceDescriptor> resourceDescriptors2 = TestUtils.createResourceDescriptors("hot.js", "hot.css", "more-hot.css");
final List<ResourceDescriptor> resourceDescriptors3 = TestUtils.createResourceDescriptors("warm.js", "warm.css", "more-warm.css");
final Plugin plugin = TestUtils.createTestPlugin();
setupRequestCache();
mockEnabledPluginModule(completeModuleKey1, TestUtils.createWebResourceModuleDescriptor(completeModuleKey1, plugin, resourceDescriptors1));
mockEnabledPluginModule(completeModuleKey2, TestUtils.createWebResourceModuleDescriptor(completeModuleKey2, plugin, resourceDescriptors2));
mockEnabledPluginModule(completeModuleKey3, TestUtils.createWebResourceModuleDescriptor(completeModuleKey3, plugin, resourceDescriptors3));
final String cssRef1 = completeModuleKey1 + "/" + completeModuleKey1 + ".css";
final String cssRef2 = completeModuleKey2 + "/" + completeModuleKey2 + ".css";
final String cssRef3 = completeModuleKey3 + "/" + completeModuleKey3 + ".css";
final String jsRef1 = completeModuleKey1 + "/" + completeModuleKey1 + ".js";
final String jsRef2 = completeModuleKey2 + "/" + completeModuleKey2 + ".js";
final String jsRef3 = completeModuleKey3 + "/" + completeModuleKey3 + ".js";
setupRequestCache();
// require module 1 for outermost resource
webResourceManager.requireResource(completeModuleKey1);
// nest middle resource context (requests module 2)
webResourceManager.executeInNewContext(new Supplier<Void>()
{
public Void get()
{
webResourceManager.requireResource(completeModuleKey2);
// nest inner-most resource context (requests module 3)
webResourceManager.executeInNewContext(new Supplier<Void>()
{
public Void get()
{
webResourceManager.requireResource(completeModuleKey3);
// check that the inner-most context only got module 3
final StringWriter writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
final String resources = writer.toString();
assertTrue(resources.contains(cssRef3));
assertTrue(resources.contains(jsRef3));
assertFalse(resources.contains(cssRef1));
assertFalse(resources.contains(jsRef1));
assertFalse(resources.contains(cssRef2));
assertFalse(resources.contains(jsRef2));
return null;
}
});
// check that the middle context only got module 2
final StringWriter writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
final String resources = writer.toString();
assertTrue(resources.contains(cssRef2));
assertTrue(resources.contains(jsRef2));
assertFalse(resources.contains(cssRef1));
assertFalse(resources.contains(jsRef1));
assertFalse(resources.contains(cssRef3));
assertFalse(resources.contains(jsRef3));
return null;
}
});
// check that the outer context only got module 1
final StringWriter writer = new StringWriter();
webResourceManager.includeResources(writer, UrlMode.AUTO);
final String resources = writer.toString();
assertTrue(resources.contains(cssRef1));
assertTrue(resources.contains(jsRef1));
assertFalse(resources.contains(cssRef2));
assertFalse(resources.contains(jsRef2));
assertFalse(resources.contains(cssRef3));
assertFalse(resources.contains(jsRef3));
}
private void setupSuperBatch()
{
when(mockBatchingConfiguration.isSuperBatchingEnabled()).thenReturn(true);
when(mockBatchingConfiguration.getSuperBatchModuleCompleteKeys()).thenReturn(
Arrays.asList("test.atlassian:superbatch", "test.atlassian:superbatch2", "test.atlassian:missing-plugin"));
}
private void mockOutSuperbatchPluginAccesses() throws ClassNotFoundException
{
mockOutPluginModule("test.atlassian:superbatch");
mockOutPluginModule("test.atlassian:superbatch2");
when(mockPluginAccessor.getPluginModule("test.atlassian:missing-plugin")).thenReturn(null);
when(mockPluginAccessor.getEnabledPluginModule("test.atlassian:missing-plugin")).thenReturn(null);
}
private void mockOutPluginModule(final String moduleKey) throws ClassNotFoundException
{
final Plugin p = TestUtils.createTestPlugin();
final ModuleDescriptor module = TestUtils.createWebResourceModuleDescriptor(moduleKey, p);
when(mockPluginAccessor.getPluginModule(moduleKey)).thenReturn(module);
when(mockPluginAccessor.getEnabledPluginModule(moduleKey)).thenReturn(module);
}
}
| |
/*
* Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government 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 UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.transform.audit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import gov.hhs.fha.nhinc.common.auditlog.LogEventRequestType;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;
import oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author dunnek
*/
public class XDRTransformsTest {
private static final String CONST_USER_NAME = XDRMessageHelper.CONST_USER_NAME;
private static final String CONST_HCID = "1.1";
public XDRTransformsTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testTransformResponseToAuditMsg_Null() {
System.out.println("testTransformResponseToAuditMsg_Null");
AssertionType assertion = createAssertion();
String direction = NhincConstants.AUDIT_LOG_INBOUND_DIRECTION;
String _interface = "interface";
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
LogEventRequestType result = instance.transformResponseToAuditMsg(null, assertion, null, direction, _interface, false);
assertNull(result);
}
@Test
public void testTransformResponseToAuditMsg_Empty() {
System.out.println("testTransformResponseToAuditMsg_Empty");
AssertionType assertion = createAssertion();
String direction = NhincConstants.AUDIT_LOG_INBOUND_DIRECTION;
String _interface = "interface";
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
NhinTargetSystemType target = new NhinTargetSystemType();
LogEventRequestType result = instance.transformResponseToAuditMsg(new RegistryResponseType(), assertion,
target, direction, _interface, false);
assertNotNull(result);
}
@Test
public void testTransformResponseToAuditMsg_NotEmpty() {
System.out.println("testTransformResponseToAuditMsg_Empty");
AssertionType assertion = createAssertion();
String direction = NhincConstants.AUDIT_LOG_INBOUND_DIRECTION;
String _interface = "interface";
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
RegistryResponseType response = new RegistryResponseType();
NhinTargetSystemType target = new NhinTargetSystemType();
LogEventRequestType result = instance.transformResponseToAuditMsg(response, assertion, target, direction,
_interface, false);
assertNotNull(result);
assertEquals(_interface, result.getInterface());
assertEquals(direction, result.getDirection());
}
@Test
public void testTransformResponseToAuditMsg_Success() {
System.out.println("testTransformResponseToAuditMsg_Empty");
AssertionType assertion = createAssertion();
String direction = NhincConstants.AUDIT_LOG_INBOUND_DIRECTION;
String _interface = "interface";
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
RegistryResponseType response = new RegistryResponseType();
response.setStatus("Success");
NhinTargetSystemType target = new NhinTargetSystemType();
LogEventRequestType result = instance.transformResponseToAuditMsg(response, assertion, target, direction, _interface, false);
assertNotNull(result);
assertEquals(_interface, result.getInterface());
assertEquals(direction, result.getDirection());
}
/**
* Test of transformRequestToAuditMsg method, of class XDRTransforms.
*/
@Test
public void testTransformRequestToAuditMsg_XDS_null() {
System.out.println("transformRequestToAuditMsg");
ProvideAndRegisterDocumentSetRequestType request = null;
AssertionType assertion = null;
String direction = "";
String _interface = "";
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
LogEventRequestType expResult = null;
LogEventRequestType result = instance.transformRequestToAuditMsg(request, assertion, null, direction, _interface);
assertNull(result);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
}
@Test
public void testTransformRequestToAuditMsg_XDS_empty() {
System.out.println("transformRequestToAuditMsg");
ProvideAndRegisterDocumentSetRequestType request = new ProvideAndRegisterDocumentSetRequestType();
AssertionType assertion = createAssertion();
String direction = "";
String _interface = "";
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
NhinTargetSystemType target = new NhinTargetSystemType();
LogEventRequestType result = instance.transformRequestToAuditMsg(request, assertion, target, direction, _interface);
assertNotNull(result);
// TODO review the generated test code and remove the default call to fail.
}
@Test
public void testTransformRequestToAuditMsg_XDS_NotEmpty() {
System.out.println("transformRequestToAuditMsg");
ProvideAndRegisterDocumentSetRequestType request = new XDRMessageHelper().getSampleMessage();
AssertionType assertion = createAssertion();
String direction = NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION;
String _interface = NhincConstants.AUDIT_LOG_NHIN_INTERFACE;
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
NhinTargetSystemType target = createNhinTargetSystem(CONST_HCID);
LogEventRequestType result = instance.transformRequestToAuditMsg(request, assertion, target, direction, _interface);
assertNotNull(result);
assertNotNull(result.getAuditMessage());
assertNotNull(result.getAuditMessage().getAuditSourceIdentification());
assertNotNull(result.getAuditMessage().getActiveParticipant());
assertNotNull(result.getAuditMessage().getAuditSourceIdentification());
assertEquals(1, result.getAuditMessage().getActiveParticipant().size());
assertEquals(1, result.getAuditMessage().getActiveParticipant().size());
assertEquals(1, result.getAuditMessage().getAuditSourceIdentification().size());
assertEquals(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, result.getDirection());
assertEquals(_interface, result.getInterface());
assertEquals(CONST_USER_NAME, result.getAuditMessage().getActiveParticipant().get(0).getUserID());
assertNotNull(result.getAuditMessage());
assertNotNull(result.getAuditMessage().getAuditSourceIdentification());
assertEquals(CONST_HCID, result.getAuditMessage().getAuditSourceIdentification().get(0).getAuditSourceID());
assertEquals(CONST_HCID, result.getAuditMessage().getAuditSourceIdentification().get(0)
.getAuditEnterpriseSiteID());
// TODO review the generated test code and remove the default call to fail.
}
@Test
public void testTransformProxyRequestToAuditMsg_XDS_null() {
System.out.println("transformRequestToAuditMsg");
gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType request = null;
AssertionType assertion = null;
String direction = "";
String _interface = "";
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
NhinTargetSystemType target = new NhinTargetSystemType();
LogEventRequestType expResult = null;
LogEventRequestType result = instance.transformRequestToAuditMsg(request, assertion, target, direction, _interface);
assertNull(result);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
}
@Test
public void testTransformProxyRequestToAuditMsg_XDS_empty() {
System.out.println("transformRequestToAuditMsg");
ProvideAndRegisterDocumentSetRequestType request = new ProvideAndRegisterDocumentSetRequestType();
gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType proxyRequest = new gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType();
proxyRequest.setProvideAndRegisterDocumentSetRequest(request);
AssertionType assertion = createAssertion();
String direction = "";
String _interface = "";
NhinTargetSystemType target = new NhinTargetSystemType();
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
LogEventRequestType result = instance
.transformRequestToAuditMsg(proxyRequest, assertion, target, direction, _interface);
assertNotNull(result);
// TODO review the generated test code and remove the default call to fail.
}
@Test
public void testTransformProxyRequestToAuditMsg_XDS_NotEmpty() {
System.out.println("transformRequestToAuditMsg");
ProvideAndRegisterDocumentSetRequestType request = new XDRMessageHelper().getSampleMessage();
gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType proxyRequest = new gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType();
proxyRequest.setProvideAndRegisterDocumentSetRequest(request);
AssertionType assertion = createAssertion();
String direction = NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION;
String _interface = NhincConstants.AUDIT_LOG_NHIN_INTERFACE;
NhinTargetSystemType target = createNhinTargetSystem(CONST_HCID);
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
LogEventRequestType result = instance
.transformRequestToAuditMsg(proxyRequest, assertion, target, direction, _interface);
assertNotNull(result);
assertNotNull(result.getAuditMessage());
assertNotNull(result.getAuditMessage().getAuditSourceIdentification());
assertNotNull(result.getAuditMessage().getActiveParticipant());
assertNotNull(result.getAuditMessage().getAuditSourceIdentification());
assertEquals(1, result.getAuditMessage().getActiveParticipant().size());
assertEquals(1, result.getAuditMessage().getActiveParticipant().size());
assertEquals(1, result.getAuditMessage().getAuditSourceIdentification().size());
assertEquals(NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, result.getDirection());
assertEquals(_interface, result.getInterface());
assertEquals(CONST_USER_NAME, result.getAuditMessage().getActiveParticipant().get(0).getUserID());
assertNotNull(result.getAuditMessage());
assertNotNull(result.getAuditMessage().getAuditSourceIdentification());
assertEquals(CONST_HCID, result.getAuditMessage().getAuditSourceIdentification().get(0).getAuditSourceID());
assertEquals(CONST_HCID, result.getAuditMessage().getAuditSourceIdentification().get(0)
.getAuditEnterpriseSiteID());
// TODO review the generated test code and remove the default call to fail.
}
@Test
public void testTransformEntityRequestToAuditMsg_XDS_null() {
System.out.println("transformRequestToAuditMsg");
gov.hhs.fha.nhinc.common.nhinccommonproxy.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType request = null;
AssertionType assertion = null;
String direction = "";
String _interface = "";
NhinTargetSystemType target = new NhinTargetSystemType();
XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
LogEventRequestType expResult = null;
LogEventRequestType result = instance.transformRequestToAuditMsg(request, assertion, target, direction, _interface);
assertNull(result);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
}
/*
* @Test public void testTransformEntityRequestToAuditMsg_XDS_empty() {
*
* System.out.println("transformRequestToAuditMsg"); ProvideAndRegisterDocumentSetRequestType request = new
* ProvideAndRegisterDocumentSetRequestType();
* gov.hhs.fha.nhinc.common.nhinccommonentity.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType
* entityRequest = new
* gov.hhs.fha.nhinc.common.nhinccommonentity.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType();
* entityRequest.setProvideAndRegisterDocumentSetRequest(request);
*
* AssertionType assertion = createAssertion(); String direction = ""; String _interface = ""; XDRTransforms
* instance = createTransformsClass_OverrideRequiredFields(); LogEventRequestType expResult = new
* LogEventRequestType(); LogEventRequestType result = instance.transformRequestToAuditMsg(entityRequest, assertion,
* direction, _interface);
*
* assertNotNull(result); // TODO review the generated test code and remove the default call to fail.
*
* }
*
* @Test public void testTransformEntityRequestToAuditMsg_XDS_NotEmpty() {
*
* System.out.println("transformRequestToAuditMsg"); ProvideAndRegisterDocumentSetRequestType request = new
* XDRMessageHelper().getSampleMessage();
* gov.hhs.fha.nhinc.common.nhinccommonentity.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType
* entityRequest = new
* gov.hhs.fha.nhinc.common.nhinccommonentity.RespondingGatewayProvideAndRegisterDocumentSetSecuredRequestType();
* entityRequest.setProvideAndRegisterDocumentSetRequest(request);
*
* AssertionType assertion = createAssertion(); String direction = NhincConstants.AUDIT_LOG_INBOUND_DIRECTION;
* String _interface = "interface"; XDRTransforms instance = createTransformsClass_OverrideRequiredFields();
* LogEventRequestType expResult = new LogEventRequestType(); LogEventRequestType result =
* instance.transformRequestToAuditMsg(entityRequest, assertion, direction, _interface);
*
* assertNotNull(result); assertNotNull(result.getAuditMessage());
* assertNotNull(result.getAuditMessage().getAuditSourceIdentification());
* assertNotNull(result.getAuditMessage().getActiveParticipant());
* assertNotNull(result.getAuditMessage().getAuditSourceIdentification());
*
* assertEquals(1,result.getAuditMessage().getActiveParticipant().size());
*
* assertEquals(1, result.getAuditMessage().getActiveParticipant().size()); assertEquals(1,
* result.getAuditMessage().getAuditSourceIdentification().size());
*
* assertEquals(NhincConstants.AUDIT_LOG_INBOUND_DIRECTION, result.getDirection()); assertEquals(_interface,
* result.getInterface());
*
* assertEquals(CONST_USER_NAME,result.getAuditMessage().getActiveParticipant().get(0).getUserID());
*
* assertNotNull(result.getAuditMessage()); assertNotNull(result.getAuditMessage().getAuditSourceIdentification());
*
* assertEquals(CONST_HCID, result.getAuditMessage().getAuditSourceIdentification().get(0).getAuditSourceID());
* assertEquals(CONST_HC_NAME,
* result.getAuditMessage().getAuditSourceIdentification().get(0).getAuditEnterpriseSiteID()); // TODO review the
* generated test code and remove the default call to fail.
*
* }
*/
@Test
public void testAreRequiredXDSfieldsNull_empty() {
System.out.println("areRequiredXDSfieldsNull_empty");
ProvideAndRegisterDocumentSetRequestType body = new ProvideAndRegisterDocumentSetRequestType();
AssertionType assertion = new AssertionType();
XDRTransforms instance = createTransformsClass_OverrideUserTypeCheck();
boolean expResult = true;
boolean result = instance.areRequiredXDSfieldsNull(body, assertion);
assertEquals(expResult, result);
}
@Test
public void testAreRequiredXDSfieldsNull_null() {
System.out.println("areRequiredXDSfieldsNull_null");
ProvideAndRegisterDocumentSetRequestType body = null;
AssertionType assertion = new AssertionType();
XDRTransforms instance = createTransformsClass_OverrideUserTypeCheck();
boolean expResult = true;
boolean result = instance.areRequiredXDSfieldsNull(body, assertion);
assertEquals(expResult, result);
}
/**
* Test of areRequiredUserTypeFieldsNull method, of class XDRTransforms.
*/
@Test
public void testAreRequiredUserTypeFieldsNull_empty() {
System.out.println("areRequiredUserTypeFieldsNull");
AssertionType oAssertion = new AssertionType();
XDRTransforms instance = createTransformsClass();
boolean expResult = true;
boolean result = instance.areRequiredUserTypeFieldsNull(oAssertion);
assertEquals(expResult, result);
}
@Test
public void testAreRequiredUserTypeFieldsNull_null() {
System.out.println("areRequiredUserTypeFieldsNull");
AssertionType oAssertion = new AssertionType();
XDRTransforms instance = createTransformsClass();
boolean expResult = true;
boolean result = instance.areRequiredUserTypeFieldsNull(oAssertion);
assertEquals(expResult, result);
}
@Test
public void testAreRequiredUserTypeFieldsNull_NotEmpty() {
System.out.println("areRequiredUserTypeFieldsNull");
AssertionType assertion = createAssertion();
XDRTransforms instance = createTransformsClass();
boolean expResult = false;
boolean result = instance.areRequiredUserTypeFieldsNull(assertion);
assertEquals(expResult, result);
}
@Test
public void testAreRequiredResponseFieldsNull_Null() {
System.out.println("testAreRequiredResponseFieldsNull_Null");
XDRTransforms instance = createTransformsClass_OverrideUserTypeCheck();
AssertionType assertion = createAssertion();
boolean expResult = true;
boolean result = instance.areRequiredResponseFieldsNull(null, assertion);
assertEquals(expResult, result);
}
@Test
public void testAreRequiredResponseFieldsNull_Empty() {
System.out.println("testAreRequiredResponseFieldsNull_Empty");
XDRTransforms instance = createTransformsClass_OverrideUserTypeCheck();
AssertionType assertion = createAssertion();
boolean expResult = true;
boolean result = instance.areRequiredResponseFieldsNull(new RegistryResponseType(), assertion);
assertEquals(expResult, result);
}
@Test
public void testAreRequiredResponseFieldsNull_NotEmpty() {
System.out.println("testAreRequiredResponseFieldsNull_NotEmpty");
XDRTransforms instance = createTransformsClass_OverrideUserTypeCheck();
AssertionType assertion = createAssertion();
RegistryResponseType response = new RegistryResponseType();
response.setStatus("Success");
boolean expResult = false;
boolean result = instance.areRequiredResponseFieldsNull(response, assertion);
assertEquals(expResult, result);
}
private XDRTransforms createTransformsClass() {
// TestHelper helper = new TestHelper();
XDRTransforms result = new XDRTransforms();
return result;
}
private XDRTransforms createTransformsClass_OverrideUserTypeCheck() {
// TestHelper helper = new TestHelper();
XDRTransforms result = new XDRTransforms() {
@Override
public boolean areRequiredUserTypeFieldsNull(AssertionType oAssertion) {
return false;
}
};
return result;
}
private XDRTransforms createTransformsClass_OverrideRequiredFields() {
// TestHelper helper = new TestHelper();
XDRTransforms result = new XDRTransforms() {
@Override
public boolean areRequiredUserTypeFieldsNull(AssertionType oAssertion) {
return false;
}
@Override
protected boolean areRequiredXDSfieldsNull(ProvideAndRegisterDocumentSetRequestType body,
AssertionType assertion) {
return false;
}
@Override
protected boolean areRequiredResponseFieldsNull(RegistryResponseType response, AssertionType assertion) {
return false;
}
};
return result;
}
private AssertionType createAssertion() {
return new XDRMessageHelper().createAssertion(CONST_HCID);
}
private NhinTargetSystemType createNhinTargetSystem(String hcid) {
return new XDRMessageHelper().createNhinTargetSystem(hcid);
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002-2010 Oracle. All rights reserved.
*
* $Id: TwoPCTest.java,v 1.15 2010/01/04 15:51:07 cwl Exp $
*/
package com.sleepycat.je.txn;
import java.io.File;
import javax.transaction.xa.XAResource;
import junit.framework.TestCase;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.Transaction;
import com.sleepycat.je.TransactionStats;
import com.sleepycat.je.XAEnvironment;
import com.sleepycat.je.log.FileManager;
import com.sleepycat.je.log.LogUtils.XidImpl;
import com.sleepycat.je.util.StringDbt;
import com.sleepycat.je.util.TestUtils;
/*
* Simple 2PC transaction testing.
*/
public class TwoPCTest extends TestCase {
private final File envHome;
private XAEnvironment env;
private Database db;
public TwoPCTest() {
envHome = new File(System.getProperty(TestUtils.DEST_DIR));
}
@Override
public void setUp()
throws DatabaseException {
TestUtils.removeFiles("Setup", envHome, FileManager.JE_SUFFIX);
EnvironmentConfig envConfig = TestUtils.initEnvConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
env = new XAEnvironment(envHome, envConfig);
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setTransactional(true);
dbConfig.setAllowCreate(true);
db = env.openDatabase(null, "foo", dbConfig);
}
@Override
public void tearDown()
throws DatabaseException {
db.close();
env.close();
TestUtils.removeFiles("TearDown", envHome, FileManager.JE_SUFFIX);
}
/**
* Basic Two Phase Commit calls.
*/
public void testBasic2PC() {
try {
TransactionStats stats =
env.getTransactionStats(TestUtils.FAST_STATS);
int numBegins = 2; // 1 for setting up XA env and 1 for open db
int numCommits = 2;
int numXAPrepares = 0;
int numXACommits = 0;
assertEquals(numBegins, stats.getNBegins());
assertEquals(numCommits, stats.getNCommits());
assertEquals(numXAPrepares, stats.getNXAPrepares());
assertEquals(numXACommits, stats.getNXACommits());
Transaction txn = env.beginTransaction(null, null);
stats = env.getTransactionStats(TestUtils.FAST_STATS);
numBegins++;
assertEquals(numBegins, stats.getNBegins());
assertEquals(numCommits, stats.getNCommits());
assertEquals(numXAPrepares, stats.getNXAPrepares());
assertEquals(numXACommits, stats.getNXACommits());
assertEquals(1, stats.getNActive());
XidImpl xid = new XidImpl(1, "TwoPCTest1".getBytes(), null);
env.setXATransaction(xid, txn);
stats = env.getTransactionStats(TestUtils.FAST_STATS);
assertEquals(numBegins, stats.getNBegins());
assertEquals(numCommits, stats.getNCommits());
assertEquals(numXAPrepares, stats.getNXAPrepares());
assertEquals(numXACommits, stats.getNXACommits());
assertEquals(1, stats.getNActive());
StringDbt key = new StringDbt("key");
StringDbt data = new StringDbt("data");
db.put(txn, key, data);
stats = env.getTransactionStats(TestUtils.FAST_STATS);
assertEquals(numBegins, stats.getNBegins());
assertEquals(numCommits, stats.getNCommits());
assertEquals(numXAPrepares, stats.getNXAPrepares());
assertEquals(numXACommits, stats.getNXACommits());
assertEquals(1, stats.getNActive());
env.prepare(xid);
numXAPrepares++;
stats = env.getTransactionStats(TestUtils.FAST_STATS);
assertEquals(numBegins, stats.getNBegins());
assertEquals(numCommits, stats.getNCommits());
assertEquals(numXAPrepares, stats.getNXAPrepares());
assertEquals(numXACommits, stats.getNXACommits());
assertEquals(1, stats.getNActive());
env.commit(xid, false);
numCommits++;
numXACommits++;
stats = env.getTransactionStats(TestUtils.FAST_STATS);
assertEquals(numBegins, stats.getNBegins());
assertEquals(numCommits, stats.getNCommits());
assertEquals(numXAPrepares, stats.getNXAPrepares());
assertEquals(numXACommits, stats.getNXACommits());
assertEquals(0, stats.getNActive());
} catch (Exception E) {
System.out.println("caught " + E);
}
}
/**
* Basic readonly-prepare.
*/
public void testROPrepare() {
try {
Transaction txn = env.beginTransaction(null, null);
XidImpl xid = new XidImpl(1, "TwoPCTest1".getBytes(), null);
env.setXATransaction(xid, txn);
assertEquals(XAResource.XA_RDONLY, env.prepare(xid));
} catch (Exception E) {
System.out.println("caught " + E);
}
}
/**
* Test calling prepare twice (should throw exception).
*/
public void testTwicePreparedTransaction()
throws Throwable {
Transaction txn = env.beginTransaction(null, null);
XidImpl xid = new XidImpl(1, "TwoPCTest2".getBytes(), null);
env.setXATransaction(xid, txn);
StringDbt key = new StringDbt("key");
StringDbt data = new StringDbt("data");
db.put(txn, key, data);
try {
env.prepare(xid);
env.prepare(xid);
fail("should not be able to prepare twice");
} catch (Exception E) {
env.commit(xid, false);
}
}
/**
* Test calling rollback(xid) on an unregistered xa txn.
*/
public void testRollbackNonExistent()
throws Throwable {
Transaction txn = env.beginTransaction(null, null);
StringDbt key = new StringDbt("key");
StringDbt data = new StringDbt("data");
db.put(txn, key, data);
XidImpl xid = new XidImpl(1, "TwoPCTest2".getBytes(), null);
try {
env.rollback(xid);
fail("should not be able to call rollback on an unknown xid");
} catch (Exception E) {
}
txn.abort();
}
/**
* Test calling commit(xid) on an unregistered xa txn.
*/
public void testCommitNonExistent()
throws Throwable {
Transaction txn = env.beginTransaction(null, null);
StringDbt key = new StringDbt("key");
StringDbt data = new StringDbt("data");
db.put(txn, key, data);
XidImpl xid = new XidImpl(1, "TwoPCTest2".getBytes(), null);
try {
env.commit(xid, false);
fail("should not be able to call commit on an unknown xid");
} catch (Exception E) {
}
txn.abort();
}
}
| |
/*
* Copyright 2015 The Closure Compiler 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 com.google.javascript.jscomp;
import com.google.common.collect.ImmutableList;
/** Unit tests for {@link InlineAliases}. */
public class InlineAliasesTest extends Es6CompilerTestCase {
@Override
protected CompilerPass getProcessor(Compiler compiler) {
return new InlineAliases(compiler);
}
void testGoogModules(ImmutableList<SourceFile> inputs, ImmutableList<SourceFile> expecteds) {
enableClosurePass();
enableRewriteClosureCode();
test(inputs, expecteds);
}
public void testRewriteGoogModuleAliases1() {
testGoogModules(
ImmutableList.of(
SourceFile.fromCode("A", LINE_JOINER.join(
"goog.module('base');",
"",
"/** @constructor */ var Base = function() {}",
"exports = Base;")),
SourceFile.fromCode("B", LINE_JOINER.join(
"goog.module('leaf');",
"",
"var Base = goog.require('base');",
"exports = /** @constructor @extends {Base} */ function Foo() {}"))),
ImmutableList.of(
SourceFile.fromCode("A", LINE_JOINER.join(
"/** @const */ var $jscomp={}; /** @const */ $jscomp.scope={};",
"/** @constructor */ $jscomp.scope.Base = function(){};",
"/** @const */ var base = $jscomp.scope.Base;")),
SourceFile.fromCode("B", LINE_JOINER.join(
"/** @const */ var leaf =",
" /** @constructor @extends {$jscomp.scope.Base} */ function Foo(){}"))));
}
public void testRewriteGoogModuleAliases2() {
testGoogModules(
ImmutableList.of(
SourceFile.fromCode("A", LINE_JOINER.join(
"goog.module('ns.base');",
"",
"/** @constructor */ var Base = function() {}",
"exports = Base;")),
SourceFile.fromCode("B", LINE_JOINER.join(
"goog.module('leaf');",
"",
"var Base = goog.require('ns.base');",
"exports = /** @constructor @extends {Base} */ function Foo() {}"))),
ImmutableList.of(
SourceFile.fromCode("A", LINE_JOINER.join(
"/** @const */ var $jscomp={}; /** @const */ $jscomp.scope={};",
" /** @const */ var ns = {}; ",
"/** @constructor */ $jscomp.scope.Base = function(){};",
"/** @const */ ns.base = $jscomp.scope.Base;")),
SourceFile.fromCode("B", LINE_JOINER.join(
"/** @const */ var leaf =",
" /** @constructor @extends {$jscomp.scope.Base} */function Foo(){}"))));
}
public void testRewriteGoogModuleAliases3() {
testGoogModules(
ImmutableList.of(
SourceFile.fromCode("A", LINE_JOINER.join(
"goog.module('ns.base');",
"",
"/** @constructor */ var Base = function() {};",
"/** @constructor */ Base.Foo = function(){};",
"exports = Base;")),
SourceFile.fromCode("B", LINE_JOINER.join(
"goog.module('leaf');",
"",
"var Base = goog.require('ns.base');",
"exports = /** @constructor @extends {Base.Foo} */ function Foo() {}"))),
ImmutableList.of(
SourceFile.fromCode("A", LINE_JOINER.join(
"/** @const */ var $jscomp={}; /** @const */ $jscomp.scope={};",
"/** @const */ var ns = {}; ",
"/** @constructor */ $jscomp.scope.Base = function(){}",
"/** @constructor */ $jscomp.scope.Base.Foo = function(){};",
"/** @const */ ns.base = $jscomp.scope.Base;")),
SourceFile.fromCode("B", LINE_JOINER.join(
" /**@const*/ var leaf =",
" /**@constructor @extends {$jscomp.scope.Base.Foo}*/function Foo(){}"))));
}
public void testRewriteGoogModuleAliases4() {
testGoogModules(
ImmutableList.of(
SourceFile.fromCode("A", LINE_JOINER.join(
"goog.module('ns.base');",
"",
"/** @constructor */ var Base = function() {}",
"exports = Base;")),
SourceFile.fromCode("B", LINE_JOINER.join(
"goog.module('leaf');",
"",
"var Base = goog.require('ns.base');",
"exports = new Base;"))),
ImmutableList.of(
SourceFile.fromCode("A", LINE_JOINER.join(
"/** @const */ var $jscomp={}; /** @const */ $jscomp.scope={};",
"/** @const */ var ns = {}; ",
"/** @constructor */ $jscomp.scope.Base = function(){};",
"/** @const */ ns.base = $jscomp.scope.Base;")),
SourceFile.fromCode("B",
"/** @const */ var leaf = new $jscomp.scope.Base;")));
}
public void testSimpleAliasInJSDoc() {
test("function Foo(){}; var /** @const */ alias = Foo; /** @type {alias} */ var x;",
"function Foo(){}; var /** @const */ alias = Foo; /** @type {Foo} */ var x;");
test(
LINE_JOINER.join(
"var ns={};",
"function Foo(){};",
"/** @const */ ns.alias = Foo;",
"/** @type {ns.alias} */ var x;"),
LINE_JOINER.join(
"var ns={};",
"function Foo(){};",
"/** @const */ ns.alias = Foo;",
"/** @type {Foo} */ var x;"));
test(
LINE_JOINER.join(
"var ns={};",
"function Foo(){};",
"/** @const */ ns.alias = Foo;",
"/** @type {ns.alias.Subfoo} */ var x;"),
LINE_JOINER.join(
"var ns={};",
"function Foo(){};",
"/** @const */ ns.alias = Foo;",
"/** @type {Foo.Subfoo} */ var x;"));
}
public void testSimpleAliasInCode() {
test("function Foo(){}; var /** @const */ alias = Foo; var x = new alias;",
"function Foo(){}; var /** @const */ alias = Foo; var x = new Foo;");
test("var ns={}; function Foo(){}; /** @const */ ns.alias = Foo; var x = new ns.alias;",
"var ns={}; function Foo(){}; /** @const */ ns.alias = Foo; var x = new Foo;");
test("var ns={}; function Foo(){}; /** @const */ ns.alias = Foo; var x = new ns.alias.Subfoo;",
"var ns={}; function Foo(){}; /** @const */ ns.alias = Foo; var x = new Foo.Subfoo;");
}
public void testAliasQualifiedName() {
test(
LINE_JOINER.join(
"var ns = {};",
"ns.Foo = function(){};",
"/** @const */ ns.alias = ns.Foo;",
"/** @type {ns.alias.Subfoo} */ var x;"),
LINE_JOINER.join(
"var ns = {};",
"ns.Foo = function(){};",
"/** @const */ ns.alias = ns.Foo;",
"/** @type {ns.Foo.Subfoo} */ var x;"));
test(
LINE_JOINER.join(
"var ns = {};",
"ns.Foo = function(){};",
"/** @const */ ns.alias = ns.Foo;",
"var x = new ns.alias.Subfoo;"),
LINE_JOINER.join(
"var ns = {};",
"ns.Foo = function(){};",
"/** @const */ ns.alias = ns.Foo;",
"var x = new ns.Foo.Subfoo;"));
}
public void testTransitiveAliases() {
test(
LINE_JOINER.join(
"/** @const */ var ns = {};",
"/** @constructor */ ns.Foo = function() {};",
"/** @constructor */ ns.Foo.Bar = function() {};",
"var /** @const */ alias = ns.Foo;",
"var /** @const */ alias2 = alias.Bar;",
"var x = new alias2"),
LINE_JOINER.join(
"/** @const */ var ns = {};",
"/** @constructor */ ns.Foo = function() {};",
"/** @constructor */ ns.Foo.Bar = function() {};",
"var /** @const */ alias = ns.Foo;",
"var /** @const */ alias2 = ns.Foo.Bar;",
"var x = new ns.Foo.Bar;"));
}
public void testAliasedEnums() {
test(
"/** @enum {number} */ var E = { A : 1 }; var /** @const */ alias = E.A; alias;",
"/** @enum {number} */ var E = { A : 1 }; var /** @const */ alias = E.A; E.A;");
}
public void testIncorrectConstAnnoataionDoesntCrash() {
testSame("var x = 0; var /** @const */ alias = x; alias = 5; use(alias);");
testSame("var x = 0; var ns={}; /** @const */ ns.alias = x; ns.alias = 5; use(ns.alias);");
}
public void testRedefinedAliasesNotRenamed() {
testSame("var x = 0; var /** @const */ alias = x; x = 5; use(alias);");
}
public void testDefinesAreNotInlined() {
testSame("var ns = {}; var /** @define {boolean} */ alias = ns.Foo; var x = new alias;");
}
public void testPrivateVariablesAreNotInlined() {
testSame("/** @private */ var x = 0; var /** @const */ alias = x; var y = alias;");
testSame("var x_ = 0; var /** @const */ alias = x_; var y = alias;");
}
public void testShadowedAliasesNotRenamed() {
testSame(
LINE_JOINER.join(
"var ns = {};",
"ns.Foo = function(){};",
"var /** @const */ alias = ns.Foo;",
"function f(alias) {",
" var x = alias",
"}"));
testSame(
LINE_JOINER.join(
"var ns = {};",
"ns.Foo = function(){};",
"var /** @const */ alias = ns.Foo;",
"function f() {",
" var /** @const */ alias = 5;",
" var x = alias",
"}"));
testSame(
LINE_JOINER.join(
"/** @const */",
"var x = y;",
"function f() {",
" var x = 123;",
" function g() {",
" return x;",
" }",
"}"));
}
}
| |
package com.wx.demo.svg;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
import com.wx.demo.R;
import java.util.ArrayList;
import java.util.List;
/**
* PathView is a View that animates paths.
*/
@SuppressWarnings("unused")
public class PathView extends View implements SvgUtils.AnimationStepListener {
/**
* Logging tag.
*/
public static final String LOG_TAG = "PathView";
/**
* The paint for the path.
*/
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
/**
* Utils to catch the paths from the svg.
*/
private final SvgUtils svgUtils = new SvgUtils(paint);
/**
* All the paths provided to the view. Both from Path and Svg.
*/
private List<SvgUtils.SvgPath> paths = new ArrayList<>();
/**
* This is a lock before the view is redrawn
* or resided it must be synchronized with this object.
*/
private final Object mSvgLock = new Object();
/**
* Thread for working with the object above.
*/
private Thread mLoader;
/**
* The svg image from the raw directory.
*/
private int svgResourceId;
/**
* Object that builds the animation for the path.
*/
private AnimatorBuilder animatorBuilder;
/**
* Object that builds the animation set for the path.
*/
private AnimatorSetBuilder animatorSetBuilder;
/**
* The progress of the drawing.
*/
private float progress = 0f;
/**
* If the used colors are from the svg or from the set color.
*/
private boolean naturalColors;
/**
* If the view is filled with its natural colors after path drawing.
*/
private boolean fillAfter;
/**
* The width of the view.
*/
private int width;
/**
* The height of the view.
*/
private int height;
/**
* Default constructor.
*
* @param context The Context of the application.
*/
public PathView(Context context) {
this(context, null);
}
/**
* Default constructor.
*
* @param context The Context of the application.
* @param attrs attributes provided from the resources.
*/
public PathView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Default constructor.
*
* @param context The Context of the application.
* @param attrs attributes provided from the resources.
* @param defStyle Default style.
*/
public PathView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
getFromAttributes(context, attrs);
}
/**
* Get all the fields from the attributes .
*
* @param context The Context of the application.
* @param attrs attributes provided from the resources.
*/
private void getFromAttributes(Context context, AttributeSet attrs) {
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PathView);
try {
if (a != null) {
paint.setColor(a.getColor(R.styleable.PathView_pathColor, 0xff00ff00));
paint.setStrokeWidth(a.getFloat(R.styleable.PathView_pathWidth, 8.0f));
svgResourceId = a.getResourceId(R.styleable.PathView_svg, 0);
}
} finally {
if (a != null) {
a.recycle();
}
}
}
/**
* Set paths to be drawn and animated.
*
* @param paths - Paths that can be drawn.
*/
public void setPaths(final List<Path> paths) {
for (Path path : paths) {
this.paths.add(new SvgUtils.SvgPath(path, paint));
}
synchronized (mSvgLock) {
updatePathsPhaseLocked();
}
}
/**
* Set path to be drawn and animated.
*
* @param path - Paths that can be drawn.
*/
public void setPath(final Path path) {
paths.add(new SvgUtils.SvgPath(path, paint));
synchronized (mSvgLock) {
updatePathsPhaseLocked();
}
}
/**
* Animate this property. It is the percentage of the path that is drawn.
* It must be [0,1].
*
* @param percentage float the percentage of the path.
*/
public void setPercentage(float percentage) {
if (percentage < 0.0f || percentage > 1.0f) {
throw new IllegalArgumentException("setPercentage not between 0.0f and 1.0f");
}
progress = percentage;
synchronized (mSvgLock) {
updatePathsPhaseLocked();
}
invalidate();
}
/**
* This refreshes the paths before draw and resize.
*/
private void updatePathsPhaseLocked() {
final int count = paths.size();
for (int i = 0; i < count; i++) {
SvgUtils.SvgPath svgPath = paths.get(i);
svgPath.path.reset();
svgPath.measure.getSegment(0.0f, svgPath.length * progress, svgPath.path, true);
// Required only for Android 4.4 and earlier
svgPath.path.rLineTo(0.0f, 0.0f);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
synchronized (mSvgLock) {
canvas.save();
canvas.translate(getPaddingLeft(), getPaddingTop());
final int count = paths.size();
for (int i = 0; i < count; i++) {
final SvgUtils.SvgPath svgPath = paths.get(i);
final Path path = svgPath.path;
final Paint paint1 = naturalColors ? svgPath.paint : paint;
canvas.drawPath(path, paint1);
}
fillAfter(canvas);
canvas.restore();
}
}
/**
* If there is svg , the user called setFillAfter(true) and the progress is finished.
*
* @param canvas Draw to this canvas.
*/
private void fillAfter(final Canvas canvas) {
if (svgResourceId != 0 && fillAfter && progress == 1f) {
svgUtils.drawSvgAfter(canvas, width, height);
}
}
@Override
protected void onSizeChanged(final int w, final int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mLoader != null) {
try {
mLoader.join();
} catch (InterruptedException e) {
Log.e(LOG_TAG, "Unexpected error", e);
}
}
if (svgResourceId != 0) {
mLoader = new Thread(new Runnable() {
@Override
public void run() {
svgUtils.load(getContext(), svgResourceId);
synchronized (mSvgLock) {
width = w - getPaddingLeft() - getPaddingRight();
height = h - getPaddingTop() - getPaddingBottom();
paths = svgUtils.getPathsForViewport(width, height);
updatePathsPhaseLocked();
}
}
}, "SVG Loader");
mLoader.start();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (svgResourceId != 0) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
return;
}
int desiredWidth = 0;
int desiredHeight = 0;
final float strokeWidth = paint.getStrokeWidth() / 2;
for (SvgUtils.SvgPath path : paths) {
desiredWidth += path.bounds.left + path.bounds.width() + strokeWidth;
desiredHeight += path.bounds.top + path.bounds.height() + strokeWidth;
}
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(widthMeasureSpec);
int measuredWidth, measuredHeight;
if (widthMode == MeasureSpec.AT_MOST) {
measuredWidth = desiredWidth;
} else {
measuredWidth = widthSize;
}
if (heightMode == MeasureSpec.AT_MOST) {
measuredHeight = desiredHeight;
} else {
measuredHeight = heightSize;
}
setMeasuredDimension(measuredWidth, measuredHeight);
}
/**
* If the real svg need to be drawn after the path animation.
*
* @param fillAfter - boolean if the view needs to be filled after path animation.
*/
public void setFillAfter(final boolean fillAfter) {
this.fillAfter = fillAfter;
}
/**
* If you want to use the colors from the svg.
*/
public void useNaturalColors() {
naturalColors = true;
}
/**
* Animator for the paths of the view.
*
* @return The AnimatorBuilder to build the animation.
*/
public AnimatorBuilder getPathAnimator() {
if (animatorBuilder == null) {
animatorBuilder = new AnimatorBuilder(this);
}
return animatorBuilder;
}
/**
* AnimatorSet for the paths of the view to be animated one after the other.
*
* @return The AnimatorBuilder to build the animation.
*/
public AnimatorSetBuilder getSequentialPathAnimator() {
if (animatorSetBuilder == null) {
animatorSetBuilder = new AnimatorSetBuilder(this);
}
return animatorSetBuilder;
}
/**
* Get the path color.
*
* @return The color of the paint.
*/
public int getPathColor() {
return paint.getColor();
}
/**
* Set the path color.
*
* @param color -The color to set to the paint.
*/
public void setPathColor(final int color) {
paint.setColor(color);
}
/**
* Get the path width.
*
* @return The width of the paint.
*/
public float getPathWidth() {
return paint.getStrokeWidth();
}
/**
* Set the path width.
*
* @param width - The width of the path.
*/
public void setPathWidth(final float width) {
paint.setStrokeWidth(width);
}
/**
* Get the svg resource id.
*
* @return The svg raw resource id.
*/
public int getSvgResource() {
return svgResourceId;
}
/**
* Set the svg resource id.
*
* @param svgResource - The resource id of the raw svg.
*/
public void setSvgResource(int svgResource) {
svgResourceId = svgResource;
}
/**
* Object for building the animation of the path of this view.
*/
public static class AnimatorBuilder {
/**
* Duration of the animation.
*/
private int duration = 350;
/**
* Interpolator for the time of the animation.
*/
private Interpolator interpolator;
/**
* The delay before the animation.
*/
private int delay = 0;
/**
* ObjectAnimator that constructs the animation.
*/
private final ObjectAnimator anim;
/**
* Listener called before the animation.
*/
private ListenerStart listenerStart;
/**
* Listener after the animation.
*/
private ListenerEnd animationEnd;
/**
* Animation listener.
*/
private PathViewAnimatorListener pathViewAnimatorListener;
/**
* Default constructor.
*
* @param pathView The view that must be animated.
*/
public AnimatorBuilder(final PathView pathView) {
anim = ObjectAnimator.ofFloat(pathView, "percentage", 0.0f, 1.0f);
}
/**
* Set the duration of the animation.
*
* @param duration - The duration of the animation.
* @return AnimatorBuilder.
*/
public AnimatorBuilder duration(final int duration) {
this.duration = duration;
return this;
}
/**
* Set the Interpolator.
*
* @param interpolator - Interpolator.
* @return AnimatorBuilder.
*/
public AnimatorBuilder interpolator(final Interpolator interpolator) {
this.interpolator = interpolator;
return this;
}
/**
* The delay before the animation.
*
* @param delay - int the delay
* @return AnimatorBuilder.
*/
public AnimatorBuilder delay(final int delay) {
this.delay = delay;
return this;
}
/**
* Set a listener before the start of the animation.
*
* @param listenerStart an interface called before the animation
* @return AnimatorBuilder.
*/
public AnimatorBuilder listenerStart(final ListenerStart listenerStart) {
this.listenerStart = listenerStart;
if (pathViewAnimatorListener == null) {
pathViewAnimatorListener = new PathViewAnimatorListener();
anim.addListener(pathViewAnimatorListener);
}
return this;
}
/**
* Set a listener after of the animation.
*
* @param animationEnd an interface called after the animation
* @return AnimatorBuilder.
*/
public AnimatorBuilder listenerEnd(final ListenerEnd animationEnd) {
this.animationEnd = animationEnd;
if (pathViewAnimatorListener == null) {
pathViewAnimatorListener = new PathViewAnimatorListener();
anim.addListener(pathViewAnimatorListener);
}
return this;
}
/**
* Starts the animation.
*/
public void start() {
anim.setDuration(duration);
anim.setInterpolator(interpolator);
anim.setStartDelay(delay);
anim.start();
}
/**
* Animation listener to be able to provide callbacks for the caller.
*/
private class PathViewAnimatorListener implements Animator.AnimatorListener {
@Override
public void onAnimationStart(Animator animation) {
if (listenerStart != null) listenerStart.onAnimationStart();
}
@Override
public void onAnimationEnd(Animator animation) {
if (animationEnd != null) animationEnd.onAnimationEnd();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}
/**
* Called when the animation start.
*/
public interface ListenerStart {
/**
* Called when the path animation start.
*/
void onAnimationStart();
}
/**
* Called when the animation end.
*/
public interface ListenerEnd {
/**
* Called when the path animation end.
*/
void onAnimationEnd();
}
}
@Override
public void onAnimationStep() {
invalidate();
}
/**
* Object for building the sequential animation of the paths of this view.
*/
public static class AnimatorSetBuilder {
/**
* Duration of the animation.
*/
private int duration = 1000;
/**
* Interpolator for the time of the animation.
*/
private Interpolator interpolator;
/**
* The delay before the animation.
*/
private int delay = 0;
/**
* List of ObjectAnimator that constructs the animations of each path.
*/
private final List<Animator> animators = new ArrayList<>();
/**
* Listener called before the animation.
*/
private AnimatorBuilder.ListenerStart listenerStart;
/**
* Listener after the animation.
*/
private AnimatorBuilder.ListenerEnd animationEnd;
/**
* Animation listener.
*/
private PathViewAnimatorListener pathViewAnimatorListener;
/**
* The animator that can animate paths sequentially
*/
private AnimatorSet animatorSet = new AnimatorSet();
/**
* The list of paths to be animated.
*/
private List<SvgUtils.SvgPath> paths;
/**
* Default constructor.
*
* @param pathView The view that must be animated.
*/
public AnimatorSetBuilder(final PathView pathView) {
paths = pathView.paths;
for (SvgUtils.SvgPath path : paths) {
path.setAnimationStepListener(pathView);
ObjectAnimator animation = ObjectAnimator.ofFloat(path, "length", 0.0f, path.getLength());
animators.add(animation);
}
animatorSet.playSequentially(animators);
}
/**
* Sets the duration of the animation. Since the AnimatorSet sets the duration for each
* Animator, we have to divide it by the number of paths.
*
* @param duration - The duration of the animation.
* @return AnimatorSetBuilder.
*/
public AnimatorSetBuilder duration(final int duration) {
this.duration = duration / paths.size();
return this;
}
/**
* Set the Interpolator.
*
* @param interpolator - Interpolator.
* @return AnimatorSetBuilder.
*/
public AnimatorSetBuilder interpolator(final Interpolator interpolator) {
this.interpolator = interpolator;
return this;
}
/**
* The delay before the animation.
*
* @param delay - int the delay
* @return AnimatorSetBuilder.
*/
public AnimatorSetBuilder delay(final int delay) {
this.delay = delay;
return this;
}
/**
* Set a listener before the start of the animation.
*
* @param listenerStart an interface called before the animation
* @return AnimatorSetBuilder.
*/
public AnimatorSetBuilder listenerStart(final AnimatorBuilder.ListenerStart listenerStart) {
this.listenerStart = listenerStart;
if (pathViewAnimatorListener == null) {
pathViewAnimatorListener = new PathViewAnimatorListener();
animatorSet.addListener(pathViewAnimatorListener);
}
return this;
}
/**
* Set a listener after of the animation.
*
* @param animationEnd an interface called after the animation
* @return AnimatorSetBuilder.
*/
public AnimatorSetBuilder listenerEnd(final AnimatorBuilder.ListenerEnd animationEnd) {
this.animationEnd = animationEnd;
if (pathViewAnimatorListener == null) {
pathViewAnimatorListener = new PathViewAnimatorListener();
animatorSet.addListener(pathViewAnimatorListener);
}
return this;
}
/**
* Starts the animation.
*/
public void start() {
resetAllPaths();
animatorSet.cancel();
animatorSet.setDuration(duration);
animatorSet.setInterpolator(interpolator);
animatorSet.setStartDelay(delay);
animatorSet.start();
}
/**
* Sets the length of all the paths to 0.
*/
private void resetAllPaths() {
for (SvgUtils.SvgPath path : paths) {
path.setLength(0);
}
}
/**
* Animation listener to be able to provide callbacks for the caller.
*/
private class PathViewAnimatorListener implements Animator.AnimatorListener {
@Override
public void onAnimationStart(Animator animation) {
if (listenerStart != null) listenerStart.onAnimationStart();
}
@Override
public void onAnimationEnd(Animator animation) {
if (animationEnd != null) animationEnd.onAnimationEnd();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}
}
}
| |
package com.water.wtdrawing;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* WTDrawing
*
* Created by Water Zhang on 11/25/15
*/
public class WTDrawingView extends View {
// Drawing mode
private static final int DRAW = 1;
private static final int ERASER = 2;
// Default config
private static final int DEFAULT_STROKE_COLOR = Color.BLACK;
private static final float DEFAULT_STROKE_WIDTH = 2.0f;
private static final float DEFAULT_ERASER_WIDTH = 20.0f;
Context context;
private boolean initialized;
private Paint drawPaint = new Paint(Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
private Paint eraserPaint = new Paint(Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
private Canvas drawCanvas;
private Bitmap drawBitmap;
private Bitmap undoBitmap;
private RectF dirtyRect;
private WTBezierPath drawPath;
private LinkedList<WTBezierPath> pathArray;
private int drawingMode;
private PointF[] points = new PointF[5];
private int pointIndex;
private int movedPointCount;
private int strokeColor;
/**
* Stroke width, unit(dp)
*/
private float strokeWidth;
/**
* Eraser width, unit(dp)
*/
private float eraserWidth;
public int getStrokeColor() {
return strokeColor;
}
public void setStrokeColor(int strokeColor) {
this.strokeColor = strokeColor;
drawPaint.setColor(this.strokeColor);
}
public float getStrokeWidth() {
return strokeWidth;
}
public void setStrokeWidth(float strokeWidth) {
this.strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, strokeWidth, getResources().getDisplayMetrics());
drawPaint.setStrokeWidth(this.strokeWidth);
}
public float getEraserWidth() {
return eraserWidth;
}
public void setEraserWidth(float eraserWidth) {
this.eraserWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, eraserWidth, getResources().getDisplayMetrics());;
eraserPaint.setStrokeWidth(this.eraserWidth);
}
public void setEraserMode(boolean drawEraser) {
drawingMode = drawEraser ? ERASER : DRAW;
}
public WTDrawingView(Context c, int width, int height) {
this(c, null);
init(width, height);
}
public WTDrawingView(Context c, AttributeSet attrs) {
super(c, attrs);
context = c;
}
/**
* Returns the bitmap of the drawing with the specified background color
*
* @param backgroundColor The background color for the bitmap
* @return The bitmap
*/
public Bitmap getBitmap(int backgroundColor) {
if (drawBitmap != null && !drawBitmap.isRecycled()) {
// create new bitmap
Bitmap bitmap = Bitmap.createBitmap(drawBitmap.getWidth(), drawBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas bitmapCanvas = new Canvas(bitmap);
// draw background if not transparent
if (backgroundColor != 0) {
bitmapCanvas.drawColor(backgroundColor);
}
// draw bitmap
bitmapCanvas.drawBitmap(drawBitmap, 0, 0, null);
return bitmap;
}
return null;
}
/**
* Undo last drawing.
*/
public void undo() {
Paint emptyPaint = new Paint();
emptyPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
drawCanvas.drawPaint(emptyPaint);
if (!pathArray.isEmpty()) {
pathArray.removeLast();
}
for (WTBezierPath path : pathArray) {
drawPaint.setStyle(path.isCircle ? Paint.Style.FILL : Paint.Style.STROKE);
if (path.isEraser) {
drawCanvas.drawPath(path, eraserPaint);
}
else {
drawPaint.setColor(path.strokeColor);
drawPaint.setStrokeWidth(path.strokeWidth);
drawCanvas.drawPath(path, drawPaint);
}
}
// Restore paint
drawPaint.setStrokeWidth(this.strokeWidth);
drawPaint.setColor(this.strokeColor);
eraserPaint.setStrokeWidth(this.eraserWidth);
invalidate();
}
/**
* Clear all drawings.
*/
public void clear() {
Paint emptyPaint = new Paint();
emptyPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
drawCanvas.drawPaint(emptyPaint);
pathArray.clear();
if (drawPath != null) {
drawPath.reset();
}
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
this.touchesBegan(new PointF(event.getX(), event.getY()));
}
else if (event.getAction() == MotionEvent.ACTION_MOVE) {
this.touchesMoved(new PointF(event.getX(),event.getY()));
}
else if (event.getAction() == MotionEvent.ACTION_UP
|| event.getAction() == MotionEvent.ACTION_CANCEL){
this.touchesEnded(new PointF(event.getX(), event.getY()));
}
return true;
}
@Override
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if (initialized) {
canvas.drawBitmap(drawBitmap, 0, 0, null);
}
else {
init(this.getWidth(),this.getHeight());
}
}
private void init(int width, int height) {
if (!initialized) {
pathArray = new LinkedList<WTBezierPath>();
drawingMode = DRAW;
drawBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
drawCanvas = new Canvas(drawBitmap);
setStrokeWidth(DEFAULT_STROKE_WIDTH);
setStrokeColor(DEFAULT_STROKE_COLOR);
setEraserWidth(DEFAULT_ERASER_WIDTH);
drawPaint.setAntiAlias(true);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
eraserPaint.setAntiAlias(true);
eraserPaint.setStyle(Paint.Style.STROKE);
eraserPaint.setStrokeCap(Paint.Cap.ROUND);
eraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
dirtyRect = new RectF();
initialized = true;
}
}
private Paint currentPaint() {
return drawingMode == ERASER ? eraserPaint : drawPaint;
}
private void touchesBegan(PointF p) {
if (drawingMode != DRAW && drawingMode != ERASER) {
drawingMode = DRAW;
}
movedPointCount = 0;
pointIndex = 0;
points[0] = p;
drawPaint.setStyle(Paint.Style.STROKE);
eraserPaint.setStyle(Paint.Style.STROKE);
drawPath = new WTBezierPath();
drawPath.strokeColor = this.strokeColor;
drawPath.strokeWidth = this.strokeWidth;
drawPath.isEraser = drawingMode == ERASER;
}
private void touchesMoved(PointF p) {
movedPointCount++;
pointIndex++;
points[pointIndex] = p;
// We got 5 points here, now we can draw a bezier drawPath,
// use 4 points to draw a bezier,and the last point is cached for next segment.
if (pointIndex == 4) {
points[3] = new PointF((points[2].x + points[4].x) / 2, (points[2].y + points[4].y) / 2);
moveToPoint(points[0]);
addCurveToPoint(points[3], points[1], points[2]);
drawCanvas.drawPath(drawPath, currentPaint());
// Calc dirty rect
float pathWidth = currentPaint().getStrokeWidth();
drawPath.computeBounds(dirtyRect, true);
dirtyRect.left = dirtyRect.left - pathWidth;
dirtyRect.top = dirtyRect.top - pathWidth;
dirtyRect.right = dirtyRect.right + pathWidth;
dirtyRect.bottom = dirtyRect.bottom + pathWidth;
Rect invalidRect = new Rect();
dirtyRect.round(invalidRect);
invalidate(invalidRect);
points[0] = points[3];
points[1] = points[3]; // this is the "magic"
points[2] = points[4];
pointIndex = 2;
}
}
private void touchesEnded(PointF p) {
// Handle if there are no enough points to draw a bezier,
// draw a circle instead.
if (movedPointCount < 3) {
Paint paint = currentPaint();
drawPath.reset();
drawPath.isCircle = true;
drawPath.addCircle(points[0].x, points[0].y, paint.getStrokeWidth(), WTBezierPath.Direction.CW);
paint.setStyle(Paint.Style.FILL);
drawCanvas.drawPath(drawPath, paint);
}
movedPointCount = 0;
pointIndex = 0;
pathArray.add(drawPath);
invalidate();
}
private void moveToPoint(PointF p) {
drawPath.moveTo(p.x, p.y);
}
private void addCurveToPoint(PointF p, PointF controlPoint1, PointF controlPoint2) {
drawPath.cubicTo(controlPoint1.x, controlPoint1.y, controlPoint2.x, controlPoint2.y, p.x, p.y);
}
}
| |
package com.oracle.pts.salesparty.wsclient.generated;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for Telex complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Telex">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ContactPointId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="ContactPointType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Status" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="OwnerTableName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="OwnerTableId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="PrimaryFlag" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="OrigSystemReference" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="LastUpdateDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/>
* <element name="LastUpdatedBy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="CreationDate" type="{http://xmlns.oracle.com/adf/svc/types/}dateTime-Timestamp" minOccurs="0"/>
* <element name="CreatedBy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="LastUpdateLogin" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="ObjectVersionNumber" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="CreatedByModule" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="ContactPointPurpose" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="PrimaryByPurpose" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="StartDate" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/>
* <element name="EndDate" type="{http://xmlns.oracle.com/adf/svc/types/}date-Date" minOccurs="0"/>
* <element name="RelationshipId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="PartyUsageCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="OrigSystem" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TelexNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="OverallPrimaryFlag" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="ContactPreference" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/}ContactPreference" maxOccurs="unbounded" minOccurs="0"/>
* <element name="OriginalSystemReference" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/partyService/}OriginalSystemReference" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Telex", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", propOrder = {
"contactPointId",
"contactPointType",
"status",
"ownerTableName",
"ownerTableId",
"primaryFlag",
"origSystemReference",
"lastUpdateDate",
"lastUpdatedBy",
"creationDate",
"createdBy",
"lastUpdateLogin",
"requestId",
"objectVersionNumber",
"createdByModule",
"contactPointPurpose",
"primaryByPurpose",
"startDate",
"endDate",
"relationshipId",
"partyUsageCode",
"origSystem",
"telexNumber",
"overallPrimaryFlag",
"contactPreference",
"originalSystemReference"
})
public class Telex {
@XmlElement(name = "ContactPointId")
protected Long contactPointId;
@XmlElement(name = "ContactPointType", defaultValue = "TLX")
protected String contactPointType;
@XmlElement(name = "Status")
protected String status;
@XmlElement(name = "OwnerTableName")
protected String ownerTableName;
@XmlElement(name = "OwnerTableId")
protected Long ownerTableId;
@XmlElement(name = "PrimaryFlag")
protected Boolean primaryFlag;
@XmlElementRef(name = "OrigSystemReference", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", type = JAXBElement.class)
protected JAXBElement<String> origSystemReference;
@XmlElement(name = "LastUpdateDate")
protected XMLGregorianCalendar lastUpdateDate;
@XmlElement(name = "LastUpdatedBy")
protected String lastUpdatedBy;
@XmlElement(name = "CreationDate")
protected XMLGregorianCalendar creationDate;
@XmlElement(name = "CreatedBy")
protected String createdBy;
@XmlElementRef(name = "LastUpdateLogin", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", type = JAXBElement.class)
protected JAXBElement<String> lastUpdateLogin;
@XmlElementRef(name = "RequestId", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", type = JAXBElement.class)
protected JAXBElement<Long> requestId;
@XmlElement(name = "ObjectVersionNumber")
protected Integer objectVersionNumber;
@XmlElementRef(name = "CreatedByModule", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", type = JAXBElement.class)
protected JAXBElement<String> createdByModule;
@XmlElementRef(name = "ContactPointPurpose", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", type = JAXBElement.class)
protected JAXBElement<String> contactPointPurpose;
@XmlElementRef(name = "PrimaryByPurpose", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", type = JAXBElement.class)
protected JAXBElement<String> primaryByPurpose;
@XmlElement(name = "StartDate")
protected XMLGregorianCalendar startDate;
@XmlElement(name = "EndDate")
protected XMLGregorianCalendar endDate;
@XmlElementRef(name = "RelationshipId", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", type = JAXBElement.class)
protected JAXBElement<Long> relationshipId;
@XmlElementRef(name = "PartyUsageCode", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", type = JAXBElement.class)
protected JAXBElement<String> partyUsageCode;
@XmlElementRef(name = "OrigSystem", namespace = "http://xmlns.oracle.com/apps/cdm/foundation/parties/contactPointService/", type = JAXBElement.class)
protected JAXBElement<String> origSystem;
@XmlElement(name = "TelexNumber")
protected String telexNumber;
@XmlElement(name = "OverallPrimaryFlag")
protected Boolean overallPrimaryFlag;
@XmlElement(name = "ContactPreference")
protected List<ContactPreference> contactPreference;
@XmlElement(name = "OriginalSystemReference")
protected List<OriginalSystemReference> originalSystemReference;
/**
* Gets the value of the contactPointId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getContactPointId() {
return contactPointId;
}
/**
* Sets the value of the contactPointId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setContactPointId(Long value) {
this.contactPointId = value;
}
/**
* Gets the value of the contactPointType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContactPointType() {
return contactPointType;
}
/**
* Sets the value of the contactPointType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContactPointType(String value) {
this.contactPointType = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStatus(String value) {
this.status = value;
}
/**
* Gets the value of the ownerTableName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOwnerTableName() {
return ownerTableName;
}
/**
* Sets the value of the ownerTableName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOwnerTableName(String value) {
this.ownerTableName = value;
}
/**
* Gets the value of the ownerTableId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getOwnerTableId() {
return ownerTableId;
}
/**
* Sets the value of the ownerTableId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setOwnerTableId(Long value) {
this.ownerTableId = value;
}
/**
* Gets the value of the primaryFlag property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isPrimaryFlag() {
return primaryFlag;
}
/**
* Sets the value of the primaryFlag property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setPrimaryFlag(Boolean value) {
this.primaryFlag = value;
}
/**
* Gets the value of the origSystemReference property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getOrigSystemReference() {
return origSystemReference;
}
/**
* Sets the value of the origSystemReference property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setOrigSystemReference(JAXBElement<String> value) {
this.origSystemReference = ((JAXBElement<String> ) value);
}
/**
* Gets the value of the lastUpdateDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getLastUpdateDate() {
return lastUpdateDate;
}
/**
* Sets the value of the lastUpdateDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setLastUpdateDate(XMLGregorianCalendar value) {
this.lastUpdateDate = value;
}
/**
* Gets the value of the lastUpdatedBy property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
/**
* Sets the value of the lastUpdatedBy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLastUpdatedBy(String value) {
this.lastUpdatedBy = value;
}
/**
* Gets the value of the creationDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getCreationDate() {
return creationDate;
}
/**
* Sets the value of the creationDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setCreationDate(XMLGregorianCalendar value) {
this.creationDate = value;
}
/**
* Gets the value of the createdBy property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCreatedBy() {
return createdBy;
}
/**
* Sets the value of the createdBy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCreatedBy(String value) {
this.createdBy = value;
}
/**
* Gets the value of the lastUpdateLogin property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getLastUpdateLogin() {
return lastUpdateLogin;
}
/**
* Sets the value of the lastUpdateLogin property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setLastUpdateLogin(JAXBElement<String> value) {
this.lastUpdateLogin = ((JAXBElement<String> ) value);
}
/**
* Gets the value of the requestId property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Long }{@code >}
*
*/
public JAXBElement<Long> getRequestId() {
return requestId;
}
/**
* Sets the value of the requestId property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Long }{@code >}
*
*/
public void setRequestId(JAXBElement<Long> value) {
this.requestId = ((JAXBElement<Long> ) value);
}
/**
* Gets the value of the objectVersionNumber property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getObjectVersionNumber() {
return objectVersionNumber;
}
/**
* Sets the value of the objectVersionNumber property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setObjectVersionNumber(Integer value) {
this.objectVersionNumber = value;
}
/**
* Gets the value of the createdByModule property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getCreatedByModule() {
return createdByModule;
}
/**
* Sets the value of the createdByModule property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setCreatedByModule(JAXBElement<String> value) {
this.createdByModule = ((JAXBElement<String> ) value);
}
/**
* Gets the value of the contactPointPurpose property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getContactPointPurpose() {
return contactPointPurpose;
}
/**
* Sets the value of the contactPointPurpose property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setContactPointPurpose(JAXBElement<String> value) {
this.contactPointPurpose = ((JAXBElement<String> ) value);
}
/**
* Gets the value of the primaryByPurpose property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getPrimaryByPurpose() {
return primaryByPurpose;
}
/**
* Sets the value of the primaryByPurpose property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setPrimaryByPurpose(JAXBElement<String> value) {
this.primaryByPurpose = ((JAXBElement<String> ) value);
}
/**
* Gets the value of the startDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartDate() {
return startDate;
}
/**
* Sets the value of the startDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartDate(XMLGregorianCalendar value) {
this.startDate = value;
}
/**
* Gets the value of the endDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEndDate() {
return endDate;
}
/**
* Sets the value of the endDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEndDate(XMLGregorianCalendar value) {
this.endDate = value;
}
/**
* Gets the value of the relationshipId property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Long }{@code >}
*
*/
public JAXBElement<Long> getRelationshipId() {
return relationshipId;
}
/**
* Sets the value of the relationshipId property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Long }{@code >}
*
*/
public void setRelationshipId(JAXBElement<Long> value) {
this.relationshipId = ((JAXBElement<Long> ) value);
}
/**
* Gets the value of the partyUsageCode property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getPartyUsageCode() {
return partyUsageCode;
}
/**
* Sets the value of the partyUsageCode property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setPartyUsageCode(JAXBElement<String> value) {
this.partyUsageCode = ((JAXBElement<String> ) value);
}
/**
* Gets the value of the origSystem property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getOrigSystem() {
return origSystem;
}
/**
* Sets the value of the origSystem property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setOrigSystem(JAXBElement<String> value) {
this.origSystem = ((JAXBElement<String> ) value);
}
/**
* Gets the value of the telexNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTelexNumber() {
return telexNumber;
}
/**
* Sets the value of the telexNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTelexNumber(String value) {
this.telexNumber = value;
}
/**
* Gets the value of the overallPrimaryFlag property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isOverallPrimaryFlag() {
return overallPrimaryFlag;
}
/**
* Sets the value of the overallPrimaryFlag property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setOverallPrimaryFlag(Boolean value) {
this.overallPrimaryFlag = value;
}
/**
* Gets the value of the contactPreference property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the contactPreference property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContactPreference().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ContactPreference }
*
*
*/
public List<ContactPreference> getContactPreference() {
if (contactPreference == null) {
contactPreference = new ArrayList<ContactPreference>();
}
return this.contactPreference;
}
/**
* Gets the value of the originalSystemReference property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the originalSystemReference property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getOriginalSystemReference().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link OriginalSystemReference }
*
*
*/
public List<OriginalSystemReference> getOriginalSystemReference() {
if (originalSystemReference == null) {
originalSystemReference = new ArrayList<OriginalSystemReference>();
}
return this.originalSystemReference;
}
}
| |
/*
* MIT License
*
* Copyright (c) 2019 Choko (choko@curioswitch.org)
*
* 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 org.curioswitch.common.protobuf.json;
import static org.curioswitch.common.protobuf.json.CodeGenUtil.invoke;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.SerializableString;
import com.google.protobuf.ByteString;
import com.google.protobuf.Descriptors.Descriptor;
import com.google.protobuf.Descriptors.EnumDescriptor;
import com.google.protobuf.Descriptors.EnumValueDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.FieldDescriptor.JavaType;
import com.google.protobuf.Descriptors.FieldDescriptor.Type;
import com.google.protobuf.Internal.EnumLite;
import com.google.protobuf.Message;
import com.google.protobuf.NullValue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.bytebuddy.description.field.FieldDescription;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription.ForLoadedType;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.StackManipulation.Trivial;
import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
import net.bytebuddy.implementation.bytecode.assign.primitive.PrimitiveUnboxingDelegate;
import net.bytebuddy.implementation.bytecode.constant.DoubleConstant;
import net.bytebuddy.implementation.bytecode.constant.FloatConstant;
import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
import net.bytebuddy.implementation.bytecode.constant.LongConstant;
import net.bytebuddy.implementation.bytecode.constant.TextConstant;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import net.bytebuddy.implementation.bytecode.member.MethodReturn;
import net.bytebuddy.jar.asm.Label;
import net.bytebuddy.jar.asm.MethodVisitor;
import org.curioswitch.common.protobuf.json.LocalVariables.VariableHandle;
import org.curioswitch.common.protobuf.json.bytebuddy.Goto;
import org.curioswitch.common.protobuf.json.bytebuddy.IfEqual;
import org.curioswitch.common.protobuf.json.bytebuddy.IfFalse;
import org.curioswitch.common.protobuf.json.bytebuddy.IfIntsNotEqual;
import org.curioswitch.common.protobuf.json.bytebuddy.SetJumpTargetLabel;
/**
* {@link ByteCodeAppender} to generate code for serializing a specific {@link Message} type. For
* all fields, checks for field presence and writes it appropriately.
*
* <p>Generated code looks something like:
*
* <pre>{@code
* if (message.getFieldOne() != 0) {
* SerializeSupport.printSignedInt32(message.getFieldOne(), gen);
* }
* if (message.getFieldTwoCount() != 0){
* SerializeSupport.printRepeatedString(message.getFieldTwoList(), gen);
* }
* if (message.getFieldThreeCount() != 0) {
* for (Map.Entry<Integer, String> entry : message.getFieldThreeMap()) {
* gen.writeFieldName(Integer.toString(SerializesSupport.normalizeInt32(entry.getKey()));
* SerializeSupport.printString(entry.getValue());
* }
* }
*
* }</pre>
*/
final class DoWrite implements ByteCodeAppender, Implementation {
private enum LocalVariable implements VariableHandle {
message,
gen,
iterator,
entry
}
private static final StackManipulation JsonGenerator_writeFieldName_SerializableString;
private static final StackManipulation JsonGenerator_writeFieldName_String;
private static final StackManipulation JsonGenerator_writeStartObject;
private static final StackManipulation JsonGenerator_writeEndObject;
private static final StackManipulation Object_equals;
private static final StackManipulation EnumLite_getNumber;
private static final StackManipulation Iterator_hasNext;
private static final StackManipulation Iterator_next;
private static final StackManipulation Map_Entry_getKey;
private static final StackManipulation Map_Entry_getValue;
private static final StackManipulation Integer_toString;
private static final StackManipulation Long_toString;
private static final StackManipulation Boolean_toString;
private static final StackManipulation SerializeSupport_mapIterator;
private static final StackManipulation SerializeSupport_printRepeatedSignedInt32;
private static final StackManipulation SerializeSupport_printSignedInt32;
private static final StackManipulation SerializeSupport_printRepeatedSignedInt64;
private static final StackManipulation SerializeSupport_printSignedInt64;
private static final StackManipulation SerializeSupport_printRepeatedBool;
private static final StackManipulation SerializeSupport_printBool;
private static final StackManipulation SerializeSupport_printRepeatedFloat;
private static final StackManipulation SerializeSupport_printFloat;
private static final StackManipulation SerializeSupport_printRepeatedDouble;
private static final StackManipulation SerializeSupport_printDouble;
private static final StackManipulation SerializeSupport_printRepeatedUnsignedInt32;
private static final StackManipulation SerializeSupport_printUnsignedInt32;
private static final StackManipulation SerializeSupport_printRepeatedUnsignedInt64;
private static final StackManipulation SerializeSupport_printUnsignedInt64;
private static final StackManipulation SerializeSupport_printRepeatedString;
private static final StackManipulation SerializeSupport_printString;
private static final StackManipulation SerializeSupport_printRepeatedBytes;
private static final StackManipulation SerializeSupport_printBytes;
private static final StackManipulation SerializeSupport_printRepeatedNull;
private static final StackManipulation SerializeSupport_printNull;
private static final StackManipulation SerializeSupport_printRepeatedEnum;
private static final StackManipulation SerializeSupport_printEnum;
private static final StackManipulation SerializeSupport_printRepeatedMessage;
private static final StackManipulation SerializeSupport_printMessage;
private static final StackManipulation SerializeSupport_normalizeUnsignedInt32;
private static final StackManipulation SerializeSupport_normalizeUnsignedInt64;
static {
try {
JsonGenerator_writeFieldName_SerializableString =
invoke(JsonGenerator.class.getDeclaredMethod("writeFieldName", SerializableString.class));
JsonGenerator_writeFieldName_String =
invoke(JsonGenerator.class.getDeclaredMethod("writeFieldName", String.class));
JsonGenerator_writeStartObject =
invoke(JsonGenerator.class.getDeclaredMethod("writeStartObject"));
JsonGenerator_writeEndObject =
invoke(JsonGenerator.class.getDeclaredMethod("writeEndObject"));
Object_equals = invoke(Object.class.getDeclaredMethod("equals", Object.class));
EnumLite_getNumber = invoke(EnumLite.class.getDeclaredMethod("getNumber"));
Integer_toString = invoke(Integer.class.getDeclaredMethod("toString", int.class));
Long_toString = invoke(Long.class.getDeclaredMethod("toString", long.class));
Boolean_toString = invoke(Boolean.class.getDeclaredMethod("toString", boolean.class));
Iterator_hasNext = invoke(Iterator.class.getDeclaredMethod("hasNext"));
Iterator_next = invoke(Iterator.class.getDeclaredMethod("next"));
Map_Entry_getKey = invoke(Entry.class.getDeclaredMethod("getKey"));
Map_Entry_getValue = invoke(Entry.class.getDeclaredMethod("getValue"));
SerializeSupport_mapIterator =
invoke(
SerializeSupport.class.getDeclaredMethod(
"mapIterator", Map.class, boolean.class, boolean.class));
SerializeSupport_printRepeatedSignedInt32 =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedSignedInt32", List.class, JsonGenerator.class));
SerializeSupport_printSignedInt32 =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printSignedInt32", int.class, JsonGenerator.class));
SerializeSupport_printRepeatedSignedInt64 =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedSignedInt64", List.class, JsonGenerator.class));
SerializeSupport_printSignedInt64 =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printSignedInt64", long.class, JsonGenerator.class));
SerializeSupport_printRepeatedBool =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedBool", List.class, JsonGenerator.class));
SerializeSupport_printBool =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printBool", boolean.class, JsonGenerator.class));
SerializeSupport_printRepeatedFloat =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedFloat", List.class, JsonGenerator.class));
SerializeSupport_printFloat =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printFloat", float.class, JsonGenerator.class));
SerializeSupport_printRepeatedDouble =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedDouble", List.class, JsonGenerator.class));
SerializeSupport_printDouble =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printDouble", double.class, JsonGenerator.class));
SerializeSupport_printRepeatedUnsignedInt32 =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedUnsignedInt32", List.class, JsonGenerator.class));
SerializeSupport_printUnsignedInt32 =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printUnsignedInt32", int.class, JsonGenerator.class));
SerializeSupport_printRepeatedUnsignedInt64 =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedUnsignedInt64", List.class, JsonGenerator.class));
SerializeSupport_printUnsignedInt64 =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printUnsignedInt64", long.class, JsonGenerator.class));
SerializeSupport_printRepeatedString =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedString", List.class, JsonGenerator.class));
SerializeSupport_printString =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printString", String.class, JsonGenerator.class));
SerializeSupport_printRepeatedBytes =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedBytes", List.class, JsonGenerator.class));
SerializeSupport_printBytes =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printBytes", ByteString.class, JsonGenerator.class));
SerializeSupport_printRepeatedNull =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedNull", List.class, JsonGenerator.class));
SerializeSupport_printNull =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printNull", int.class, JsonGenerator.class));
SerializeSupport_printRepeatedEnum =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedEnum", List.class, JsonGenerator.class, EnumDescriptor.class));
SerializeSupport_printEnum =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printEnum", int.class, JsonGenerator.class, EnumDescriptor.class));
SerializeSupport_printRepeatedMessage =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printRepeatedMessage",
List.class,
JsonGenerator.class,
TypeSpecificMarshaller.class));
SerializeSupport_printMessage =
invoke(
SerializeSupport.class.getDeclaredMethod(
"printMessage",
Message.class,
JsonGenerator.class,
TypeSpecificMarshaller.class));
SerializeSupport_normalizeUnsignedInt32 =
invoke(SerializeSupport.class.getDeclaredMethod("normalizeUnsignedInt32", int.class));
SerializeSupport_normalizeUnsignedInt64 =
invoke(SerializeSupport.class.getDeclaredMethod("normalizeUnsignedInt64", long.class));
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
private final Message prototype;
private final Class<? extends Message> messageClass;
private final Descriptor descriptor;
private final boolean includeDefaults;
private final boolean printingEnumsAsInts;
private final boolean sortingMapKeys;
DoWrite(
Message prototype,
boolean includeDefaults,
boolean printingEnumsAsInts,
boolean sortingMapKeys) {
this.prototype = prototype;
this.messageClass = prototype.getClass();
this.descriptor = prototype.getDescriptorForType();
this.includeDefaults = includeDefaults;
this.printingEnumsAsInts = printingEnumsAsInts;
this.sortingMapKeys = sortingMapKeys;
}
@Override
public Size apply(
MethodVisitor methodVisitor,
Context implementationContext,
MethodDescription instrumentedMethod) {
Map<String, FieldDescription> fieldsByName = CodeGenUtil.fieldsByName(implementationContext);
List<StackManipulation> stackManipulations = new ArrayList<>();
final StackManipulation getDefaultInstance;
try {
getDefaultInstance = invoke(messageClass.getDeclaredMethod("getDefaultInstance"));
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find getDefaultInstance on a Message class.");
}
LocalVariables<LocalVariable> locals =
LocalVariables.builderForMethod(instrumentedMethod, LocalVariable.values())
.add(Iterator.class, LocalVariable.iterator)
.add(Map.Entry.class, LocalVariable.entry)
.build();
stackManipulations.add(locals.initialize());
// We output serialization code for each field, with an accompanying presence-check if-statement
// based on the includeDefaults parameter.
for (FieldDescriptor f : CodeGenUtil.sorted(descriptor.getFields())) {
ProtoFieldInfo field = new ProtoFieldInfo(f, prototype);
StackManipulation getValue =
new StackManipulation.Compound(
locals.load(LocalVariable.message), invoke(field.getValueMethod()));
Label afterSerializeField = new Label();
// If includeDefaults is false, or for repeated fields, we check whether the value is default
// and skip otherwise.
//
// e.g.,
// if (message.getFoo() == field.getDefaultValue()) {
// ...
// }
// if (message.getBarCount() != 0) {
// ...
// }
if (!includeDefaults
// Only print one-of fields if they're actually set (the default of a one-of is an empty
// one-of).
|| field.isInOneof()
// Always skip empty optional message fields. If not we will recurse indefinitely if
// a message has itself as a sub-field.
|| (field.descriptor().isOptional() && field.valueJavaType() == JavaType.MESSAGE)) {
stackManipulations.add(
checkDefaultValue(field, locals, getValue, getDefaultInstance, afterSerializeField));
}
stackManipulations.addAll(
Arrays.asList(
locals.load(LocalVariable.gen),
FieldAccess.forField(
fieldsByName.get(CodeGenUtil.fieldNameForSerializedFieldName(field)))
.read(),
JsonGenerator_writeFieldName_SerializableString));
// Serializes a map field by iterating over entries, encoding the key and value as
// appropriate. Map keys are always strings. There are too many combinations of field to value
// for maps, so we generate the code to iterate over them, unlike normal repeated fields.
//
// e.g.,
// gen.writeStartObject();
// for (Map.Entry<K, V> entry : message.getFooMap().entrySet()) {
// String key = keyToString(entry.getKey());
// gen.writeFieldName(key);
// SerializeSupport.printFoo(gen, entry.getValue());
// }
// gen.writeEndObject();
if (field.isMapField()) {
final StackManipulation keyToString;
switch (field.mapKeyField().descriptor().getType()) {
case INT32:
case SINT32:
case SFIXED32:
keyToString = Integer_toString;
break;
case INT64:
case SINT64:
case SFIXED64:
keyToString = Long_toString;
break;
case BOOL:
keyToString = Boolean_toString;
break;
case UINT32:
case FIXED32:
keyToString =
new StackManipulation.Compound(
SerializeSupport_normalizeUnsignedInt32, Long_toString);
break;
case UINT64:
case FIXED64:
keyToString = SerializeSupport_normalizeUnsignedInt64;
break;
case STRING:
keyToString = Trivial.INSTANCE;
break;
default:
throw new IllegalStateException(
"Unexpected map key type: " + field.mapKeyField().descriptor().getType());
}
final Label loopStart = new Label();
final Label loopEnd = new Label();
final StackManipulation printValue = printValue(fieldsByName, field);
final StackManipulation printMapFieldValue =
new StackManipulation.Compound(
locals.load(LocalVariable.gen),
JsonGenerator_writeStartObject,
getValue,
IntegerConstant.forValue(sortingMapKeys),
IntegerConstant.forValue(field.mapKeyField().valueType() == Type.STRING),
SerializeSupport_mapIterator,
locals.store(LocalVariable.iterator),
new SetJumpTargetLabel(loopStart),
locals.load(LocalVariable.iterator),
Iterator_hasNext,
new IfFalse(loopEnd),
locals.load(LocalVariable.iterator),
Iterator_next,
TypeCasting.to(new ForLoadedType(Entry.class)),
locals.store(LocalVariable.entry),
locals.load(LocalVariable.gen),
locals.load(LocalVariable.entry),
Map_Entry_getKey,
unbox(field.mapKeyField()),
keyToString,
JsonGenerator_writeFieldName_String,
locals.load(LocalVariable.entry),
Map_Entry_getValue,
unbox(field.valueField()),
locals.load(LocalVariable.gen),
printValue,
new Goto(loopStart),
new SetJumpTargetLabel(loopEnd),
locals.load(LocalVariable.gen),
JsonGenerator_writeEndObject);
stackManipulations.add(printMapFieldValue);
} else {
// Simply calls the SerializeSupport method that prints out this field. Any iteration will
// be handled there.
//
// e.g.,
// SerializeSupport.printUnsignedInt32(message.getFoo());
// SerializeSupport.printRepeatedString(message.getBar());
final StackManipulation printValue = printValue(fieldsByName, field);
stackManipulations.addAll(
Arrays.asList(getValue, locals.load(LocalVariable.gen), printValue));
}
stackManipulations.add(new SetJumpTargetLabel(afterSerializeField));
}
stackManipulations.add(MethodReturn.VOID);
StackManipulation.Size operandStackSize =
new StackManipulation.Compound(stackManipulations)
.apply(methodVisitor, implementationContext);
return new Size(operandStackSize.getMaximalSize(), locals.stackSize());
}
/**
* Retrurns a {@link StackManipulation} that checks whether the value in the message is a default
* value, and if so jumps to after serialization to skip the serialization of the default value.
* e.g.,
*
* <pre>{code
* if (message.getFoo() != field.getDefaultValue) {
* ...
* }
* // afterSerializeField
* }</pre>
*/
private static StackManipulation checkDefaultValue(
ProtoFieldInfo info,
LocalVariables<LocalVariable> locals,
StackManipulation getValue,
StackManipulation getDefaultInstance,
Label afterSerializeField) {
if (info.isInOneof()) {
// For one-ofs, we can just check the set field number directly.
return new StackManipulation.Compound(
locals.load(LocalVariable.message),
CodeGenUtil.invoke(info.oneOfCaseMethod()),
EnumLite_getNumber,
IntegerConstant.forValue(info.descriptor().getNumber()),
new IfIntsNotEqual(afterSerializeField));
} else if (!info.isRepeated()) {
switch (info.valueJavaType()) {
case INT:
return checkPrimitiveDefault(
getValue,
IntegerConstant.forValue((int) info.descriptor().getDefaultValue()),
int.class,
afterSerializeField);
case LONG:
return checkPrimitiveDefault(
getValue,
LongConstant.forValue((long) info.descriptor().getDefaultValue()),
long.class,
afterSerializeField);
case FLOAT:
return checkPrimitiveDefault(
getValue,
FloatConstant.forValue((float) info.descriptor().getDefaultValue()),
float.class,
afterSerializeField);
case DOUBLE:
return checkPrimitiveDefault(
getValue,
DoubleConstant.forValue((double) info.descriptor().getDefaultValue()),
double.class,
afterSerializeField);
case BOOLEAN:
return checkPrimitiveDefault(
getValue,
IntegerConstant.forValue((boolean) info.descriptor().getDefaultValue()),
boolean.class,
afterSerializeField);
case ENUM:
return checkPrimitiveDefault(
getValue,
IntegerConstant.forValue(
((EnumValueDescriptor) info.descriptor().getDefaultValue()).getNumber()),
int.class,
afterSerializeField);
case STRING:
return new StackManipulation.Compound(
getValue,
new TextConstant((String) info.descriptor().getDefaultValue()),
Object_equals,
new IfEqual(Object.class, afterSerializeField));
case BYTE_STRING:
// We'll use the default instance to get the default value for types that can't be
// loaded into the constant pool. Since it's a constant, the somewhat indirect reference
// should get inlined and be the same as a class constant.
return new StackManipulation.Compound(
getValue,
getDefaultInstance,
invoke(info.getValueMethod()),
Object_equals,
new IfEqual(Object.class, afterSerializeField));
case MESSAGE:
return new StackManipulation.Compound(
locals.load(LocalVariable.message),
invoke(info.hasValueMethod()),
new IfFalse(afterSerializeField));
default:
throw new IllegalStateException("Unknown JavaType: " + info.valueJavaType());
}
} else {
return new StackManipulation.Compound(
locals.load(LocalVariable.message),
CodeGenUtil.invoke(info.repeatedValueCountMethod()),
new IfFalse(afterSerializeField));
}
}
private static StackManipulation unbox(ProtoFieldInfo field) {
switch (field.valueJavaType()) {
case INT:
case ENUM:
return new StackManipulation.Compound(
TypeCasting.to(new ForLoadedType(Integer.class)), PrimitiveUnboxingDelegate.INTEGER);
case LONG:
return new StackManipulation.Compound(
TypeCasting.to(new ForLoadedType(Long.class)), PrimitiveUnboxingDelegate.LONG);
case BOOLEAN:
return new StackManipulation.Compound(
TypeCasting.to(new ForLoadedType(Boolean.class)), PrimitiveUnboxingDelegate.BOOLEAN);
case FLOAT:
return new StackManipulation.Compound(
TypeCasting.to(new ForLoadedType(Float.class)), PrimitiveUnboxingDelegate.FLOAT);
case DOUBLE:
return new StackManipulation.Compound(
TypeCasting.to(new ForLoadedType(Double.class)), PrimitiveUnboxingDelegate.DOUBLE);
case STRING:
return TypeCasting.to(new ForLoadedType(String.class));
case BYTE_STRING:
return TypeCasting.to(new ForLoadedType(ByteString.class));
case MESSAGE:
return TypeCasting.to(new ForLoadedType(Message.class));
default:
throw new IllegalStateException("Unknown field type.");
}
}
private StackManipulation printValue(
Map<String, FieldDescription> fieldsByName, ProtoFieldInfo info) {
boolean repeated = !info.isMapField() && info.isRepeated();
switch (info.valueType()) {
case INT32:
case SINT32:
case SFIXED32:
return repeated
? SerializeSupport_printRepeatedSignedInt32
: SerializeSupport_printSignedInt32;
case INT64:
case SINT64:
case SFIXED64:
return repeated
? SerializeSupport_printRepeatedSignedInt64
: SerializeSupport_printSignedInt64;
case BOOL:
return repeated ? SerializeSupport_printRepeatedBool : SerializeSupport_printBool;
case FLOAT:
return repeated ? SerializeSupport_printRepeatedFloat : SerializeSupport_printFloat;
case DOUBLE:
return repeated ? SerializeSupport_printRepeatedDouble : SerializeSupport_printDouble;
case UINT32:
case FIXED32:
return repeated
? SerializeSupport_printRepeatedUnsignedInt32
: SerializeSupport_printUnsignedInt32;
case UINT64:
case FIXED64:
return repeated
? SerializeSupport_printRepeatedUnsignedInt64
: SerializeSupport_printUnsignedInt64;
case STRING:
return repeated ? SerializeSupport_printRepeatedString : SerializeSupport_printString;
case BYTES:
return repeated ? SerializeSupport_printRepeatedBytes : SerializeSupport_printBytes;
case ENUM:
// Special-case google.protobuf.NullValue (it's an Enum).
if (info.valueField().descriptor().getEnumType().equals(NullValue.getDescriptor())) {
return repeated ? SerializeSupport_printRepeatedNull : SerializeSupport_printNull;
} else {
if (printingEnumsAsInts) {
return repeated
? SerializeSupport_printRepeatedUnsignedInt32
: SerializeSupport_printUnsignedInt32;
} else {
return new StackManipulation.Compound(
CodeGenUtil.getEnumDescriptor(info),
repeated ? SerializeSupport_printRepeatedEnum : SerializeSupport_printEnum);
}
}
case MESSAGE:
case GROUP:
return new StackManipulation.Compound(
FieldAccess.forField(
fieldsByName.get(
CodeGenUtil.fieldNameForNestedMarshaller(
info.valueField().descriptor().getMessageType())))
.read(),
repeated ? SerializeSupport_printRepeatedMessage : SerializeSupport_printMessage);
default:
throw new IllegalStateException("Unknown field type.");
}
}
private static StackManipulation checkPrimitiveDefault(
StackManipulation getValue,
StackManipulation loadDefault,
Class<?> variableType,
Label afterPrint) {
return new StackManipulation.Compound(
getValue, loadDefault, new IfEqual(variableType, afterPrint));
}
@Override
public ByteCodeAppender appender(Target implementationTarget) {
return this;
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
}
| |
/*
* 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.cocoon.webapps.session.components;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.components.ContextHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Session;
import org.apache.cocoon.util.AbstractLogEnabled;
import org.apache.cocoon.webapps.session.ContextManager;
import org.apache.cocoon.webapps.session.SessionConstants;
import org.apache.cocoon.webapps.session.SessionManager;
import org.apache.cocoon.webapps.session.context.SessionContext;
import org.apache.cocoon.xml.XMLConsumer;
import org.apache.cocoon.xml.XMLUtils;
import org.apache.cocoon.xml.dom.DOMUtil;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* This is the default implementation of the session manager
*
* @deprecated This block is deprecated and will be removed in future versions.
* @version $Id$
*/
public final class DefaultSessionManager
extends AbstractLogEnabled
implements Serviceable, ThreadSafe, SessionManager, Disposable, Contextualizable {
/** The context */
private Context context;
/** The <code>ServiceManager</code> */
private ServiceManager manager;
/** The context manager */
private ContextManager contextManager;
/**
* @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
*/
public void service(ServiceManager manager)
throws ServiceException {
this.manager = manager;
this.contextManager = (ContextManager)this.manager.lookup(ContextManager.ROLE);
}
/**
* @see org.apache.avalon.framework.activity.Disposable#dispose()
*/
public void dispose() {
if (this.manager != null ) {
this.manager.release(this.contextManager);
this.manager = null;
this.contextManager = null;
}
}
/**
* Create a new session for the user.
* A new session is created for this user. If the user has already a session,
* no new session is created and the old one is returned.
*/
public Session createSession() {
// synchronized
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("BEGIN createSession");
}
Session session = this.getSession(true);
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("END createSession session=" + session);
}
return session;
}
/**
* Get the session for the current user.
* If the user has no session right now, <CODE>null</CODE> is returned.
* If createFlag is true, the session is created if it does not exist.
*/
public Session getSession(boolean createFlag) {
final Request request = ContextHelper.getRequest(this.context);
// synchronized
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("BEGIN getSession create=" + createFlag);
}
Session session = (Session) request.getCocoonSession(createFlag);
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("END getSession session=" + session);
}
return session;
}
/**
* Terminate the current session.
* If the user has a session, this session is terminated and all of its
* data is deleted.
* @param force If this is set to true the session is terminated, if
* it is set to false, the session is only terminated
* if no session context is available.
*/
public void terminateSession(boolean force)
throws ProcessingException {
// synchronized
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("BEGIN terminateSession force="+force);
}
Session session = this.getSession( false );
if (session != null) {
if (force || this.contextManager.hasSessionContext() ) {
synchronized(session) {
session.invalidate();
}
}
}
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("END terminateSession");
}
}
/**
* Get information from the context.
* A document fragment containg the xml data stored in the session context
* with the given name is returned. If the information is not available,
* <CODE>null</CODE> is returned.
* @param contextName The name of the public context.
* @param path XPath expression specifying which data to get.
* @return A DocumentFragment containing the data or <CODE>null</CODE>
*/
public DocumentFragment getContextFragment(String contextName,
String path)
throws ProcessingException {
// synchronized via context
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("BEGIN getContextFragment name=" + contextName + ", path=" + path);
}
// test arguments
if (contextName == null) {
throw new ProcessingException("SessionManager.getContextFragment: Name is required");
}
if (path == null) {
throw new ProcessingException("SessionManager.getContextFragment: Path is required");
}
SessionContext context = this.contextManager.getContext( contextName );
if (context == null) {
throw new ProcessingException("SessionManager.getContextFragment: Context '" + contextName + "' not found.");
}
DocumentFragment frag;
frag = context.getXML(path);
if (getLogger().isDebugEnabled() ) {
getLogger().debug("END getContextFragment documentFragment=" +
(frag == null? "null": XMLUtils.serializeNode(frag)));
}
return frag;
}
/**
* Stream public context data.
* The document fragment containing the data from a path in the
* given context is streamed to the consumer.
*
* @param contextName The name of the public context.
* @param path XPath expression specifying which data to get.
*
* @return If the data is available <code>true</code> is returned,
* otherwise <code>false</code> is returned.
*/
public boolean streamContextFragment(String contextName,
String path,
XMLConsumer consumer)
throws SAXException, ProcessingException {
// synchronized via context
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("BEGIN streamContextFragment name=" + contextName + ", path=" + path + ", consumer"+consumer);
}
boolean streamed = false;
// test arguments
if (contextName == null) {
throw new ProcessingException("SessionManager.streamContextFragment: Name is required");
}
if (path == null) {
throw new ProcessingException("SessionManager.streamContextFragment: Path is required");
}
SessionContext context = this.contextManager.getContext( contextName );
if (context == null) {
throw new ProcessingException("SessionManager.streamContextFragment: Context '" + contextName + "' not found.");
}
streamed = context.streamXML(path, consumer, consumer);
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("END streamContextFragment streamed=" + streamed);
}
return streamed;
}
/**
* Set data in a public context.
* The document fragment containing the data is set at the given path in the
* public session context.
*
* @param contextName The name of the public context.
* @param path XPath expression specifying where to set the data.
* @param fragment The DocumentFragment containing the data.
*
*/
public void setContextFragment(String contextName,
String path,
DocumentFragment fragment)
throws ProcessingException {
// synchronized via context
if (getLogger().isDebugEnabled()) {
getLogger().debug("BEGIN setContextFragment name=" + contextName +
", path=" + path +
", fragment=" + (fragment == null? "null": XMLUtils.serializeNode(fragment)));
}
// test arguments
if (contextName == null) {
throw new ProcessingException("SessionManager.setContextFragment: Name is required");
}
if (path == null) {
throw new ProcessingException("SessionManager.setContextFragment: Path is required");
}
if (fragment == null) {
throw new ProcessingException("SessionManager.setContextFragment: Fragment is required");
}
// get context
SessionContext context = this.contextManager.getContext( contextName );
// check context
if (context == null) {
throw new ProcessingException("SessionManager.setContextFragment: Context '" + contextName + "' not found.");
}
context.setXML(path, fragment);
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("END setContextFragment");
}
}
/**
* Append data in a public context.
* The document fragment containing the data is appended at the given
* path in the public session context.
*
* @param contextName The name of the public context.
* @param path XPath expression specifying where to append the data.
* @param fragment The DocumentFragment containing the data.
*
*/
public void appendContextFragment(String contextName,
String path,
DocumentFragment fragment)
throws ProcessingException {
// synchronized via context
if (getLogger().isDebugEnabled() ) {
getLogger().debug("BEGIN appendContextFragment name=" + contextName +
", path=" + path +
", fragment=" + (fragment == null? "null": XMLUtils.serializeNode(fragment)));
}
// test arguments
if (contextName == null) {
throw new ProcessingException("SessionManager.appendContextFragment: Name is required");
}
if (path == null) {
throw new ProcessingException("SessionManager.appendContextFragment: Path is required");
}
if (fragment == null) {
throw new ProcessingException("SessionManager.appendContextFragment: Fragment is required");
}
// get context
SessionContext context = this.contextManager.getContext( contextName );
// check context
if (context == null) {
throw new ProcessingException("SessionManager.appendContextFragment: Context '" + contextName + "' not found.");
}
context.appendXML(path, fragment);
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("END appendContextFragment");
}
}
/**
* Merge data in a public context.
* The document fragment containing the data is merged at the given
* path in the public session context.
*
* @param contextName The name of the public context.
* @param path XPath expression specifying where to merge the data.
* @param fragment The DocumentFragment containing the data.
*
*/
public void mergeContextFragment(String contextName,
String path,
DocumentFragment fragment)
throws ProcessingException {
// synchronized via context
if (getLogger().isDebugEnabled() ) {
getLogger().debug("BEGIN mergeContextFragment name=" + contextName +
", path=" + path +
", fragment=" + (fragment == null? "null": XMLUtils.serializeNode(fragment)));
}
// test arguments
if (contextName == null) {
throw new ProcessingException("SessionManager.mergeContextFragment: Name is required");
}
if (path == null) {
throw new ProcessingException("SessionManager.mergeContextFragment: Path is required");
}
if (fragment == null) {
throw new ProcessingException("SessionManager.mergeContextFragment: Fragment is required");
}
// get context
SessionContext context = this.contextManager.getContext( contextName );
// check context
if (context == null) {
throw new ProcessingException("SessionManager.mergeContextFragment: Context '" + contextName + "' not found.");
}
Node contextNode = context.getSingleNode(path);
if (contextNode == null) {
// no merge required
context.setXML(path, fragment);
} else {
this.importNode(contextNode, fragment, false);
context.setNode(path, contextNode);
}
if (this.getLogger().isDebugEnabled()) {
this.getLogger().debug("END mergeContextFragment");
}
}
/**
* Remove data in a public context.
* The data specified by the path is removed from the public session context.
*
* @param contextName The name of the public context.
* @param path XPath expression specifying where to merge the data.
*
*/
public void removeContextFragment(String contextName,
String path)
throws ProcessingException {
// synchronized via context
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("BEGIN removeContextFragment name=" + contextName + ", path=" + path);
}
// test arguments
if (contextName == null) {
throw new ProcessingException("SessionManager.removeContextFragment: Name is required");
}
if (path == null) {
throw new ProcessingException("SessionManager.removeContextFragment: Path is required");
}
// get context
SessionContext context = this.contextManager.getContext( contextName );
// check context
if (context == null) {
throw new ProcessingException("SessionManager.removeContextFragment: Context '" + contextName + "' not found.");
}
context.removeXML(path);
if (this.getLogger().isDebugEnabled() ) {
this.getLogger().debug("END removeContextFragment");
}
}
/**
* Import nodes. If preserve is set to true, the nodes
* marked with cocoon:preserve are always imported
* overwriting others!
*/
private void importNode(Node profile, Node delta, boolean preserve) {
// no sync req
NodeList profileChilds = null;
NodeList deltaChilds = delta.getChildNodes();
int i, len;
int m, l;
boolean found;
Node currentDelta = null;
Node currentProfile = null;
len = deltaChilds.getLength();
for(i = 0; i < len; i++) {
currentDelta = deltaChilds.item(i);
if (currentDelta.getNodeType() == Node.ELEMENT_NODE) {
// search the delta node in the profile
profileChilds = profile.getChildNodes();
l = profileChilds.getLength();
m = 0;
found = false;
while (found == false && m < l) {
currentProfile = profileChilds.item(m);
if (currentProfile.getNodeType() == Node.ELEMENT_NODE
&& currentProfile.getNodeName().equals(currentDelta.getNodeName()) == true) {
// now we have found a node with the same name
// next: the attributes must match also
found = DOMUtil.compareAttributes((Element)currentProfile, (Element)currentDelta);
}
if (found == false) m++;
}
if (found == true) {
// this is not new
if (preserve == true
&& ((Element)currentDelta).hasAttributeNS(SessionConstants.SESSION_NAMESPACE_URI, "preserve")
&& ((Element)currentDelta).getAttributeNS(SessionConstants.SESSION_NAMESPACE_URI, "preserve").equalsIgnoreCase("true")) {
// replace the original with the delta
profile.replaceChild(profile.getOwnerDocument().importNode(currentDelta, true),
currentProfile);
} else {
// do we have elements as children or text?
if (currentDelta.hasChildNodes() == true) {
currentDelta.normalize();
currentProfile.normalize();
// do a recursive call for sub elements
this.importNode(currentProfile, currentDelta, preserve);
// and now the text nodes: Remove all from the profile and add all
// of the delta
NodeList childs = currentProfile.getChildNodes();
int index, max;
max = childs.getLength();
for(index = max - 1; index >= 0; index--) {
if (childs.item(index).getNodeType() == Node.TEXT_NODE) {
currentProfile.removeChild(childs.item(index));
}
}
childs = currentDelta.getChildNodes();
max = childs.getLength();
for(index = 0; index < max; index++) {
if (childs.item(index).getNodeType() == Node.TEXT_NODE) {
currentProfile.appendChild(currentProfile.getOwnerDocument()
.createTextNode(childs.item(index).getNodeValue()));
}
}
}
}
} else {
profile.appendChild(profile.getOwnerDocument().importNode(currentDelta, true));
}
}
}
}
/* (non-Javadoc)
* @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
*/
public void contextualize(Context context) throws ContextException {
this.context = context;
}
}
| |
/*
* 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.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.aws2.lambda.Lambda2Component;
/**
* Manage and invoke AWS Lambda functions using AWS SDK version 2.x.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface Aws2LambdaComponentBuilderFactory {
/**
* AWS 2 Lambda (camel-aws2-lambda)
* Manage and invoke AWS Lambda functions using AWS SDK version 2.x.
*
* Category: cloud,computing,serverless
* Since: 3.2
* Maven coordinates: org.apache.camel:camel-aws2-lambda
*
* @return the dsl builder
*/
static Aws2LambdaComponentBuilder aws2Lambda() {
return new Aws2LambdaComponentBuilderImpl();
}
/**
* Builder for the AWS 2 Lambda component.
*/
interface Aws2LambdaComponentBuilder
extends
ComponentBuilder<Lambda2Component> {
/**
* Component configuration.
*
* The option is a:
* <code>org.apache.camel.component.aws2.lambda.Lambda2Configuration</code> type.
*
* Group: producer
*
* @param configuration the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder configuration(
org.apache.camel.component.aws2.lambda.Lambda2Configuration configuration) {
doSetProperty("configuration", configuration);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* The operation to perform. It can be listFunctions, getFunction,
* createFunction, deleteFunction or invokeFunction.
*
* The option is a:
* <code>org.apache.camel.component.aws2.lambda.Lambda2Operations</code> type.
*
* Default: invokeFunction
* Group: producer
*
* @param operation the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder operation(
org.apache.camel.component.aws2.lambda.Lambda2Operations operation) {
doSetProperty("operation", operation);
return this;
}
/**
* If we want to use a POJO request as body or not.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param pojoRequest the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder pojoRequest(boolean pojoRequest) {
doSetProperty("pojoRequest", pojoRequest);
return this;
}
/**
* The region in which ECS client needs to work. When using this
* parameter, the configuration will expect the lowercase name of the
* region (for example ap-east-1) You'll need to use the name
* Region.EU_WEST_1.id().
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param region the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder region(java.lang.String region) {
doSetProperty("region", region);
return this;
}
/**
* If we want to trust all certificates in case of overriding the
* endpoint.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param trustAllCertificates the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder trustAllCertificates(
boolean trustAllCertificates) {
doSetProperty("trustAllCertificates", trustAllCertificates);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder autowiredEnabled(
boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* To use a existing configured AwsLambdaClient as client.
*
* The option is a:
* <code>software.amazon.awssdk.services.lambda.LambdaClient</code> type.
*
* Group: advanced
*
* @param awsLambdaClient the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder awsLambdaClient(
software.amazon.awssdk.services.lambda.LambdaClient awsLambdaClient) {
doSetProperty("awsLambdaClient", awsLambdaClient);
return this;
}
/**
* To define a proxy host when instantiating the Lambda client.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyHost the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder proxyHost(java.lang.String proxyHost) {
doSetProperty("proxyHost", proxyHost);
return this;
}
/**
* To define a proxy port when instantiating the Lambda client.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: proxy
*
* @param proxyPort the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder proxyPort(java.lang.Integer proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* To define a proxy protocol when instantiating the Lambda client.
*
* The option is a:
* <code>software.amazon.awssdk.core.Protocol</code> type.
*
* Default: HTTPS
* Group: proxy
*
* @param proxyProtocol the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder proxyProtocol(
software.amazon.awssdk.core.Protocol proxyProtocol) {
doSetProperty("proxyProtocol", proxyProtocol);
return this;
}
/**
* Amazon AWS Access Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessKey the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder accessKey(java.lang.String accessKey) {
doSetProperty("accessKey", accessKey);
return this;
}
/**
* Amazon AWS Secret Key.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param secretKey the value to set
* @return the dsl builder
*/
default Aws2LambdaComponentBuilder secretKey(java.lang.String secretKey) {
doSetProperty("secretKey", secretKey);
return this;
}
}
class Aws2LambdaComponentBuilderImpl
extends
AbstractComponentBuilder<Lambda2Component>
implements
Aws2LambdaComponentBuilder {
@Override
protected Lambda2Component buildConcreteComponent() {
return new Lambda2Component();
}
private org.apache.camel.component.aws2.lambda.Lambda2Configuration getOrCreateConfiguration(
org.apache.camel.component.aws2.lambda.Lambda2Component component) {
if (component.getConfiguration() == null) {
component.setConfiguration(new org.apache.camel.component.aws2.lambda.Lambda2Configuration());
}
return component.getConfiguration();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "configuration": ((Lambda2Component) component).setConfiguration((org.apache.camel.component.aws2.lambda.Lambda2Configuration) value); return true;
case "lazyStartProducer": ((Lambda2Component) component).setLazyStartProducer((boolean) value); return true;
case "operation": getOrCreateConfiguration((Lambda2Component) component).setOperation((org.apache.camel.component.aws2.lambda.Lambda2Operations) value); return true;
case "pojoRequest": getOrCreateConfiguration((Lambda2Component) component).setPojoRequest((boolean) value); return true;
case "region": getOrCreateConfiguration((Lambda2Component) component).setRegion((java.lang.String) value); return true;
case "trustAllCertificates": getOrCreateConfiguration((Lambda2Component) component).setTrustAllCertificates((boolean) value); return true;
case "autowiredEnabled": ((Lambda2Component) component).setAutowiredEnabled((boolean) value); return true;
case "awsLambdaClient": getOrCreateConfiguration((Lambda2Component) component).setAwsLambdaClient((software.amazon.awssdk.services.lambda.LambdaClient) value); return true;
case "proxyHost": getOrCreateConfiguration((Lambda2Component) component).setProxyHost((java.lang.String) value); return true;
case "proxyPort": getOrCreateConfiguration((Lambda2Component) component).setProxyPort((java.lang.Integer) value); return true;
case "proxyProtocol": getOrCreateConfiguration((Lambda2Component) component).setProxyProtocol((software.amazon.awssdk.core.Protocol) value); return true;
case "accessKey": getOrCreateConfiguration((Lambda2Component) component).setAccessKey((java.lang.String) value); return true;
case "secretKey": getOrCreateConfiguration((Lambda2Component) component).setSecretKey((java.lang.String) value); return true;
default: return false;
}
}
}
}
| |
/**
* 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.alibaba.rocketmq.store.ha;
import com.alibaba.rocketmq.common.ServiceThread;
import com.alibaba.rocketmq.common.constant.LoggerName;
import com.alibaba.rocketmq.remoting.common.RemotingUtil;
import com.alibaba.rocketmq.store.SelectMapedBufferResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
/**
* @author shijia.wxr
*/
public class HAConnection {
private static final Logger log = LoggerFactory.getLogger(LoggerName.StoreLoggerName);
private final HAService haService;
private final SocketChannel socketChannel;
private final String clientAddr;
private WriteSocketService writeSocketService;
private ReadSocketService readSocketService;
private volatile long slaveRequestOffset = -1;
private volatile long slaveAckOffset = -1;
public HAConnection(final HAService haService, final SocketChannel socketChannel) throws IOException {
this.haService = haService;
this.socketChannel = socketChannel;
this.clientAddr = this.socketChannel.socket().getRemoteSocketAddress().toString();
this.socketChannel.configureBlocking(false);
this.socketChannel.socket().setSoLinger(false, -1);
this.socketChannel.socket().setTcpNoDelay(true);
this.socketChannel.socket().setReceiveBufferSize(1024 * 64);
this.socketChannel.socket().setSendBufferSize(1024 * 64);
this.writeSocketService = new WriteSocketService(this.socketChannel);
this.readSocketService = new ReadSocketService(this.socketChannel);
this.haService.getConnectionCount().incrementAndGet();
}
public void start() {
this.readSocketService.start();
this.writeSocketService.start();
}
public void shutdown() {
this.writeSocketService.shutdown(true);
this.readSocketService.shutdown(true);
this.close();
}
public void close() {
if (this.socketChannel != null) {
try {
this.socketChannel.close();
} catch (IOException e) {
HAConnection.log.error("", e);
}
}
}
public SocketChannel getSocketChannel() {
return socketChannel;
}
/**
*
* @author shijia.wxr
*/
class ReadSocketService extends ServiceThread {
private static final int ReadMaxBufferSize = 1024 * 1024;
private final Selector selector;
private final SocketChannel socketChannel;
private final ByteBuffer byteBufferRead = ByteBuffer.allocate(ReadMaxBufferSize);
private int processPostion = 0;
private volatile long lastReadTimestamp = System.currentTimeMillis();
public ReadSocketService(final SocketChannel socketChannel) throws IOException {
this.selector = RemotingUtil.openSelector();
this.socketChannel = socketChannel;
this.socketChannel.register(this.selector, SelectionKey.OP_READ);
this.thread.setDaemon(true);
}
@Override
public void run() {
HAConnection.log.info(this.getServiceName() + " service started");
while (!this.isStoped()) {
try {
this.selector.select(1000);
boolean ok = this.processReadEvent();
if (!ok) {
HAConnection.log.error("processReadEvent error");
break;
}
long interval = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now() - this.lastReadTimestamp;
if (interval > HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig().getHaHousekeepingInterval()) {
log.warn("ha housekeeping, found this connection[" + HAConnection.this.clientAddr + "] expired, " + interval);
break;
}
} catch (Exception e) {
HAConnection.log.error(this.getServiceName() + " service has exception.", e);
break;
}
}
this.makeStop();
writeSocketService.makeStop();
haService.removeConnection(HAConnection.this);
HAConnection.this.haService.getConnectionCount().decrementAndGet();
SelectionKey sk = this.socketChannel.keyFor(this.selector);
if (sk != null) {
sk.cancel();
}
try {
this.selector.close();
this.socketChannel.close();
} catch (IOException e) {
HAConnection.log.error("", e);
}
HAConnection.log.info(this.getServiceName() + " service end");
}
@Override
public String getServiceName() {
return ReadSocketService.class.getSimpleName();
}
private boolean processReadEvent() {
int readSizeZeroTimes = 0;
if (!this.byteBufferRead.hasRemaining()) {
this.byteBufferRead.flip();
this.processPostion = 0;
}
while (this.byteBufferRead.hasRemaining()) {
try {
int readSize = this.socketChannel.read(this.byteBufferRead);
if (readSize > 0) {
readSizeZeroTimes = 0;
this.lastReadTimestamp = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now();
if ((this.byteBufferRead.position() - this.processPostion) >= 8) {
int pos = this.byteBufferRead.position() - (this.byteBufferRead.position() % 8);
long readOffset = this.byteBufferRead.getLong(pos - 8);
this.processPostion = pos;
HAConnection.this.slaveAckOffset = readOffset;
if (HAConnection.this.slaveRequestOffset < 0) {
HAConnection.this.slaveRequestOffset = readOffset;
log.info("slave[" + HAConnection.this.clientAddr + "] request offset " + readOffset);
}
HAConnection.this.haService.notifyTransferSome(HAConnection.this.slaveAckOffset);
}
} else if (readSize == 0) {
if (++readSizeZeroTimes >= 3) {
break;
}
} else {
log.error("read socket[" + HAConnection.this.clientAddr + "] < 0");
return false;
}
} catch (IOException e) {
log.error("processReadEvent exception", e);
return false;
}
}
return true;
}
}
/**
*
* @author shijia.wxr
*/
class WriteSocketService extends ServiceThread {
private final Selector selector;
private final SocketChannel socketChannel;
private final int HEADER_SIZE = 8 + 4;
private final ByteBuffer byteBufferHeader = ByteBuffer.allocate(HEADER_SIZE);
private long nextTransferFromWhere = -1;
private SelectMapedBufferResult selectMapedBufferResult;
private boolean lastWriteOver = true;
private long lastWriteTimestamp = System.currentTimeMillis();
public WriteSocketService(final SocketChannel socketChannel) throws IOException {
this.selector = RemotingUtil.openSelector();
this.socketChannel = socketChannel;
this.socketChannel.register(this.selector, SelectionKey.OP_WRITE);
this.thread.setDaemon(true);
}
@Override
public void run() {
HAConnection.log.info(this.getServiceName() + " service started");
while (!this.isStoped()) {
try {
this.selector.select(1000);
if (-1 == HAConnection.this.slaveRequestOffset) {
Thread.sleep(10);
continue;
}
if (-1 == this.nextTransferFromWhere) {
if (0 == HAConnection.this.slaveRequestOffset) {
long masterOffset = HAConnection.this.haService.getDefaultMessageStore().getCommitLog().getMaxOffset();
masterOffset =
masterOffset
- (masterOffset % HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig()
.getMapedFileSizeCommitLog());
if (masterOffset < 0) {
masterOffset = 0;
}
this.nextTransferFromWhere = masterOffset;
} else {
this.nextTransferFromWhere = HAConnection.this.slaveRequestOffset;
}
log.info("master transfer data from " + this.nextTransferFromWhere + " to slave[" + HAConnection.this.clientAddr
+ "], and slave request " + HAConnection.this.slaveRequestOffset);
}
if (this.lastWriteOver) {
long interval =
HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now() - this.lastWriteTimestamp;
if (interval > HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig()
.getHaSendHeartbeatInterval()) {
// Build Header
this.byteBufferHeader.position(0);
this.byteBufferHeader.limit(HEADER_SIZE);
this.byteBufferHeader.putLong(this.nextTransferFromWhere);
this.byteBufferHeader.putInt(0);
this.byteBufferHeader.flip();
this.lastWriteOver = this.transferData();
if (!this.lastWriteOver)
continue;
}
}
else {
this.lastWriteOver = this.transferData();
if (!this.lastWriteOver)
continue;
}
SelectMapedBufferResult selectResult =
HAConnection.this.haService.getDefaultMessageStore().getCommitLogData(this.nextTransferFromWhere);
if (selectResult != null) {
int size = selectResult.getSize();
if (size > HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig().getHaTransferBatchSize()) {
size = HAConnection.this.haService.getDefaultMessageStore().getMessageStoreConfig().getHaTransferBatchSize();
}
long thisOffset = this.nextTransferFromWhere;
this.nextTransferFromWhere += size;
selectResult.getByteBuffer().limit(size);
this.selectMapedBufferResult = selectResult;
// Build Header
this.byteBufferHeader.position(0);
this.byteBufferHeader.limit(HEADER_SIZE);
this.byteBufferHeader.putLong(thisOffset);
this.byteBufferHeader.putInt(size);
this.byteBufferHeader.flip();
this.lastWriteOver = this.transferData();
} else {
HAConnection.this.haService.getWaitNotifyObject().allWaitForRunning(100);
}
} catch (Exception e) {
HAConnection.log.error(this.getServiceName() + " service has exception.", e);
break;
}
}
if (this.selectMapedBufferResult != null) {
this.selectMapedBufferResult.release();
}
this.makeStop();
readSocketService.makeStop();
haService.removeConnection(HAConnection.this);
SelectionKey sk = this.socketChannel.keyFor(this.selector);
if (sk != null) {
sk.cancel();
}
try {
this.selector.close();
this.socketChannel.close();
} catch (IOException e) {
HAConnection.log.error("", e);
}
HAConnection.log.info(this.getServiceName() + " service end");
}
/**
*/
private boolean transferData() throws Exception {
int writeSizeZeroTimes = 0;
// Write Header
while (this.byteBufferHeader.hasRemaining()) {
int writeSize = this.socketChannel.write(this.byteBufferHeader);
if (writeSize > 0) {
writeSizeZeroTimes = 0;
this.lastWriteTimestamp = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now();
} else if (writeSize == 0) {
if (++writeSizeZeroTimes >= 3) {
break;
}
} else {
throw new Exception("ha master write header error < 0");
}
}
if (null == this.selectMapedBufferResult) {
return !this.byteBufferHeader.hasRemaining();
}
writeSizeZeroTimes = 0;
// Write Body
if (!this.byteBufferHeader.hasRemaining()) {
while (this.selectMapedBufferResult.getByteBuffer().hasRemaining()) {
int writeSize = this.socketChannel.write(this.selectMapedBufferResult.getByteBuffer());
if (writeSize > 0) {
writeSizeZeroTimes = 0;
this.lastWriteTimestamp = HAConnection.this.haService.getDefaultMessageStore().getSystemClock().now();
} else if (writeSize == 0) {
if (++writeSizeZeroTimes >= 3) {
break;
}
} else {
throw new Exception("ha master write body error < 0");
}
}
}
boolean result = !this.byteBufferHeader.hasRemaining() && !this.selectMapedBufferResult.getByteBuffer().hasRemaining();
if (!this.selectMapedBufferResult.getByteBuffer().hasRemaining()) {
this.selectMapedBufferResult.release();
this.selectMapedBufferResult = null;
}
return result;
}
@Override
public String getServiceName() {
return WriteSocketService.class.getSimpleName();
}
@Override
public void shutdown() {
super.shutdown();
}
}
}
| |
package org.saucistophe.utils;
import java.awt.Color;
import java.util.List;
import org.apache.commons.math3.util.FastMath;
import org.saucistophe.geometry.twoDimensional.Point2F;
import org.saucistophe.math.MathUtils;
/**
Utils class to process colors.
*/
public class ColorUtils
{
/**
A HSVA channel type to refer to its various values.
*/
public enum HsvaChannelType
{
HUE, SATURATION, VALUE, ALPHA, ALPHA_TIMES_VALUE;
};
/**
Returns a value extracted from the input volor, that corresponds to the selected channel.
@param hsvaColor The color to get a value from.
@param channelType The desired channel.
@return The extracted value.
*/
public static float getValueFromChannel(float[] hsvaColor, HsvaChannelType channelType)
{
if(channelType.ordinal() <= 3)
return hsvaColor[channelType.ordinal()];
switch(channelType)
{
case ALPHA_TIMES_VALUE:
return hsvaColor[2] * hsvaColor[3];
default:
throw new IllegalArgumentException("Unknown value for channel type " + channelType);
}
}
/**
Transforms an ARGB value to a Color.
@param argb The ARGB value to transform.
@return The color.
*/
public static Color argbToColor(int argb)
{
int a = (argb & 0xFF000000) >>> 24;
int r = (argb & 0x00FF0000) >>> 16;
int g = (argb & 0x0000FF00) >>> 8;
int b = (argb & 0x000000FF);
return new Color(r, g, b, a);
}
/**
Transforms a [0,1] float value to a ARGB grey level value.
@param floatValue The value to convert.
@return A grey color between 0xFF000000 and 0xFFFFFFFF.
*/
public static int floatToArgbGrey(float floatValue)
{
int intValue = (int) (floatValue * 255) & 255;
int result = 0xFF000000;
result |= intValue;
result |= intValue << 8;
result |= intValue << 16;
return result;
}
/**
Turns an HSVA color (as an array of floats) into a RGBA color.
Note that the alpha value is optionnal; in which case a HSV value will turn to RGB.
@param hsva The HSVA color array, with each float 0-1.
@return The RGBA color, as 0-255 int values.
*/
public static int[] hsvaToRgba(float[] hsva)
{
int[] rgba = new int[hsva.length];
int rgbaInt = Color.HSBtoRGB(hsva[0], hsva[1], hsva[2]);
rgba[0] = (rgbaInt >> 16) & 255;
rgba[1] = (rgbaInt >> 8) & 255;
rgba[2] = (rgbaInt) & 255;
if (rgba.length >= 4)
rgba[3] = (int) (hsva[3] * 255);
return rgba;
}
/**
Turns an HSVA color (as an array of floats) into a RGBA color int.
Note that the alpha value is optionnal; in which case a HSV value will turn to RGB.
@param hsva The HSVA color array, with each float 0-1.
@return The RGBA color, as an int.
*/
public static int hsvaToRgbaInt(float[] hsva)
{
return Color.HSBtoRGB(hsva[0], hsva[1], hsva[2]);
}
/**
Turns an HSVA color (as an array of floats) into AWT Color.
Note that the alpha value is optionnal; in which case a HSV value will turn to RGB.
@param hsva The HSVA color array, with each float 0-1.
@return The RGBA color, as a AWT Color.
*/
public static Color hsvaToColor(float[] hsva)
{
return new Color(Color.HSBtoRGB(hsva[0], hsva[1], hsva[2]));
}
/**
Turns an RGBA color (as an array of int) into a HSVA color.
Note that the alpha value is optionnal; in which case a RGB value will turn to HSV.
@param rgba The RGBA color array, with each int 0-255.
@return The HSVA color.
*/
public static float[] rgbaToHsva(int[] rgba)
{
float[] hsva = new float[rgba.length];
Color.RGBtoHSB(rgba[0], rgba[1], rgba[2], hsva);
if (hsva.length >= 4)
hsva[3] = rgba[3] / 255f;
return hsva;
}
/**
Turns an RGBA color (as an hexadecimal int) into a HSVA color.
@param rgba The 0xRRGGBBAA color int.
@return The HSVA color.
*/
public static float[] rgbaToHsva(int rgba)
{
return rgbaToHsva(new int[]
{
(rgba >> 24) & 255, (rgba >> 16) & 255, (rgba >> 8) & 255, (rgba) & 255
});
}
/**
Turns an ARGB color (as an hexadecimal int) into a HSVA color.
@param argb The 0xAARRGGBB color int.
@return The HSVA color.
*/
public static float[] argbToHsva(int argb)
{
return rgbaToHsva(new int[]
{
(argb >> 16) & 255, (argb >> 8) & 255, (argb) & 255, (argb >> 24) & 255
});
}
/**
Transforms a part of a vector (-1,1) to a normal map part (0-255).
@param vectorValue The [1,1] value to transform.
@return The [0-255] output.
*/
public static int vectorToNormal(double vectorValue)
{
return (int) ((vectorValue / 2 + 0.5) * 255);
}
/**
Surimpose a color on another, according to their alphas.
https://en.wikipedia.org/wiki/Alpha_compositing
@param background The background HSVA color.
@param foreground The foreground HSVA color.
@return The surimposition of the foreground on the background.
*/
public static float[] surimposeHsvaColors(float[] background, float[] foreground)
{
// Skip transparent colors.
if(background[3] == 0 && foreground[3] == 0)
return background;
int[] a = hsvaToRgba(foreground);
int[] b = hsvaToRgba(background);
int alphaA = a[3];
int alphaB = b[3];
int commonDivider = alphaA + alphaB * (255 - alphaA) / 255;
// Skip transparent colors again, if the alpha turner out to be too small to be greater than 0 as int.
if(commonDivider == 0 )
return background;
b[0] = (a[0] * alphaA + b[0] * alphaB * (255 - alphaA) / 255) / commonDivider;
b[1] = (a[1] * alphaA + b[1] * alphaB * (255 - alphaA) / 255) / commonDivider;
b[2] = (a[2] * alphaA + b[2] * alphaB * (255 - alphaA) / 255) / commonDivider;
b[3] = commonDivider;
return ColorUtils.rgbaToHsva(b);
}
/**
Merges a list of HSVA colors, returning the average color.
Each point's value will make it contribute more or less to the result color.
@param colorsToMerge The list of colors to merge.
@return The average of the given colors.
*/
public static float[] mergeHsvColors(List<float[]> colorsToMerge)
{
assert (!colorsToMerge.isEmpty());
// First off, if there's only one color, return it verbatim.
if (colorsToMerge.size() == 1)
{
return colorsToMerge.get(0);
}
Point2F meanHsPoint = new Point2F(0, 0);
float result[] = new float[colorsToMerge.get(0).length];
for (float[] color : colorsToMerge)
{
// Compute average hue and saturation by interpolating vectors in HSV space.
meanHsPoint.x += color[2] * color[1] * FastMath.cos(color[0] * FastMath.PI * 2);
meanHsPoint.y += color[2] * color[1] * FastMath.sin(color[0] * FastMath.PI * 2);
// Copy value and alpha as a simple average.
result[2] = Math.max(result[2], color[2]);
if (result.length >= 4)
result[3] += color[3];
}
// Divide by the number of points to get the average.
meanHsPoint.multLocal(1f / colorsToMerge.size());
// Compute the average value.
result[0] = (float) (Math.atan2(meanHsPoint.y, meanHsPoint.x) / FastMath.PI / 2);
if (result[0] < 0)
{
result[0] = 1 + result[0];
}
result[1] = meanHsPoint.getNorm();
//result[2] /= numberOfPoints;
if (result.length >= 4)
result[3] /= colorsToMerge.size();
return result;
}
/**
@param hsva1 The first color to interpolate.
@param hsva2 The second color to interpolate.
@param coeff The interpolation coefficient. 0 means using hsva1, 1 means using hsva2.
@return The interpolation of the two colors.
*/
public static float[] interpolate(float[] hsva1, float[] hsva2, float coeff)
{
assert (0 <= coeff);
assert (coeff <= 1);
assert hsva1.length == hsva2.length;
float[] result = new float[hsva1.length];
// Simply interpolate value and alpha.
float coeff2 = 1 - coeff;
result[2] = hsva1[2] * coeff2 + coeff * hsva2[2];
if (hsva1.length >= 4)
result[3] = hsva1[3] * coeff2 + coeff * hsva2[3];
// Project both HS points to cartesian coordinates:
double theta1 = hsva1[0] * Math.PI * 2;
float x1 = (float) (hsva1[1] * Math.cos(theta1));
float y1 = (float) (hsva1[1] * Math.sin(theta1));
double theta2 = hsva2[0] * Math.PI * 2;
float x2 = (float) (hsva2[1] * Math.cos(theta2));
float y2 = (float) (hsva2[1] * Math.sin(theta2));
// Interpolate the cartesian coordinates
float newX = x1 * coeff2 + coeff * x2;
float newY = y1 * coeff2 + coeff * y2;
// Get the point back to HS space.
double newRho = Math.sqrt(newX * newX + newY * newY);
double newTheta = Math.atan2(newY, newX);
if (newTheta < 0)
newTheta += Math.PI * 2;
result[0] = (float) (newTheta / Math.PI / 2);
result[1] = (float) newRho;
return result;
}
/**
Returns the actual (as perceived by the eye) luminance of the color.
@param rgba The RGBA color.
@return Its (0-255) luminance.
*/
public static int getLuminance(int[] rgba)
{
return (rgba[0] + rgba[0] + rgba[1] + rgba[1] + rgba[1] + rgba[2]) * rgba[3] / 255 / 6;
}
/**
A temperature to color conversion, inspired from a blogpost from PhotoDemon
(http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/).
@param temperature The temperature of an ideal black body, in Kelvins;
@param alpha If true, the return value will be RGBA instead of RGB.
@return The corresponding RGB color.
*/
public static int[] getRgbFromTemperature(double temperature, boolean alpha)
{
// Temperature must fit between 1000 and 40000 degrees
temperature = MathUtils.clamp(temperature, 1000, 40000);
// All calculations require tmpKelvin \ 100, so only do the conversion once
temperature /= 100;
// Compute each color in turn.
int red, green, blue;
// First: red
if (temperature <= 66)
red = 255;
else
{
// Note: the R-squared value for this approximation is .988
red = (int) (329.698727446 * (Math.pow(temperature - 60, -0.1332047592)));
red = MathUtils.clamp(red, 0, 255);
}
// Second: green
if (temperature <= 66)
// Note: the R-squared value for this approximation is .996
green = (int) (99.4708025861 * Math.log(temperature) - 161.1195681661);
else
// Note: the R-squared value for this approximation is .987
green = (int) (288.1221695283 * (Math.pow(temperature - 60, -0.0755148492)));
green = MathUtils.clamp(green, 0, 255);
// Third: blue
if (temperature >= 66)
blue = 255;
else if (temperature <= 19)
blue = 0;
else
{
// Note: the R-squared value for this approximation is .998
blue = (int) (138.5177312231 * Math.log(temperature - 10) - 305.0447927307);
blue = MathUtils.clamp(blue, 0, 255);
}
if (alpha)
return new int[]
{
red, green, blue, 255
};
else
return new int[]
{
red, green, blue
};
}
}
| |
/*
* 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.ignite.internal.processors.cache;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.affinity.AffinityFunctionContext;
import org.apache.ignite.cache.affinity.AffinityKeyMapped;
import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.binary.BinaryMarshaller;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLocalPartition;
import org.apache.ignite.internal.util.lang.GridAbsPredicate;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi;
import org.apache.ignite.spi.failover.always.AlwaysFailoverSpi;
import org.apache.ignite.testframework.GridTestUtils;
import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
/**
* Base class of the tests to validate https://issues.apache.org/jira/browse/IGNITE-2310
*/
public class IgniteCacheLockPartitionOnAffinityRunAbstractTest extends GridCacheAbstractSelfTest {
/** Count of affinity run threads. */
protected static final int AFFINITY_THREADS_CNT = 10;
/** Count of collocated objects. */
protected static final int PERS_AT_ORG_CNT = 10_000;
/** Name of the cache with special affinity function (all partition are placed on the first node). */
protected static final String OTHER_CACHE_NAME = "otherCache";
/** Grid count. */
protected static final int GRID_CNT = 4;
/** Count of restarted nodes. */
protected static final int RESTARTED_NODE_CNT = 2;
/** Count of objects. */
protected static final int ORGS_COUNT_PER_NODE = 2;
/** Test duration. */
protected static final long TEST_DURATION = 5 * 60_000;
/** Test timeout. */
protected static final long TEST_TIMEOUT = TEST_DURATION + 2 * 60_000;
/** Timeout between restart of a node. */
protected static final long RESTART_TIMEOUT = 3_000;
/** Max failover attempts. */
protected static final int MAX_FAILOVER_ATTEMPTS = 100;
/** Organization ids. */
protected static List<Integer> orgIds;
/** Test end time. */
protected static long endTime;
/** Node restart thread future. */
protected static IgniteInternalFuture<?> nodeRestartFut;
/** Stop a test flag . */
protected final AtomicBoolean stopRestartThread = new AtomicBoolean();
/** {@inheritDoc} */
@Override protected long getTestTimeout() {
return TEST_TIMEOUT;
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
// Enables template with default test configuration
cfg.setCacheConfiguration(F.concat(cfg.getCacheConfiguration(), cacheConfiguration(igniteInstanceName).setName("*")));
((TcpCommunicationSpi)cfg.getCommunicationSpi()).setSharedMemoryPort(-1);
cfg.setMarshaller(new BinaryMarshaller());
AlwaysFailoverSpi failSpi = new AlwaysFailoverSpi();
failSpi.setMaximumFailoverAttempts(MAX_FAILOVER_ATTEMPTS);
cfg.setFailoverSpi(failSpi);
return cfg;
}
/** {@inheritDoc} */
@Override protected Class<?>[] indexedTypes() {
return new Class<?>[] {
Integer.class, Organization.class,
Person.Key.class, Person.class,
Integer.class, Integer.class
};
}
/** {@inheritDoc} */
@Override protected CacheAtomicityMode atomicityMode() {
return ATOMIC;
}
/** {@inheritDoc} */
@Override protected int gridCount() {
return GRID_CNT;
}
/** {@inheritDoc} */
@Override protected CacheMode cacheMode() {
return PARTITIONED;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
info("Fill caches begin...");
fillCaches();
info("Caches are filled");
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
grid(0).destroyCache(Organization.class.getSimpleName());
grid(0).destroyCache(Person.class.getSimpleName());
grid(0).destroyCache(OTHER_CACHE_NAME);
super.afterTestsStopped();
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
stopRestartThread.set(true);
if (nodeRestartFut != null) {
nodeRestartFut.get();
nodeRestartFut = null;
}
Thread.sleep(3_000);
awaitPartitionMapExchange();
super.afterTest();
}
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
endTime = System.currentTimeMillis() + TEST_DURATION;
super.beforeTest();
}
/**
* @param cacheName Cache name.
* @throws Exception If failed.
*/
private void createCacheWithAffinity(String cacheName) throws Exception {
CacheConfiguration ccfg = cacheConfiguration(grid(0).name());
ccfg.setName(cacheName);
ccfg.setAffinity(new DummyAffinity());
grid(0).createCache(ccfg);
}
/**
* @throws Exception If failed.
*/
protected void fillCaches() throws Exception {
grid(0).createCache(Organization.class.getSimpleName());
grid(0).createCache(Person.class.getSimpleName());
createCacheWithAffinity(OTHER_CACHE_NAME);
awaitPartitionMapExchange();
orgIds = new ArrayList<>(ORGS_COUNT_PER_NODE * RESTARTED_NODE_CNT);
for (int i = GRID_CNT - RESTARTED_NODE_CNT; i < GRID_CNT; ++i)
orgIds.addAll(primaryKeys(grid(i).cache(Organization.class.getSimpleName()), ORGS_COUNT_PER_NODE));
try (
IgniteDataStreamer<Integer, Organization> orgStreamer =
grid(0).dataStreamer(Organization.class.getSimpleName());
IgniteDataStreamer<Person.Key, Person> persStreamer =
grid(0).dataStreamer(Person.class.getSimpleName())) {
int persId = 0;
for (int orgId : orgIds) {
Organization org = new Organization(orgId);
orgStreamer.addData(orgId, org);
for (int persCnt = 0; persCnt < PERS_AT_ORG_CNT; ++persCnt, ++persId) {
Person pers = new Person(persId, orgId);
persStreamer.addData(pers.createKey(), pers);
}
}
}
awaitPartitionMapExchange();
}
/**
*
*/
protected void beginNodesRestart() {
stopRestartThread.set(false);
nodeRestartFut = GridTestUtils.runAsync(new Callable<Void>() {
@Override public Void call() throws Exception {
int restartGrid = GRID_CNT - RESTARTED_NODE_CNT;
while (!stopRestartThread.get() && System.currentTimeMillis() < endTime) {
log.info("Restart grid: " + restartGrid);
stopGrid(restartGrid);
Thread.sleep(500);
startGrid(restartGrid);
GridTestUtils.waitForCondition(new GridAbsPredicate() {
@Override public boolean apply() {
return !stopRestartThread.get();
}
}, RESTART_TIMEOUT);
restartGrid++;
if (restartGrid >= GRID_CNT)
restartGrid = GRID_CNT - RESTARTED_NODE_CNT;
awaitPartitionMapExchange();
}
return null;
}
}, "restart-node");
}
/**
* @param ignite Ignite.
* @param orgId Org id.
* @param expReservations Expected reservations.
* @throws Exception If failed.
*/
protected static void checkPartitionsReservations(final IgniteEx ignite, int orgId,
final int expReservations) throws Exception {
int part = ignite.affinity(Organization.class.getSimpleName()).partition(orgId);
final GridDhtLocalPartition pPers = ignite.context().cache()
.internalCache(Person.class.getSimpleName()).context().topology()
.localPartition(part, AffinityTopologyVersion.NONE, false);
assertNotNull(pPers);
final GridDhtLocalPartition pOrgs = ignite.context().cache()
.internalCache(Organization.class.getSimpleName()).context().topology()
.localPartition(part, AffinityTopologyVersion.NONE, false);
assertNotNull(pOrgs);
GridTestUtils.waitForCondition(new GridAbsPredicate() {
@Override public boolean apply() {
return expReservations == pOrgs.reservations() && expReservations == pPers.reservations();
}
}, 1000L);
assertEquals("Unexpected reservations count", expReservations, pOrgs.reservations());
assertEquals("Unexpected reservations count", expReservations, pPers.reservations());
}
/** */
private static class DummyAffinity extends RendezvousAffinityFunction {
/**
* Default constructor.
*/
public DummyAffinity() {
// No-op.
}
/** {@inheritDoc} */
@Override public List<List<ClusterNode>> assignPartitions(AffinityFunctionContext affCtx) {
List<ClusterNode> nodes = affCtx.currentTopologySnapshot();
List<List<ClusterNode>> assign = new ArrayList<>(partitions());
for (int i = 0; i < partitions(); ++i)
assign.add(Collections.singletonList(nodes.get(0)));
return assign;
}
}
/**
* Test class Organization.
*/
public static class Organization implements Serializable {
/** */
@QuerySqlField(index = true)
private final int id;
/**
* @param id ID.
*/
Organization(int id) {
this.id = id;
}
/**
* @return id.
*/
int getId() {
return id;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(Organization.class, this);
}
}
/**
* Test class Organization.
*/
public static class Person implements Serializable {
/** */
@QuerySqlField
private final int id;
/** */
@QuerySqlField(index = true)
private final int orgId;
/**
* @param id ID.
* @param orgId Organization ID.
*/
Person(int id, int orgId) {
this.id = id;
this.orgId = orgId;
}
/**
* @return id.
*/
int getId() {
return id;
}
/**
* @return organization id.
*/
int getOrgId() {
return orgId;
}
/**
* @return Affinity key.
*/
public Person.Key createKey() {
return new Person.Key(id, orgId);
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(Person.class, this);
}
/**
*
*/
static class Key implements Serializable {
/** Id. */
private final int id;
/** Org id. */
@AffinityKeyMapped
protected final int orgId;
/**
* @param id Id.
* @param orgId Org id.
*/
private Key(int id, int orgId) {
this.id = id;
this.orgId = orgId;
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Person.Key key = (Person.Key)o;
return id == key.id && orgId == key.orgId;
}
/** {@inheritDoc} */
@Override public int hashCode() {
int res = id;
res = 31 * res + orgId;
return res;
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType;
import org.apache.hadoop.hdfs.server.common.Storage;
import org.apache.hadoop.hdfs.server.common.Storage.StorageDirectory;
import org.apache.hadoop.hdfs.server.common.StorageErrorReporter;
import org.apache.hadoop.hdfs.server.common.StorageInfo;
import org.apache.hadoop.hdfs.server.namenode.FSEditLogLoader.EditLogValidation;
import org.apache.hadoop.hdfs.server.namenode.NNStorage.NameNodeFile;
import org.apache.hadoop.hdfs.server.namenode.NNStorageRetentionManager.StoragePurger;
import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
import org.apache.hadoop.hdfs.server.protocol.RemoteEditLog;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Lists;
/**
* Journal manager for the common case of edits files being written
* to a storage directory.
*
* Note: this class is not thread-safe and should be externally
* synchronized.
*/
@InterfaceAudience.Private
public class FileJournalManager implements JournalManager {
private static final Log LOG = LogFactory.getLog(FileJournalManager.class);
private final Configuration conf;
private final StorageDirectory sd;
private final StorageErrorReporter errorReporter;
private int outputBufferCapacity = 512*1024;
private static final Pattern EDITS_REGEX = Pattern.compile(
NameNodeFile.EDITS.getName() + "_(\\d+)-(\\d+)");
private static final Pattern EDITS_INPROGRESS_REGEX = Pattern.compile(
NameNodeFile.EDITS_INPROGRESS.getName() + "_(\\d+)");
private File currentInProgress = null;
@VisibleForTesting
StoragePurger purger
= new NNStorageRetentionManager.DeletionStoragePurger();
public FileJournalManager(Configuration conf, StorageDirectory sd,
StorageErrorReporter errorReporter) {
this.conf = conf;
this.sd = sd;
this.errorReporter = errorReporter;
}
@Override
public void close() throws IOException {}
@Override
public void format(NamespaceInfo ns) throws IOException {
// Formatting file journals is done by the StorageDirectory
// format code, since they may share their directory with
// checkpoints, etc.
throw new UnsupportedOperationException();
}
@Override
public boolean hasSomeData() {
// Formatting file journals is done by the StorageDirectory
// format code, since they may share their directory with
// checkpoints, etc.
throw new UnsupportedOperationException();
}
@Override
synchronized public EditLogOutputStream startLogSegment(long txid,
int layoutVersion) throws IOException {
try {
currentInProgress = NNStorage.getInProgressEditsFile(sd, txid);
EditLogOutputStream stm = new EditLogFileOutputStream(conf,
currentInProgress, outputBufferCapacity);
stm.create(layoutVersion);
return stm;
} catch (IOException e) {
LOG.warn("Unable to start log segment " + txid +
" at " + currentInProgress + ": " +
e.getLocalizedMessage());
errorReporter.reportErrorOnFile(currentInProgress);
throw e;
}
}
@Override
synchronized public void finalizeLogSegment(long firstTxId, long lastTxId)
throws IOException {
File inprogressFile = NNStorage.getInProgressEditsFile(sd, firstTxId);
File dstFile = NNStorage.getFinalizedEditsFile(
sd, firstTxId, lastTxId);
LOG.info("Finalizing edits file " + inprogressFile + " -> " + dstFile);
Preconditions.checkState(!dstFile.exists(),
"Can't finalize edits file " + inprogressFile + " since finalized file " +
"already exists");
if (!inprogressFile.renameTo(dstFile)) {
errorReporter.reportErrorOnFile(dstFile);
throw new IllegalStateException("Unable to finalize edits file " + inprogressFile);
}
if (inprogressFile.equals(currentInProgress)) {
currentInProgress = null;
}
}
@VisibleForTesting
public StorageDirectory getStorageDirectory() {
return sd;
}
@Override
synchronized public void setOutputBufferCapacity(int size) {
this.outputBufferCapacity = size;
}
@Override
public void purgeLogsOlderThan(long minTxIdToKeep)
throws IOException {
LOG.info("Purging logs older than " + minTxIdToKeep);
File[] files = FileUtil.listFiles(sd.getCurrentDir());
List<EditLogFile> editLogs =
FileJournalManager.matchEditLogs(files);
for (EditLogFile log : editLogs) {
if (log.getFirstTxId() < minTxIdToKeep &&
log.getLastTxId() < minTxIdToKeep) {
purger.purgeLog(log);
}
}
}
/**
* Find all editlog segments starting at or above the given txid.
* @param fromTxId the txnid which to start looking
* @param inProgressOk whether or not to include the in-progress edit log
* segment
* @return a list of remote edit logs
* @throws IOException if edit logs cannot be listed.
*/
public List<RemoteEditLog> getRemoteEditLogs(long firstTxId,
boolean inProgressOk) throws IOException {
File currentDir = sd.getCurrentDir();
List<EditLogFile> allLogFiles = matchEditLogs(currentDir);
List<RemoteEditLog> ret = Lists.newArrayListWithCapacity(
allLogFiles.size());
for (EditLogFile elf : allLogFiles) {
if (elf.hasCorruptHeader() || (!inProgressOk && elf.isInProgress())) {
continue;
}
if (elf.getFirstTxId() >= firstTxId) {
ret.add(new RemoteEditLog(elf.firstTxId, elf.lastTxId));
} else if (elf.getFirstTxId() < firstTxId && firstTxId <= elf.getLastTxId()) {
// If the firstTxId is in the middle of an edit log segment. Return this
// anyway and let the caller figure out whether it wants to use it.
ret.add(new RemoteEditLog(elf.firstTxId, elf.lastTxId));
}
}
Collections.sort(ret);
return ret;
}
/**
* Discard all editlog segments whose first txid is greater than or equal to
* the given txid, by renaming them with suffix ".trash".
*/
private void discardEditLogSegments(long startTxId) throws IOException {
File currentDir = sd.getCurrentDir();
List<EditLogFile> allLogFiles = matchEditLogs(currentDir);
List<EditLogFile> toTrash = Lists.newArrayList();
LOG.info("Discard the EditLog files, the given start txid is " + startTxId);
// go through the editlog files to make sure the startTxId is right at the
// segment boundary
for (EditLogFile elf : allLogFiles) {
if (elf.getFirstTxId() >= startTxId) {
toTrash.add(elf);
} else {
Preconditions.checkState(elf.getLastTxId() < startTxId);
}
}
for (EditLogFile elf : toTrash) {
// rename these editlog file as .trash
elf.moveAsideTrashFile(startTxId);
LOG.info("Trash the EditLog file " + elf);
}
}
/**
* returns matching edit logs via the log directory. Simple helper function
* that lists the files in the logDir and calls matchEditLogs(File[])
*
* @param logDir
* directory to match edit logs in
* @return matched edit logs
* @throws IOException
* IOException thrown for invalid logDir
*/
public static List<EditLogFile> matchEditLogs(File logDir) throws IOException {
return matchEditLogs(FileUtil.listFiles(logDir));
}
static List<EditLogFile> matchEditLogs(File[] filesInStorage) {
List<EditLogFile> ret = Lists.newArrayList();
for (File f : filesInStorage) {
String name = f.getName();
// Check for edits
Matcher editsMatch = EDITS_REGEX.matcher(name);
if (editsMatch.matches()) {
try {
long startTxId = Long.valueOf(editsMatch.group(1));
long endTxId = Long.valueOf(editsMatch.group(2));
ret.add(new EditLogFile(f, startTxId, endTxId));
} catch (NumberFormatException nfe) {
LOG.error("Edits file " + f + " has improperly formatted " +
"transaction ID");
// skip
}
}
// Check for in-progress edits
Matcher inProgressEditsMatch = EDITS_INPROGRESS_REGEX.matcher(name);
if (inProgressEditsMatch.matches()) {
try {
long startTxId = Long.valueOf(inProgressEditsMatch.group(1));
ret.add(
new EditLogFile(f, startTxId, HdfsConstants.INVALID_TXID, true));
} catch (NumberFormatException nfe) {
LOG.error("In-progress edits file " + f + " has improperly " +
"formatted transaction ID");
// skip
}
}
}
return ret;
}
@Override
synchronized public void selectInputStreams(
Collection<EditLogInputStream> streams, long fromTxId,
boolean inProgressOk) throws IOException {
List<EditLogFile> elfs = matchEditLogs(sd.getCurrentDir());
LOG.debug(this + ": selecting input streams starting at " + fromTxId +
(inProgressOk ? " (inProgress ok) " : " (excluding inProgress) ") +
"from among " + elfs.size() + " candidate file(s)");
addStreamsToCollectionFromFiles(elfs, streams, fromTxId, inProgressOk);
}
static void addStreamsToCollectionFromFiles(Collection<EditLogFile> elfs,
Collection<EditLogInputStream> streams, long fromTxId, boolean inProgressOk) {
for (EditLogFile elf : elfs) {
if (elf.isInProgress()) {
if (!inProgressOk) {
LOG.debug("passing over " + elf + " because it is in progress " +
"and we are ignoring in-progress logs.");
continue;
}
try {
elf.validateLog();
} catch (IOException e) {
LOG.error("got IOException while trying to validate header of " +
elf + ". Skipping.", e);
continue;
}
}
if (elf.lastTxId < fromTxId) {
assert elf.lastTxId != HdfsConstants.INVALID_TXID;
LOG.debug("passing over " + elf + " because it ends at " +
elf.lastTxId + ", but we only care about transactions " +
"as new as " + fromTxId);
continue;
}
EditLogFileInputStream elfis = new EditLogFileInputStream(elf.getFile(),
elf.getFirstTxId(), elf.getLastTxId(), elf.isInProgress());
LOG.debug("selecting edit log stream " + elf);
streams.add(elfis);
}
}
@Override
synchronized public void recoverUnfinalizedSegments() throws IOException {
File currentDir = sd.getCurrentDir();
LOG.info("Recovering unfinalized segments in " + currentDir);
List<EditLogFile> allLogFiles = matchEditLogs(currentDir);
for (EditLogFile elf : allLogFiles) {
if (elf.getFile().equals(currentInProgress)) {
continue;
}
if (elf.isInProgress()) {
// If the file is zero-length, we likely just crashed after opening the
// file, but before writing anything to it. Safe to delete it.
if (elf.getFile().length() == 0) {
LOG.info("Deleting zero-length edit log file " + elf);
if (!elf.getFile().delete()) {
throw new IOException("Unable to delete file " + elf.getFile());
}
continue;
}
elf.validateLog();
if (elf.hasCorruptHeader()) {
elf.moveAsideCorruptFile();
throw new CorruptionException("In-progress edit log file is corrupt: "
+ elf);
}
if (elf.getLastTxId() == HdfsConstants.INVALID_TXID) {
// If the file has a valid header (isn't corrupt) but contains no
// transactions, we likely just crashed after opening the file and
// writing the header, but before syncing any transactions. Safe to
// delete the file.
LOG.info("Moving aside edit log file that seems to have zero " +
"transactions " + elf);
elf.moveAsideEmptyFile();
continue;
}
finalizeLogSegment(elf.getFirstTxId(), elf.getLastTxId());
}
}
}
public List<EditLogFile> getLogFiles(long fromTxId) throws IOException {
File currentDir = sd.getCurrentDir();
List<EditLogFile> allLogFiles = matchEditLogs(currentDir);
List<EditLogFile> logFiles = Lists.newArrayList();
for (EditLogFile elf : allLogFiles) {
if (fromTxId <= elf.getFirstTxId() ||
elf.containsTxId(fromTxId)) {
logFiles.add(elf);
}
}
Collections.sort(logFiles, EditLogFile.COMPARE_BY_START_TXID);
return logFiles;
}
public EditLogFile getLogFile(long startTxId) throws IOException {
return getLogFile(sd.getCurrentDir(), startTxId);
}
public static EditLogFile getLogFile(File dir, long startTxId)
throws IOException {
List<EditLogFile> files = matchEditLogs(dir);
List<EditLogFile> ret = Lists.newLinkedList();
for (EditLogFile elf : files) {
if (elf.getFirstTxId() == startTxId) {
ret.add(elf);
}
}
if (ret.isEmpty()) {
// no matches
return null;
} else if (ret.size() == 1) {
return ret.get(0);
} else {
throw new IllegalStateException("More than one log segment in " +
dir + " starting at txid " + startTxId + ": " +
Joiner.on(", ").join(ret));
}
}
@Override
public String toString() {
return String.format("FileJournalManager(root=%s)", sd.getRoot());
}
/**
* Record of an edit log that has been located and had its filename parsed.
*/
@InterfaceAudience.Private
public static class EditLogFile {
private File file;
private final long firstTxId;
private long lastTxId;
private boolean hasCorruptHeader = false;
private final boolean isInProgress;
final static Comparator<EditLogFile> COMPARE_BY_START_TXID
= new Comparator<EditLogFile>() {
@Override
public int compare(EditLogFile a, EditLogFile b) {
return ComparisonChain.start()
.compare(a.getFirstTxId(), b.getFirstTxId())
.compare(a.getLastTxId(), b.getLastTxId())
.result();
}
};
EditLogFile(File file,
long firstTxId, long lastTxId) {
this(file, firstTxId, lastTxId, false);
assert (lastTxId != HdfsConstants.INVALID_TXID)
&& (lastTxId >= firstTxId);
}
EditLogFile(File file, long firstTxId,
long lastTxId, boolean isInProgress) {
assert (lastTxId == HdfsConstants.INVALID_TXID && isInProgress)
|| (lastTxId != HdfsConstants.INVALID_TXID && lastTxId >= firstTxId);
assert (firstTxId > 0) || (firstTxId == HdfsConstants.INVALID_TXID);
assert file != null;
Preconditions.checkArgument(!isInProgress ||
lastTxId == HdfsConstants.INVALID_TXID);
this.firstTxId = firstTxId;
this.lastTxId = lastTxId;
this.file = file;
this.isInProgress = isInProgress;
}
public long getFirstTxId() {
return firstTxId;
}
public long getLastTxId() {
return lastTxId;
}
boolean containsTxId(long txId) {
return firstTxId <= txId && txId <= lastTxId;
}
/**
* Find out where the edit log ends.
* This will update the lastTxId of the EditLogFile or
* mark it as corrupt if it is.
*/
public void validateLog() throws IOException {
EditLogValidation val = EditLogFileInputStream.validateEditLog(file);
this.lastTxId = val.getEndTxId();
this.hasCorruptHeader = val.hasCorruptHeader();
}
public void scanLog() throws IOException {
EditLogValidation val = EditLogFileInputStream.scanEditLog(file);
this.lastTxId = val.getEndTxId();
this.hasCorruptHeader = val.hasCorruptHeader();
}
public boolean isInProgress() {
return isInProgress;
}
public File getFile() {
return file;
}
boolean hasCorruptHeader() {
return hasCorruptHeader;
}
void moveAsideCorruptFile() throws IOException {
assert hasCorruptHeader;
renameSelf(".corrupt");
}
void moveAsideTrashFile(long markerTxid) throws IOException {
assert this.getFirstTxId() >= markerTxid;
renameSelf(".trash");
}
public void moveAsideEmptyFile() throws IOException {
assert lastTxId == HdfsConstants.INVALID_TXID;
renameSelf(".empty");
}
private void renameSelf(String newSuffix) throws IOException {
File src = file;
File dst = new File(src.getParent(), src.getName() + newSuffix);
boolean success = src.renameTo(dst);
if (!success) {
throw new IOException(
"Couldn't rename log " + src + " to " + dst);
}
file = dst;
}
@Override
public String toString() {
return String.format("EditLogFile(file=%s,first=%019d,last=%019d,"
+"inProgress=%b,hasCorruptHeader=%b)",
file.toString(), firstTxId, lastTxId,
isInProgress(), hasCorruptHeader);
}
}
@Override
public void discardSegments(long startTxid) throws IOException {
discardEditLogSegments(startTxid);
}
@Override
public void doPreUpgrade() throws IOException {
LOG.info("Starting upgrade of edits directory " + sd.getRoot());
try {
NNUpgradeUtil.doPreUpgrade(sd);
} catch (IOException ioe) {
LOG.error("Failed to move aside pre-upgrade storage " +
"in image directory " + sd.getRoot(), ioe);
throw ioe;
}
}
/**
* This method assumes that the fields of the {@link Storage} object have
* already been updated to the appropriate new values for the upgrade.
*/
@Override
public void doUpgrade(Storage storage) throws IOException {
NNUpgradeUtil.doUpgrade(sd, storage);
}
@Override
public void doFinalize() throws IOException {
NNUpgradeUtil.doFinalize(sd);
}
@Override
public boolean canRollBack(StorageInfo storage, StorageInfo prevStorage,
int targetLayoutVersion) throws IOException {
return NNUpgradeUtil.canRollBack(sd, storage,
prevStorage, targetLayoutVersion);
}
@Override
public void doRollback() throws IOException {
NNUpgradeUtil.doRollBack(sd);
}
@Override
public long getJournalCTime() throws IOException {
StorageInfo sInfo = new StorageInfo((NodeType)null);
sInfo.readProperties(sd);
return sInfo.getCTime();
}
}
| |
package cx.it.nullpo.nm9.engine.game;
import java.io.Serializable;
import java.util.ArrayList;
import cx.it.nullpo.nm9.engine.common.Copyable;
import cx.it.nullpo.nm9.engine.common.NRandom;
import cx.it.nullpo.nm9.engine.definition.Game;
import cx.it.nullpo.nm9.engine.definition.Piece;
import cx.it.nullpo.nm9.engine.definition.PieceState;
import cx.it.nullpo.nm9.engine.definition.XYPair;
/**
* The onscreen piece
* @author NullNoname
*/
public class RuntimePiece implements Serializable, Copyable {
private static final long serialVersionUID = -2744397138078475043L;
/**
* Definition of the piece
*/
private Piece pieceDef;
/**
* Blocks in the piece
*/
private RuntimeBlock[] blocks;
public RuntimePiece() {
}
public RuntimePiece(Game gameDef, Piece pieceDef, NRandom random) {
this.pieceDef = pieceDef;
ArrayList<String> blkNameList = new ArrayList<String>();
if(pieceDef.isRandomizeBlock()) {
// Randomize the block list
while(blkNameList.size() < pieceDef.getBlocks().size()) {
blkNameList.add(pieceDef.getBlocks().get(random.nextInt(pieceDef.getBlocks().size())));
}
} else {
blkNameList.addAll(pieceDef.getBlocks());
}
// Set the number of blocks
int numBlocks = pieceDef.getNumBlocks();
if(numBlocks <= 0) {
int n = blkNameList.size();
for(PieceState state: pieceDef.getStates()) {
n = Math.min(n, state.getBlockPosList().size());
}
numBlocks = n;
}
blocks = new RuntimeBlock[numBlocks];
for(int i = 0; i < numBlocks; i++) {
String blkName = blkNameList.get(i);
blocks[i] = new RuntimeBlock(gameDef, blkName);
}
}
public RuntimePiece(Copyable src) {
copy(src);
}
public void copy(Copyable src) {
RuntimePiece s = (RuntimePiece)src;
this.pieceDef = new Piece(s.pieceDef);
this.blocks = new RuntimeBlock[s.blocks.length];
for(int i = 0; i < s.blocks.length; i++) {
this.blocks[i] = new RuntimeBlock(s.blocks[i]);
}
}
public int getNumBlocks() {
if(blocks == null) return -1;
return blocks.length;
}
public int getNumStates() {
if(pieceDef == null) return -1;
return pieceDef.getStates().size();
}
public XYPair getBlockPosition(int stateID, int blockID) {
return pieceDef.getStates().get(stateID).getBlockPosList().get(blockID);
}
public int getBlockPositionX(int stateID, int blockID) {
return getBlockPosition(stateID, blockID).getX();
}
public int getBlockPositionY(int stateID, int blockID) {
return getBlockPosition(stateID, blockID).getY();
}
public boolean isBlockConnectUp(int stateID, int blockID) {
if(pieceDef.getConnectionType().equals("None")) return false;
boolean sameBlockRequired = pieceDef.getConnectionType().equals("SameBlock");
int x = getBlockPositionX(stateID, blockID);
int y = getBlockPositionY(stateID, blockID);
RuntimeBlock b = getRuntimeBlock(blockID);
for(int i = 0; i < blocks.length; i++) {
if(i != blockID) {
int x2 = getBlockPositionX(stateID, i);
int y2 = getBlockPositionY(stateID, i);
RuntimeBlock b2 = getRuntimeBlock(i);
if(x2 == x && y2 == y - 1 && (!sameBlockRequired || b.getBlockDef().getName().equals(b2.getBlockDef().getName())))
return true;
}
}
return false;
}
public boolean isBlockConnectDown(int stateID, int blockID) {
if(pieceDef.getConnectionType().equals("None")) return false;
boolean sameBlockRequired = pieceDef.getConnectionType().equals("SameBlock");
int x = getBlockPositionX(stateID, blockID);
int y = getBlockPositionY(stateID, blockID);
RuntimeBlock b = getRuntimeBlock(blockID);
for(int i = 0; i < blocks.length; i++) {
if(i != blockID) {
int x2 = getBlockPositionX(stateID, i);
int y2 = getBlockPositionY(stateID, i);
RuntimeBlock b2 = getRuntimeBlock(i);
if(x2 == x && y2 == y + 1 && (!sameBlockRequired || b.getBlockDef().getName().equals(b2.getBlockDef().getName())))
return true;
}
}
return false;
}
public boolean isBlockConnectLeft(int stateID, int blockID) {
if(pieceDef.getConnectionType().equals("None")) return false;
boolean sameBlockRequired = pieceDef.getConnectionType().equals("SameBlock");
int x = getBlockPositionX(stateID, blockID);
int y = getBlockPositionY(stateID, blockID);
RuntimeBlock b = getRuntimeBlock(blockID);
for(int i = 0; i < blocks.length; i++) {
if(i != blockID) {
int x2 = getBlockPositionX(stateID, i);
int y2 = getBlockPositionY(stateID, i);
RuntimeBlock b2 = getRuntimeBlock(i);
if(x2 == x - 1 && y2 == y && (!sameBlockRequired || b.getBlockDef().getName().equals(b2.getBlockDef().getName())))
return true;
}
}
return false;
}
public boolean isBlockConnectRight(int stateID, int blockID) {
if(pieceDef.getConnectionType().equals("None")) return false;
boolean sameBlockRequired = pieceDef.getConnectionType().equals("SameBlock");
int x = getBlockPositionX(stateID, blockID);
int y = getBlockPositionY(stateID, blockID);
RuntimeBlock b = getRuntimeBlock(blockID);
for(int i = 0; i < blocks.length; i++) {
if(i != blockID) {
int x2 = getBlockPositionX(stateID, i);
int y2 = getBlockPositionY(stateID, i);
RuntimeBlock b2 = getRuntimeBlock(i);
if(x2 == x + 1 && y2 == y && (!sameBlockRequired || b.getBlockDef().getName().equals(b2.getBlockDef().getName())))
return true;
}
}
return false;
}
public Piece getPieceDef() {
return pieceDef;
}
public void setPieceDef(Piece pieceDef) {
this.pieceDef = pieceDef;
}
public RuntimeBlock[] getBlocks() {
return blocks;
}
public void setBlocks(RuntimeBlock[] blocks) {
this.blocks = blocks;
}
public RuntimeBlock getRuntimeBlock(int blockID) {
return blocks[blockID];
}
public void setRuntimeBlock(int blockID, RuntimeBlock b) {
blocks[blockID] = b;
}
public int getMinBlockPositionX(int stateID) {
int m = Integer.MAX_VALUE;
for(int i = 0; i < getNumBlocks(); i++) {
m = Math.min(m, getBlockPositionX(stateID, i));
}
return m;
}
public int getMaxBlockPositionX(int stateID) {
int m = Integer.MIN_VALUE;
for(int i = 0; i < getNumBlocks(); i++) {
m = Math.max(m, getBlockPositionX(stateID, i));
}
return m;
}
public int getMinBlockPositionY(int stateID) {
int m = Integer.MAX_VALUE;
for(int i = 0; i < getNumBlocks(); i++) {
m = Math.min(m, getBlockPositionY(stateID, i));
}
return m;
}
public int getMaxBlockPositionY(int stateID) {
int m = Integer.MIN_VALUE;
for(int i = 0; i < getNumBlocks(); i++) {
m = Math.max(m, getBlockPositionY(stateID, i));
}
return m;
}
public int getWidth(int stateID) {
return (getMaxBlockPositionX(stateID) - getMinBlockPositionX(stateID)) + 1;
}
public int getWidth() {
int m = 0;
for(int i = 0; i < getNumStates(); i++) {
m = Math.max(m, getWidth(i));
}
return m;
}
public int getHeight(int stateID) {
return (getMaxBlockPositionY(stateID) - getMinBlockPositionY(stateID)) + 1;
}
public int getHeight() {
int m = 0;
for(int i = 0; i < getNumStates(); i++) {
m = Math.max(m, getHeight(i));
}
return m;
}
public boolean fieldCollision(Field fld, int x, int y, int stateID) {
for(int i = 0; i < blocks.length; i++) {
XYPair blkPos = getBlockPosition(stateID, i);
if(!fld.isEmpty(x + blkPos.getX(), y + blkPos.getY())) {
return true;
}
}
return false;
}
public boolean fieldFullLockout(Field fld, int x, int y, int stateID) {
for(int i = 0; i < blocks.length; i++) {
XYPair blkPos = getBlockPosition(stateID, i);
int coordType = fld.getCoordType(x + blkPos.getX(), y + blkPos.getY());
if(coordType == Field.COORD_NORMAL || coordType == Field.COORD_WALL)
return false;
}
return true;
}
public boolean fieldPartialLockout(Field fld, int x, int y, int stateID) {
for(int i = 0; i < blocks.length; i++) {
XYPair blkPos = getBlockPosition(stateID, i);
int coordType = fld.getCoordType(x + blkPos.getX(), y + blkPos.getY());
if(coordType == Field.COORD_HIDDEN || coordType == Field.COORD_VANISH)
return true;
}
return false;
}
public int fieldPut(Field fld, int x, int y, int stateID, long internalTime, long gameTime) {
int putCount = 0;
for(int i = 0; i < blocks.length; i++) {
RuntimeBlock blk = new RuntimeBlock(blocks[i].getBlockDef());
blk.setPlaceInternalTime(internalTime);
blk.setPlaceGameTime(gameTime);
blk.setConnectUp(isBlockConnectUp(stateID, i));
blk.setConnectDown(isBlockConnectDown(stateID, i));
blk.setConnectLeft(isBlockConnectLeft(stateID, i));
blk.setConnectRight(isBlockConnectRight(stateID, i));
XYPair blkPos = getBlockPosition(stateID, i);
if(fld.setBlock(x + blkPos.getX(), y + blkPos.getY(), blk))
putCount++;
}
return putCount;
}
public int fieldBottom(Field fld, int x, int y, int stateID) {
int y2 = y;
while(!fieldCollision(fld, x, y2, stateID)) y2++;
return y2 - 1;
}
public int fieldFarLeft(Field fld, int x, int y, int stateID) {
int x2 = x;
while(!fieldCollision(fld, x2, y, stateID)) x2--;
return x2 + 1;
}
public int fieldFarRight(Field fld, int x, int y, int stateID) {
int x2 = x;
while(!fieldCollision(fld, x2, y, stateID)) x2++;
return x2 - 1;
}
public int getRotateAfterState(int beforeState, int rot) {
int afterState = beforeState + rot;
if(afterState < 0) {
afterState = getNumStates() - 1;
} else if(afterState >= getNumStates()) {
afterState = afterState - getNumStates();
}
return afterState;
}
}
| |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.client;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import io.druid.jackson.DefaultObjectMapper;
import io.druid.segment.IndexIO;
import io.druid.timeline.DataSegment;
import io.druid.timeline.partition.NoneShardSpec;
import io.druid.timeline.partition.SingleDimensionShardSpec;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*/
public class DataSegmentTest
{
final ObjectMapper mapper = new DefaultObjectMapper();
@Test
public void testV1Serialization() throws Exception
{
final Interval interval = new Interval("2011-10-01/2011-10-02");
final ImmutableMap<String, Object> loadSpec = ImmutableMap.<String, Object>of("something", "or_other");
DataSegment segment = new DataSegment(
"something",
interval,
"1",
loadSpec,
Arrays.asList("dim1", "dim2"),
Arrays.asList("met1", "met2"),
new NoneShardSpec(),
IndexIO.CURRENT_VERSION_ID,
1
);
final Map<String, Object> objectMap = mapper.readValue(mapper.writeValueAsString(segment), new TypeReference<Map<String, Object>>(){});
Assert.assertEquals(10, objectMap.size());
Assert.assertEquals("something", objectMap.get("dataSource"));
Assert.assertEquals(interval.toString(), objectMap.get("interval"));
Assert.assertEquals("1", objectMap.get("version"));
Assert.assertEquals(loadSpec, objectMap.get("loadSpec"));
Assert.assertEquals("dim1,dim2", objectMap.get("dimensions"));
Assert.assertEquals("met1,met2", objectMap.get("metrics"));
Assert.assertEquals(ImmutableMap.of("type", "none"), objectMap.get("shardSpec"));
Assert.assertEquals(IndexIO.CURRENT_VERSION_ID, objectMap.get("binaryVersion"));
Assert.assertEquals(1, objectMap.get("size"));
DataSegment deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class);
Assert.assertEquals(segment.getDataSource(), deserializedSegment.getDataSource());
Assert.assertEquals(segment.getInterval(), deserializedSegment.getInterval());
Assert.assertEquals(segment.getVersion(), deserializedSegment.getVersion());
Assert.assertEquals(segment.getLoadSpec(), deserializedSegment.getLoadSpec());
Assert.assertEquals(segment.getDimensions(), deserializedSegment.getDimensions());
Assert.assertEquals(segment.getMetrics(), deserializedSegment.getMetrics());
Assert.assertEquals(segment.getShardSpec(), deserializedSegment.getShardSpec());
Assert.assertEquals(segment.getSize(), deserializedSegment.getSize());
Assert.assertEquals(segment.getIdentifier(), deserializedSegment.getIdentifier());
deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class);
Assert.assertEquals(0, segment.compareTo(deserializedSegment));
deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class);
Assert.assertEquals(0, deserializedSegment.compareTo(segment));
deserializedSegment = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class);
Assert.assertEquals(segment.hashCode(), deserializedSegment.hashCode());
}
@Test
public void testIdentifier()
{
final DataSegment segment = DataSegment.builder()
.dataSource("foo")
.interval(new Interval("2012-01-01/2012-01-02"))
.version(new DateTime("2012-01-01T11:22:33.444Z").toString())
.shardSpec(new NoneShardSpec())
.build();
Assert.assertEquals(
"foo_2012-01-01T00:00:00.000Z_2012-01-02T00:00:00.000Z_2012-01-01T11:22:33.444Z",
segment.getIdentifier()
);
}
@Test
public void testIdentifierWithZeroPartition()
{
final DataSegment segment = DataSegment.builder()
.dataSource("foo")
.interval(new Interval("2012-01-01/2012-01-02"))
.version(new DateTime("2012-01-01T11:22:33.444Z").toString())
.shardSpec(new SingleDimensionShardSpec("bar", null, "abc", 0))
.build();
Assert.assertEquals(
"foo_2012-01-01T00:00:00.000Z_2012-01-02T00:00:00.000Z_2012-01-01T11:22:33.444Z",
segment.getIdentifier()
);
}
@Test
public void testIdentifierWithNonzeroPartition()
{
final DataSegment segment = DataSegment.builder()
.dataSource("foo")
.interval(new Interval("2012-01-01/2012-01-02"))
.version(new DateTime("2012-01-01T11:22:33.444Z").toString())
.shardSpec(new SingleDimensionShardSpec("bar", "abc", "def", 1))
.build();
Assert.assertEquals(
"foo_2012-01-01T00:00:00.000Z_2012-01-02T00:00:00.000Z_2012-01-01T11:22:33.444Z_1",
segment.getIdentifier()
);
}
@Test
public void testV1SerializationNullMetrics() throws Exception
{
final DataSegment segment = DataSegment.builder()
.dataSource("foo")
.interval(new Interval("2012-01-01/2012-01-02"))
.version(new DateTime("2012-01-01T11:22:33.444Z").toString())
.build();
final DataSegment segment2 = mapper.readValue(mapper.writeValueAsString(segment), DataSegment.class);
Assert.assertEquals("empty dimensions", ImmutableList.of(), segment2.getDimensions());
Assert.assertEquals("empty metrics", ImmutableList.of(), segment2.getMetrics());
}
@Test
public void testBucketMonthComparator() throws Exception
{
DataSegment[] sortedOrder = {
makeDataSegment("test1", "2011-01-01/2011-01-02", "a"),
makeDataSegment("test1", "2011-01-02/2011-01-03", "a"),
makeDataSegment("test1", "2011-01-02/2011-01-03", "b"),
makeDataSegment("test2", "2011-01-01/2011-01-02", "a"),
makeDataSegment("test2", "2011-01-02/2011-01-03", "a"),
makeDataSegment("test1", "2011-02-01/2011-02-02", "a"),
makeDataSegment("test1", "2011-02-02/2011-02-03", "a"),
makeDataSegment("test1", "2011-02-02/2011-02-03", "b"),
makeDataSegment("test2", "2011-02-01/2011-02-02", "a"),
makeDataSegment("test2", "2011-02-02/2011-02-03", "a"),
};
List<DataSegment> shuffled = Lists.newArrayList(sortedOrder);
Collections.shuffle(shuffled);
Set<DataSegment> theSet = Sets.newTreeSet(DataSegment.bucketMonthComparator());
theSet.addAll(shuffled);
int index = 0;
for (DataSegment dataSegment : theSet) {
Assert.assertEquals(sortedOrder[index], dataSegment);
++index;
}
}
private DataSegment makeDataSegment(String dataSource, String interval, String version)
{
return DataSegment.builder()
.dataSource(dataSource)
.interval(new Interval(interval))
.version(version)
.size(1)
.build();
}
}
| |
package com.mikelau.croperino;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import java.util.ArrayList;
class CropImageView extends ImageViewTouchBase {
ArrayList<HighlightView> mHighlightViews = new ArrayList<>();
HighlightView mMotionHighlightView = null;
float mLastX, mLastY;
int mMotionEdge;
private Context mContext;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (mBitmapDisplayed.getBitmap() != null) {
for (HighlightView hv : mHighlightViews) {
hv.mMatrix.set(getImageMatrix());
hv.invalidate();
if (hv.mIsFocused) {
centerBasedOnHighlightView(hv);
}
}
}
}
public CropImageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
}
@Override
protected void zoomTo(float scale, float centerX, float centerY) {
super.zoomTo(scale, centerX, centerY);
for (HighlightView hv : mHighlightViews) {
hv.mMatrix.set(getImageMatrix());
hv.invalidate();
}
}
@Override
protected void zoomIn() {
super.zoomIn();
for (HighlightView hv : mHighlightViews) {
hv.mMatrix.set(getImageMatrix());
hv.invalidate();
}
}
@Override
protected void zoomOut() {
super.zoomOut();
for (HighlightView hv : mHighlightViews) {
hv.mMatrix.set(getImageMatrix());
hv.invalidate();
}
}
@Override
protected void postTranslate(float deltaX, float deltaY) {
super.postTranslate(deltaX, deltaY);
for (int i = 0; i < mHighlightViews.size(); i++) {
HighlightView hv = mHighlightViews.get(i);
hv.mMatrix.postTranslate(deltaX, deltaY);
hv.invalidate();
}
}
// According to the event's position, change the focus to the first
// hitting cropping rectangle.
private void recomputeFocus(MotionEvent event) {
for (int i = 0; i < mHighlightViews.size(); i++) {
HighlightView hv = mHighlightViews.get(i);
hv.setFocus(false);
hv.invalidate();
}
for (int i = 0; i < mHighlightViews.size(); i++) {
HighlightView hv = mHighlightViews.get(i);
int edge = hv.getHit(event.getX(), event.getY());
if (edge != HighlightView.GROW_NONE) {
if (!hv.hasFocus()) {
hv.setFocus(true);
hv.invalidate();
}
break;
}
}
invalidate();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
CropImage croperino = (CropImage) mContext;
if (croperino.mSaving) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (croperino.mWaitingToPick) {
recomputeFocus(event);
} else {
for (int i = 0; i < mHighlightViews.size(); i++) {
HighlightView hv = mHighlightViews.get(i);
int edge = hv.getHit(event.getX(), event.getY());
if (edge != HighlightView.GROW_NONE) {
mMotionEdge = edge;
mMotionHighlightView = hv;
mLastX = event.getX();
mLastY = event.getY();
mMotionHighlightView.setMode((edge == HighlightView.MOVE) ? HighlightView.ModifyMode.Move : HighlightView.ModifyMode.Grow);
break;
}
}
}
break;
case MotionEvent.ACTION_UP:
if (croperino.mWaitingToPick) {
for (int i = 0; i < mHighlightViews.size(); i++) {
HighlightView hv = mHighlightViews.get(i);
if (hv.hasFocus()) {
croperino.mCrop = hv;
for (int j = 0; j < mHighlightViews.size(); j++) {
if (j == i) {
continue;
}
mHighlightViews.get(j).setHidden(true);
}
centerBasedOnHighlightView(hv);
((CropImage) mContext).mWaitingToPick = false;
return true;
}
}
} else if (mMotionHighlightView != null) {
centerBasedOnHighlightView(mMotionHighlightView);
mMotionHighlightView.setMode(HighlightView.ModifyMode.None);
}
mMotionHighlightView = null;
break;
case MotionEvent.ACTION_MOVE:
if (croperino.mWaitingToPick) {
recomputeFocus(event);
} else if (mMotionHighlightView != null) {
mMotionHighlightView.handleMotion(mMotionEdge, event.getX() - mLastX, event.getY() - mLastY);
mLastX = event.getX();
mLastY = event.getY();
if (true) {
// This section of code is optional. It has some user
// benefit in that moving the crop rectangle against
// the edge of the screen causes scrolling but it means
// that the crop rectangle is no longer fixed under
// the user's finger.
ensureVisible(mMotionHighlightView);
}
}
break;
}
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
center(true, true);
break;
case MotionEvent.ACTION_MOVE:
// if we're not zoomed then there's no point in even allowing
// the user to move the image around. This call to center puts
// it back to the normalized location (with false meaning don't
// animate).
if (getScale() == 1F) {
center(true, true);
}
break;
}
return true;
}
// Pan the displayed image to make sure the cropping rectangle is visible.
private void ensureVisible(HighlightView hv) {
Rect r = hv.mDrawRect;
int panDeltaX1 = Math.max(0, mLeft - r.left);
int panDeltaX2 = Math.min(0, mRight - r.right);
int panDeltaY1 = Math.max(0, mTop - r.top);
int panDeltaY2 = Math.min(0, mBottom - r.bottom);
int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2;
int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2;
if (panDeltaX != 0 || panDeltaY != 0) {
panBy(panDeltaX, panDeltaY);
}
}
// If the cropping rectangle's size changed significantly, change the
// view's center and scale according to the cropping rectangle.
private void centerBasedOnHighlightView(HighlightView hv) {
Rect drawRect = hv.mDrawRect;
float width = drawRect.width();
float height = drawRect.height();
float thisWidth = getWidth();
float thisHeight = getHeight();
float z1 = thisWidth / width * .6F;
float z2 = thisHeight / height * .6F;
float zoom = Math.min(z1, z2);
zoom = zoom * this.getScale();
zoom = Math.max(1F, zoom);
if ((Math.abs(zoom - getScale()) / zoom) > .1) {
float[] coordinates = new float[]{hv.mCropRect.centerX(),
hv.mCropRect.centerY()};
getImageMatrix().mapPoints(coordinates);
zoomTo(zoom, coordinates[0], coordinates[1], 300F);
}
ensureVisible(hv);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < mHighlightViews.size(); i++) {
mHighlightViews.get(i).draw(canvas);
}
}
public void add(HighlightView hv) {
mHighlightViews.add(hv);
invalidate();
}
}
| |
/*
* Copyright 2010 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.internal.graph;
import org.gradle.util.GUtil;
import java.util.*;
/**
* A graph walker which collects the values reachable from a given set of start nodes. Handles cycles in the graph. Can
* be reused to perform multiple searches, and reuses the results of previous searches.
*
* Uses a variation of Tarjan's algorithm: http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
*/
public class CachingDirectedGraphWalker<N, T> {
private final DirectedGraphWithEdgeValues<N, T> graph;
private List<N> startNodes = new LinkedList<N>();
private Set<NodeDetails<N, T>> strongComponents = new LinkedHashSet<NodeDetails<N, T>>();
private final Map<N, Set<T>> cachedNodeValues = new HashMap<N, Set<T>>();
public CachingDirectedGraphWalker(DirectedGraph<N, T> graph) {
this.graph = new GraphWithEmpyEdges<N, T>(graph);
}
public CachingDirectedGraphWalker(DirectedGraphWithEdgeValues<N, T> graph) {
this.graph = graph;
}
/**
* Adds some start nodes.
*/
public CachingDirectedGraphWalker<N, T> add(N... values) {
add(Arrays.asList(values));
return this;
}
/**
* Adds some start nodes.
*/
public CachingDirectedGraphWalker add(Iterable<? extends N> values) {
GUtil.addToCollection(startNodes, values);
return this;
}
/**
* Calculates the set of values of nodes reachable from the start nodes.
*/
public Set<T> findValues() {
try {
return doSearch();
} finally {
startNodes.clear();
}
}
/**
* Returns the set of cycles seen in the graph.
*/
public List<Set<N>> findCycles() {
findValues();
List<Set<N>> result = new ArrayList<Set<N>>();
for (NodeDetails<N, T> nodeDetails : strongComponents) {
Set<N> componentMembers = new LinkedHashSet<N>();
for (NodeDetails<N, T> componentMember : nodeDetails.componentMembers) {
componentMembers.add(componentMember.node);
}
result.add(componentMembers);
}
return result;
}
private Set<T> doSearch() {
int componentCount = 0;
Map<N, NodeDetails<N, T>> seenNodes = new HashMap<N, NodeDetails<N, T>>();
Map<Integer, NodeDetails<N, T>> components = new HashMap<Integer, NodeDetails<N, T>>();
LinkedList<N> queue = new LinkedList<N>(startNodes);
while (!queue.isEmpty()) {
N node = queue.getFirst();
NodeDetails<N, T> details = seenNodes.get(node);
if (details == null) {
// Have not visited this node yet. Push its successors onto the queue in front of this node and visit
// them
details = new NodeDetails<N, T>(node, componentCount++);
seenNodes.put(node, details);
components.put(details.component, details);
Set<T> cacheValues = cachedNodeValues.get(node);
if (cacheValues != null) {
// Already visited this node
details.values = cacheValues;
details.finished = true;
queue.removeFirst();
continue;
}
graph.getNodeValues(node, details.values, details.successors);
for (N connectedNode : details.successors) {
NodeDetails<N, T> connectedNodeDetails = seenNodes.get(connectedNode);
if (connectedNodeDetails == null) {
// Have not visited the successor node, so add to the queue for visiting
queue.add(0, connectedNode);
} else if (!connectedNodeDetails.finished) {
// Currently visiting the successor node - we're in a cycle
details.stronglyConnected = true;
}
// Else, already visited
}
} else {
// Have visited all of this node's successors
queue.removeFirst();
if (cachedNodeValues.containsKey(node)) {
continue;
}
for (N connectedNode : details.successors) {
NodeDetails<N, T> connectedNodeDetails = seenNodes.get(connectedNode);
if (!connectedNodeDetails.finished) {
// part of a cycle : use the 'minimum' component as the root of the cycle
int minSeen = Math.min(details.minSeen, connectedNodeDetails.minSeen);
details.minSeen = minSeen;
connectedNodeDetails.minSeen = minSeen;
details.stronglyConnected = true;
}
details.values.addAll(connectedNodeDetails.values);
graph.getEdgeValues(node, connectedNode, details.values);
}
if (details.minSeen != details.component) {
// Part of a strongly connected component (ie cycle) - move values to root of the component
// The root is the first node of the component we encountered
NodeDetails<N, T> rootDetails = components.get(details.minSeen);
rootDetails.values.addAll(details.values);
details.values.clear();
rootDetails.componentMembers.addAll(details.componentMembers);
} else {
// Not part of a strongly connected component or the root of a strongly connected component
for (NodeDetails<N, T> componentMember : details.componentMembers) {
cachedNodeValues.put(componentMember.node, details.values);
componentMember.finished = true;
components.remove(componentMember.component);
}
if (details.stronglyConnected) {
strongComponents.add(details);
}
}
}
}
Set<T> values = new LinkedHashSet<T>();
for (N startNode : startNodes) {
values.addAll(cachedNodeValues.get(startNode));
}
return values;
}
private static class NodeDetails<N, T> {
private final int component;
private final N node;
private Set<T> values = new LinkedHashSet<T>();
private List<N> successors = new ArrayList<N>();
private Set<NodeDetails<N, T>> componentMembers = new LinkedHashSet<NodeDetails<N, T>>();
private int minSeen;
private boolean stronglyConnected;
private boolean finished;
public NodeDetails(N node, int component) {
this.node = node;
this.component = component;
minSeen = component;
componentMembers.add(this);
}
}
private static class GraphWithEmpyEdges<N, T> implements DirectedGraphWithEdgeValues<N, T> {
private final DirectedGraph<N, T> graph;
public GraphWithEmpyEdges(DirectedGraph<N, T> graph) {
this.graph = graph;
}
public void getEdgeValues(N from, N to, Collection<T> values) {
}
public void getNodeValues(N node, Collection<? super T> values, Collection<? super N> connectedNodes) {
graph.getNodeValues(node, values, connectedNodes);
}
}
}
| |
/*
* Copyright 2000-2014 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.client.connectors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.CheckBox;
import com.vaadin.client.ServerConnector;
import com.vaadin.client.annotations.OnStateChange;
import com.vaadin.client.data.DataSource;
import com.vaadin.client.data.DataSource.RowHandle;
import com.vaadin.client.renderers.ComplexRenderer;
import com.vaadin.client.renderers.Renderer;
import com.vaadin.client.widget.grid.DataAvailableEvent;
import com.vaadin.client.widget.grid.DataAvailableHandler;
import com.vaadin.client.widget.grid.events.SelectAllEvent;
import com.vaadin.client.widget.grid.events.SelectAllHandler;
import com.vaadin.client.widget.grid.selection.MultiSelectionRenderer;
import com.vaadin.client.widget.grid.selection.SelectionModel;
import com.vaadin.client.widget.grid.selection.SelectionModel.Multi;
import com.vaadin.client.widget.grid.selection.SpaceSelectHandler;
import com.vaadin.client.widgets.Grid;
import com.vaadin.client.widgets.Grid.HeaderCell;
import com.vaadin.shared.ui.Connect;
import com.vaadin.shared.ui.grid.GridState;
import com.vaadin.shared.ui.grid.Range;
import com.vaadin.shared.ui.grid.selection.MultiSelectionModelServerRpc;
import com.vaadin.shared.ui.grid.selection.MultiSelectionModelState;
import com.vaadin.ui.Grid.MultiSelectionModel;
import elemental.json.JsonObject;
/**
* Connector for server-side {@link MultiSelectionModel}.
*
* @since 7.6
* @author Vaadin Ltd
*/
@Connect(MultiSelectionModel.class)
public class MultiSelectionModelConnector extends
AbstractSelectionModelConnector<SelectionModel.Multi<JsonObject>> {
private Multi<JsonObject> selectionModel = createSelectionModel();
private SpaceSelectHandler<JsonObject> spaceHandler;
@Override
protected void extend(ServerConnector target) {
getGrid().setSelectionModel(selectionModel);
spaceHandler = new SpaceSelectHandler<JsonObject>(getGrid());
}
@Override
public void onUnregister() {
spaceHandler.removeHandler();
}
@Override
protected Multi<JsonObject> createSelectionModel() {
return new MultiSelectionModel();
}
@Override
public MultiSelectionModelState getState() {
return (MultiSelectionModelState) super.getState();
}
@OnStateChange("allSelected")
void updateSelectAllCheckbox() {
if (selectionModel.getSelectionColumnRenderer() != null) {
HeaderCell cell = getGrid().getDefaultHeaderRow().getCell(
getGrid().getColumn(0));
CheckBox widget = (CheckBox) cell.getWidget();
widget.setValue(getState().allSelected, false);
}
}
protected class MultiSelectionModel extends AbstractSelectionModel
implements SelectionModel.Multi.Batched<JsonObject> {
private ComplexRenderer<Boolean> renderer = null;
private Set<RowHandle<JsonObject>> selected = new HashSet<RowHandle<JsonObject>>();
private Set<RowHandle<JsonObject>> deselected = new HashSet<RowHandle<JsonObject>>();
private HandlerRegistration selectAll;
private HandlerRegistration dataAvailable;
private Range availableRows;
private boolean batchSelect = false;
@Override
public void setGrid(Grid<JsonObject> grid) {
super.setGrid(grid);
if (grid != null) {
renderer = createSelectionColumnRenderer(grid);
selectAll = getGrid().addSelectAllHandler(
new SelectAllHandler<JsonObject>() {
@Override
public void onSelectAll(
SelectAllEvent<JsonObject> event) {
selectAll();
}
});
dataAvailable = getGrid().addDataAvailableHandler(
new DataAvailableHandler() {
@Override
public void onDataAvailable(DataAvailableEvent event) {
availableRows = event.getAvailableRows();
}
});
} else if (renderer != null) {
selectAll.removeHandler();
dataAvailable.removeHandler();
renderer = null;
}
}
/**
* Creates a selection column renderer. This method can be overridden to
* use a custom renderer or use {@code null} to disable the selection
* column.
*
* @param grid
* the grid for this selection model
* @return selection column renderer or {@code null} if not needed
*/
protected ComplexRenderer<Boolean> createSelectionColumnRenderer(
Grid<JsonObject> grid) {
return new MultiSelectionRenderer<JsonObject>(grid);
}
/**
* Selects all available rows, sends request to server to select
* everything.
*/
public void selectAll() {
assert !isBeingBatchSelected() : "Can't select all in middle of a batch selection.";
DataSource<JsonObject> dataSource = getGrid().getDataSource();
for (int i = availableRows.getStart(); i < availableRows.getEnd(); ++i) {
final JsonObject row = dataSource.getRow(i);
if (row != null) {
RowHandle<JsonObject> handle = dataSource.getHandle(row);
markAsSelected(handle, true);
}
}
getRpcProxy(MultiSelectionModelServerRpc.class).selectAll();
}
@Override
public Renderer<Boolean> getSelectionColumnRenderer() {
return renderer;
}
/**
* {@inheritDoc}
*
* @return {@code false} if rows is empty, else {@code true}
*/
@Override
public boolean select(JsonObject... rows) {
return select(Arrays.asList(rows));
}
/**
* {@inheritDoc}
*
* @return {@code false} if rows is empty, else {@code true}
*/
@Override
public boolean deselect(JsonObject... rows) {
return deselect(Arrays.asList(rows));
}
/**
* {@inheritDoc}
*
* @return always {@code true}
*/
@Override
public boolean deselectAll() {
assert !isBeingBatchSelected() : "Can't select all in middle of a batch selection.";
DataSource<JsonObject> dataSource = getGrid().getDataSource();
for (int i = availableRows.getStart(); i < availableRows.getEnd(); ++i) {
final JsonObject row = dataSource.getRow(i);
if (row != null) {
RowHandle<JsonObject> handle = dataSource.getHandle(row);
markAsSelected(handle, false);
}
}
getRpcProxy(MultiSelectionModelServerRpc.class).deselectAll();
return true;
}
/**
* {@inheritDoc}
*
* @return {@code false} if rows is empty, else {@code true}
*/
@Override
public boolean select(Collection<JsonObject> rows) {
if (rows.isEmpty()) {
return false;
}
for (JsonObject row : rows) {
RowHandle<JsonObject> rowHandle = getRowHandle(row);
if (markAsSelected(rowHandle, true)) {
selected.add(rowHandle);
}
}
if (!isBeingBatchSelected()) {
sendSelected();
}
return true;
}
/**
* Marks the given row to be selected or deselected. Returns true if the
* value actually changed.
* <p>
* Note: If selection model is in batch select state, the row will be
* pinned on select.
*
* @param row
* row handle
* @param selected
* {@code true} if row should be selected; {@code false} if
* not
* @return {@code true} if selected status changed; {@code false} if not
*/
protected boolean markAsSelected(RowHandle<JsonObject> row,
boolean selected) {
if (selected && !isSelected(row.getRow())) {
row.getRow().put(GridState.JSONKEY_SELECTED, true);
} else if (!selected && isSelected(row.getRow())) {
row.getRow().remove(GridState.JSONKEY_SELECTED);
} else {
return false;
}
row.updateRow();
if (isBeingBatchSelected()) {
row.pin();
}
return true;
}
/**
* {@inheritDoc}
*
* @return {@code false} if rows is empty, else {@code true}
*/
@Override
public boolean deselect(Collection<JsonObject> rows) {
if (rows.isEmpty()) {
return false;
}
for (JsonObject row : rows) {
RowHandle<JsonObject> rowHandle = getRowHandle(row);
if (markAsSelected(rowHandle, false)) {
deselected.add(rowHandle);
}
}
if (!isBeingBatchSelected()) {
sendDeselected();
}
return true;
}
/**
* Sends a deselect RPC call to server-side containing all deselected
* rows. Unpins any pinned rows.
*/
private void sendDeselected() {
getRpcProxy(MultiSelectionModelServerRpc.class).deselect(
getRowKeys(deselected));
if (isBeingBatchSelected()) {
for (RowHandle<JsonObject> row : deselected) {
row.unpin();
}
}
deselected.clear();
}
/**
* Sends a select RPC call to server-side containing all selected rows.
* Unpins any pinned rows.
*/
private void sendSelected() {
getRpcProxy(MultiSelectionModelServerRpc.class).select(
getRowKeys(selected));
if (isBeingBatchSelected()) {
for (RowHandle<JsonObject> row : selected) {
row.unpin();
}
}
selected.clear();
}
private List<String> getRowKeys(Set<RowHandle<JsonObject>> handles) {
List<String> keys = new ArrayList<String>();
for (RowHandle<JsonObject> handle : handles) {
keys.add(getRowKey(handle.getRow()));
}
return keys;
}
private Set<JsonObject> getRows(Set<RowHandle<JsonObject>> handles) {
Set<JsonObject> rows = new HashSet<JsonObject>();
for (RowHandle<JsonObject> handle : handles) {
rows.add(handle.getRow());
}
return rows;
}
@Override
public void startBatchSelect() {
assert selected.isEmpty() && deselected.isEmpty() : "Row caches were not clear.";
batchSelect = true;
}
@Override
public void commitBatchSelect() {
assert batchSelect : "Not batch selecting.";
if (!selected.isEmpty()) {
sendSelected();
}
if (!deselected.isEmpty()) {
sendDeselected();
}
batchSelect = false;
}
@Override
public boolean isBeingBatchSelected() {
return batchSelect;
}
@Override
public Collection<JsonObject> getSelectedRowsBatch() {
return Collections.unmodifiableSet(getRows(selected));
}
@Override
public Collection<JsonObject> getDeselectedRowsBatch() {
return Collections.unmodifiableSet(getRows(deselected));
}
}
}
| |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.dmn.engine.hitpolicy;
import static java.lang.Integer.MAX_VALUE;
import static java.lang.Integer.MIN_VALUE;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.camunda.bpm.dmn.engine.test.asserts.DmnEngineTestAssertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.camunda.bpm.dmn.engine.DmnDecisionRuleResult;
import org.camunda.bpm.dmn.engine.DmnDecisionTableResult;
import org.camunda.bpm.dmn.engine.impl.hitpolicy.DmnHitPolicyException;
import org.camunda.bpm.dmn.engine.impl.transform.DmnTransformException;
import org.camunda.bpm.dmn.engine.test.DecisionResource;
import org.camunda.bpm.dmn.engine.test.DmnEngineTest;
import org.camunda.bpm.dmn.engine.test.asserts.DmnDecisionTableResultAssert;
import org.junit.Test;
public class HitPolicyTest extends DmnEngineTest {
protected static final Double DOUBLE_MIN = -Double.MAX_VALUE;
public static final String DEFAULT_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.default.single.dmn";
public static final String DEFAULT_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.default.compound.dmn";
public static final String UNIQUE_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.unique.single.dmn";
public static final String UNIQUE_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.unique.compound.dmn";
public static final String ANY_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.any.single.dmn";
public static final String ANY_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.any.compound.dmn";
public static final String PRIORITY_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.priority.single.dmn";
public static final String FIRST_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.first.single.dmn";
public static final String FIRST_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.first.compound.dmn";
public static final String OUTPUT_ORDER_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.outputOrder.single.dmn";
public static final String RULE_ORDER_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.ruleOrder.single.dmn";
public static final String RULE_ORDER_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.ruleOrder.compound.dmn";
public static final String COLLECT_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.single.dmn";
public static final String COLLECT_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.compound.dmn";
public static final String COLLECT_SUM_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.sum.single.dmn";
public static final String COLLECT_SUM_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.sum.compound.dmn";
public static final String COLLECT_MIN_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.min.single.dmn";
public static final String COLLECT_MIN_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.min.compound.dmn";
public static final String COLLECT_MAX_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.max.single.dmn";
public static final String COLLECT_MAX_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.max.compound.dmn";
public static final String COLLECT_COUNT_SINGLE = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.count.single.dmn";
public static final String COLLECT_COUNT_COMPOUND = "org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.count.compound.dmn";
@Test
@DecisionResource(resource = DEFAULT_SINGLE)
public void testDefaultHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = DEFAULT_SINGLE)
public void testDefaultHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("b");
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("c");
}
@Test
@DecisionResource(resource = DEFAULT_SINGLE)
public void testDefaultHitPolicySingleOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(true, false, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(false, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(true, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
}
@Test
@DecisionResource(resource = DEFAULT_COMPOUND)
public void testDefaultHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = DEFAULT_COMPOUND)
public void testDefaultHitPolicyCompoundOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
}
@Test
@DecisionResource(resource = DEFAULT_COMPOUND)
public void testDefaultHitPolicyCompoundOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(true, false, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(false, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(true, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
}
@Test
@DecisionResource(resource = UNIQUE_SINGLE)
public void testUniqueHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = UNIQUE_SINGLE)
public void testUniqueHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("b");
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("c");
}
@Test
@DecisionResource(resource = UNIQUE_SINGLE)
public void testUniqueHitPolicySingleOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(true, false, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(false, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(true, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
}
@Test
@DecisionResource(resource = UNIQUE_COMPOUND)
public void testUniqueHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = UNIQUE_COMPOUND)
public void testUniqueHitPolicyCompoundOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
}
@Test
@DecisionResource(resource = UNIQUE_COMPOUND)
public void testUniqueHitPolicyCompoundOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(true, false, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(false, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
try {
evaluateDecisionTable(true, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03001");
}
}
@Test
@DecisionResource(resource = ANY_SINGLE)
public void testAnyHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = ANY_SINGLE)
public void testAnyHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("b");
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("c");
}
@Test
@DecisionResource(resource = ANY_SINGLE)
public void testAnyHitPolicySingleOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03002");
}
try {
evaluateDecisionTable(true, false, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03002");
}
try {
evaluateDecisionTable(false, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03002");
}
try {
evaluateDecisionTable(true, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03002");
}
assertThatDecisionTableResult(true, true, false, "a", "a", "a")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(true, false, true, "a", "a", "a")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(false, true, true, "a", "a", "a")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(true, true, true, "a", "a", "a")
.hasSingleResult()
.hasSingleEntry("a");
}
@Test
@DecisionResource(resource = ANY_COMPOUND)
public void testAnyHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = ANY_COMPOUND)
public void testAnyHitPolicyCompoundOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
}
@Test
@DecisionResource(resource = ANY_COMPOUND)
public void testAnyHitPolicyCompoundOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03002");
}
try {
evaluateDecisionTable(true, false, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03002");
}
try {
evaluateDecisionTable(false, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03002");
}
try {
evaluateDecisionTable(true, true, true, "a", "b", "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03002");
}
assertThatDecisionTableResult(true, true, false, "a", "a", "a")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(true, false, true, "a", "a", "a")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(false, true, true, "a", "a", "a")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(true, true, true, "a", "a", "a")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
}
@Test
public void testPriorityHitPolicySingleOutputNoMatchingRule() {
try {
parseDecisionsFromFile(PRIORITY_SINGLE);
failBecauseExceptionWasNotThrown(DmnTransformException.class);
}
catch (DmnTransformException e) {
assertThat(e).hasMessageStartingWith("DMN-02004");
}
}
@Test
@DecisionResource(resource = FIRST_SINGLE)
public void testFirstHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = FIRST_SINGLE)
public void testFirstHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("b");
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("c");
}
@Test
@DecisionResource(resource = FIRST_SINGLE)
public void testFirstHitPolicySingleOutputMultipleMatchingRules() {
assertThatDecisionTableResult(true, true, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(true, true, false, "c", "b", "a")
.hasSingleResult()
.hasSingleEntry("c");
assertThatDecisionTableResult(true, false, true, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(true, false, true, "c", "b", "a")
.hasSingleResult()
.hasSingleEntry("c");
assertThatDecisionTableResult(false, true, true, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("b");
assertThatDecisionTableResult(false, true, true, "c", "b", "a")
.hasSingleResult()
.hasSingleEntry("b");
assertThatDecisionTableResult(true, true, true, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(true, true, true, "c", "b", "a")
.hasSingleResult()
.hasSingleEntry("c");
}
@Test
@DecisionResource(resource = FIRST_COMPOUND)
public void testFirstHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = FIRST_COMPOUND)
public void testFirstHitPolicyCompoundOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
}
@Test
@DecisionResource(resource = FIRST_COMPOUND)
public void testFirstHitPolicyCompoundOutputMultipleMatchingRules() {
assertThatDecisionTableResult(true, true, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(true, true, false, "c", "b", "a")
.hasSingleResult()
.containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
assertThatDecisionTableResult(true, false, true, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(true, false, true, "c", "b", "a")
.hasSingleResult()
.containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
assertThatDecisionTableResult(false, true, true, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThatDecisionTableResult(false, true, true, "c", "b", "a")
.hasSingleResult()
.containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThatDecisionTableResult(true, true, true, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(true, true, true, "c", "b", "a")
.hasSingleResult()
.containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
}
@Test
public void testOutputOrderHitPolicyNotSupported() {
try {
parseDecisionsFromFile(OUTPUT_ORDER_SINGLE);
failBecauseExceptionWasNotThrown(DmnTransformException.class);
}
catch (DmnTransformException e) {
assertThat(e).hasMessageStartingWith("DMN-02004");
}
}
@Test
@DecisionResource(resource = RULE_ORDER_SINGLE)
public void testRuleOrderHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = RULE_ORDER_SINGLE)
public void testRuleOrderHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("b");
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("c");
}
@Test
@DecisionResource(resource = RULE_ORDER_SINGLE)
public void testRuleOrderHitPolicySingleOutputMultipleMatchingRules() {
DmnDecisionTableResult results = evaluateDecisionTable(true, true, false, "a", "b", "c");
assertThat(results).hasSize(2);
assertThat(collectSingleOutputEntries(results)).containsExactly("a", "b");
results = evaluateDecisionTable(true, true, false, "c", "b", "a");
assertThat(results).hasSize(2);
assertThat(collectSingleOutputEntries(results)).containsExactly("c", "b");
results = evaluateDecisionTable(true, false, true, "a", "b", "c");
assertThat(results).hasSize(2);
assertThat(collectSingleOutputEntries(results)).containsExactly("a", "c");
results = evaluateDecisionTable(true, false, true, "c", "b", "a");
assertThat(results).hasSize(2);
assertThat(collectSingleOutputEntries(results)).containsExactly("c", "a");
results = evaluateDecisionTable(false, true, true, "a", "b", "c");
assertThat(results).hasSize(2);
assertThat(collectSingleOutputEntries(results)).containsExactly("b", "c");
results = evaluateDecisionTable(false, true, true, "c", "b", "a");
assertThat(results).hasSize(2);
assertThat(collectSingleOutputEntries(results)).containsExactly("b", "a");
results = evaluateDecisionTable(true, true, true, "a", "b", "c");
assertThat(results).hasSize(3);
assertThat(collectSingleOutputEntries(results)).containsExactly("a", "b", "c");
results = evaluateDecisionTable(true, true, true, "c", "b", "a");
assertThat(results).hasSize(3);
assertThat(collectSingleOutputEntries(results)).containsExactly("c", "b", "a");
}
@Test
@DecisionResource(resource = RULE_ORDER_COMPOUND)
public void testRuleOrderHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = RULE_ORDER_COMPOUND)
public void testRuleOrderHitPolicyCompoundOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
}
@Test
@DecisionResource(resource = RULE_ORDER_COMPOUND)
public void testRuleOrderHitPolicyCompoundOutputMultipleMatchingRules() {
DmnDecisionTableResult results = evaluateDecisionTable(true, true, false, "a", "b", "c");
assertThat(results).hasSize(2);
assertThat(results.get(0)).containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThat(results.get(1)).containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
results = evaluateDecisionTable(true, true, false, "c", "b", "a");
assertThat(results).hasSize(2);
assertThat(results.get(0)).containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
assertThat(results.get(1)).containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
results = evaluateDecisionTable(true, false, true, "a", "b", "c");
assertThat(results).hasSize(2);
assertThat(results.get(0)).containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThat(results.get(1)).containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
results = evaluateDecisionTable(true, false, true, "c", "b", "a");
assertThat(results).hasSize(2);
assertThat(results.get(0)).containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
assertThat(results.get(1)).containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
results = evaluateDecisionTable(false, true, true, "a", "b", "c");
assertThat(results).hasSize(2);
assertThat(results.get(0)).containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThat(results.get(1)).containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
results = evaluateDecisionTable(false, true, true, "c", "b", "a");
assertThat(results).hasSize(2);
assertThat(results.get(0)).containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThat(results.get(1)).containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
results = evaluateDecisionTable(true, true, true, "a", "b", "c");
assertThat(results).hasSize(3);
assertThat(results.get(0)).containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
assertThat(results.get(1)).containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThat(results.get(2)).containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
results = evaluateDecisionTable(true, true, true, "c", "b", "a");
assertThat(results).hasSize(3);
assertThat(results.get(0)).containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
assertThat(results.get(1)).containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
assertThat(results.get(2)).containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
}
@Test
@DecisionResource(resource = COLLECT_SINGLE)
public void testCollectHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = COLLECT_SINGLE)
public void testCollectHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("a");
assertThatDecisionTableResult(false, true, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("b");
assertThatDecisionTableResult(false, false, true, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry("c");
}
@Test
@DecisionResource(resource = COLLECT_SINGLE)
public void testCollectHitPolicySingleOutputMultipleMatchingRules() {
DmnDecisionTableResult results = evaluateDecisionTable(true, true, false, "a", "b", "c");
assertThat(results).hasSize(2);
assertThat(collectSingleOutputEntries(results)).containsOnlyOnce("a", "b");
results = evaluateDecisionTable(true, false, true, "a", "b", "c");
assertThat(results).hasSize(2);
assertThat(collectSingleOutputEntries(results)).containsOnlyOnce("a", "c");
results = evaluateDecisionTable(false, true, true, "a", "b", "c");
assertThat(results).hasSize(2);
assertThat(collectSingleOutputEntries(results)).containsOnlyOnce("b", "c");
results = evaluateDecisionTable(true, true, true, "a", "b", "c");
assertThat(results).hasSize(3);
assertThat(collectSingleOutputEntries(results)).containsOnlyOnce("a", "b", "c");
}
@Test
@DecisionResource(resource = COLLECT_COMPOUND)
public void testCollectHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = COLLECT_COMPOUND)
public void testCollectHitPolicyCompoundOutputSingleMatchingRule() {
DmnDecisionTableResult results = evaluateDecisionTable(true, false, false, "a", "b", "c");
assertThat(results)
.hasSingleResult()
.containsOnly(entry("out1", "a"), entry("out2", "a"), entry("out3", "a"));
results = evaluateDecisionTable(false, true, false, "a", "b", "c");
assertThat(results)
.hasSingleResult()
.containsOnly(entry("out1", "b"), entry("out2", "b"), entry("out3", "b"));
results = evaluateDecisionTable(false, false, true, "a", "b", "c");
assertThat(results)
.hasSingleResult()
.containsOnly(entry("out1", "c"), entry("out2", "c"), entry("out3", "c"));
}
@Test
@DecisionResource(resource = COLLECT_SUM_SINGLE)
public void testCollectSumHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, 10, 20L, 30.034)
.isEmpty();
}
@Test
@DecisionResource(resource = COLLECT_SUM_SINGLE)
public void testCollectSumHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(10);
assertThatDecisionTableResult(false, true, false, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(20L);
assertThatDecisionTableResult(false, false, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(30.034);
assertThatDecisionTableResult(true, false, false, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(MAX_VALUE);
assertThatDecisionTableResult(true, false, false, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(MIN_VALUE);
assertThatDecisionTableResult(false, true, false, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Long.MAX_VALUE);
assertThatDecisionTableResult(false, true, false, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(Long.MIN_VALUE);
assertThatDecisionTableResult(false, false, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Double.MAX_VALUE);
assertThatDecisionTableResult(false, false, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(DOUBLE_MIN);
assertThatDecisionTableResult(true, false, false, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(1L);
assertThatDecisionTableResult(false, true, false, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(2L);
assertThatDecisionTableResult(false, false, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(3.0);
try {
evaluateDecisionTable(false, false, true, 10, 20L, "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03004");
}
}
@Test
@DecisionResource(resource = COLLECT_SUM_SINGLE)
public void testCollectSumHitPolicySingleOutputMultipleMatchingRules() {
assertThatDecisionTableResult(true, true, false, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(30L);
assertThatDecisionTableResult(true, false, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(40.034);
assertThatDecisionTableResult(false, true, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(50.034);
assertThatDecisionTableResult(true, true, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(60.034);
assertThatDecisionTableResult(true, true, false, MAX_VALUE, Long.MAX_VALUE - MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Long.MAX_VALUE);
assertThatDecisionTableResult(true, true, false, MIN_VALUE, Long.MIN_VALUE - MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(Long.MIN_VALUE);
assertThatDecisionTableResult(true, false, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE - MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Double.MAX_VALUE);
assertThatDecisionTableResult(true, false, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN - MIN_VALUE)
.hasSingleResult()
.hasSingleEntry(DOUBLE_MIN);
assertThatDecisionTableResult(false, true, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE - Long.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Double.MAX_VALUE);
assertThatDecisionTableResult(false, true, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN - Long.MIN_VALUE)
.hasSingleResult()
.hasSingleEntry(DOUBLE_MIN);
assertThatDecisionTableResult(true, true, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE - MAX_VALUE - Long.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Double.MAX_VALUE);
assertThatDecisionTableResult(true, true, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN - MIN_VALUE - Long.MIN_VALUE)
.hasSingleResult()
.hasSingleEntry(DOUBLE_MIN);
assertThatDecisionTableResult(true, true, false, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(3L);
assertThatDecisionTableResult(true, false, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(4.0);
assertThatDecisionTableResult(false, true, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(5.0);
assertThatDecisionTableResult(true, true, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(6.0);
try {
evaluateDecisionTable(true, true, true, 10, 20L, true);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03004");
}
}
@Test
@DecisionResource(resource = COLLECT_SUM_COMPOUND)
public void testCollectSumHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = COLLECT_SUM_COMPOUND)
public void testCollectSumHitPolicyCompoundOutputSingleMatchingRule() {
try {
evaluateDecisionTable(true, false, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, true, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, false, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
}
@Test
@DecisionResource(resource = COLLECT_SUM_COMPOUND)
public void testCollectSumHitPolicyCompoundOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(true, false, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, true, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(true, true, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
}
@Test
@DecisionResource(resource = COLLECT_MIN_SINGLE)
public void testCollectMinHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, 10, 20L, 30.034)
.isEmpty();
}
@Test
@DecisionResource(resource = COLLECT_MIN_SINGLE)
public void testCollectMinHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(10);
assertThatDecisionTableResult(false, true, false, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(20L);
assertThatDecisionTableResult(false, false, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(30.034);
assertThatDecisionTableResult(true, false, false, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(MAX_VALUE);
assertThatDecisionTableResult(true, false, false, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(MIN_VALUE);
assertThatDecisionTableResult(false, true, false, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Long.MAX_VALUE);
assertThatDecisionTableResult(false, true, false, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(Long.MIN_VALUE);
assertThatDecisionTableResult(false, false, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Double.MAX_VALUE);
assertThatDecisionTableResult(false, false, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(DOUBLE_MIN);
assertThatDecisionTableResult(true, false, false, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(1L);
assertThatDecisionTableResult(false, true, false, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(2L);
assertThatDecisionTableResult(false, false, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(3.0);
try {
evaluateDecisionTable(false, false, true, 10, 20L, "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03004");
}
}
@Test
@DecisionResource(resource = COLLECT_MIN_SINGLE)
public void testCollectMinHitPolicySingleOutputMultipleMatchingRules() {
assertThatDecisionTableResult(true, true, false, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(10L);
assertThatDecisionTableResult(true, false, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(10.0);
assertThatDecisionTableResult(false, true, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(20.0);
assertThatDecisionTableResult(true, true, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(10.0);
assertThatDecisionTableResult(true, true, false, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry((long) MAX_VALUE);
assertThatDecisionTableResult(true, true, false, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(Long.MIN_VALUE);
assertThatDecisionTableResult(true, false, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry((double) MAX_VALUE);
assertThatDecisionTableResult(true, false, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(DOUBLE_MIN);
assertThatDecisionTableResult(false, true, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry((double) Long.MAX_VALUE);
assertThatDecisionTableResult(false, true, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(DOUBLE_MIN);
assertThatDecisionTableResult(true, true, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry((double) MAX_VALUE);
assertThatDecisionTableResult(true, true, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(DOUBLE_MIN);
assertThatDecisionTableResult(true, true, false, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(1L);
assertThatDecisionTableResult(true, false, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(1.0);
assertThatDecisionTableResult(false, true, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(2.0);
assertThatDecisionTableResult(true, true, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(1.0);
try {
evaluateDecisionTable(true, true, true, 10, 20L, true);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03004");
}
}
@Test
@DecisionResource(resource = COLLECT_MIN_COMPOUND)
public void testCollectMinHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = COLLECT_MIN_COMPOUND)
public void testCollectMinHitPolicyCompoundOutputSingleMatchingRule() {
try {
evaluateDecisionTable(true, false, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, true, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, false, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
}
@Test
@DecisionResource(resource = COLLECT_MIN_COMPOUND)
public void testCollectMinHitPolicyCompoundOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(true, false, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, true, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(true, true, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
}
@Test
@DecisionResource(resource = COLLECT_MAX_SINGLE)
public void testCollectMaxHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, 10, 20L, 30.034)
.isEmpty();
}
@Test
@DecisionResource(resource = COLLECT_MAX_SINGLE)
public void testCollectMaxHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(10);
assertThatDecisionTableResult(false, true, false, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(20L);
assertThatDecisionTableResult(false, false, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(30.034);
assertThatDecisionTableResult(true, false, false, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(MAX_VALUE);
assertThatDecisionTableResult(true, false, false, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(MIN_VALUE);
assertThatDecisionTableResult(false, true, false, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Long.MAX_VALUE);
assertThatDecisionTableResult(false, true, false, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(Long.MIN_VALUE);
assertThatDecisionTableResult(false, false, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Double.MAX_VALUE);
assertThatDecisionTableResult(false, false, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry(DOUBLE_MIN);
assertThatDecisionTableResult(true, false, false, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(1L);
assertThatDecisionTableResult(false, true, false, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(2L);
assertThatDecisionTableResult(false, false, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(3.0);
try {
evaluateDecisionTable(false, false, true, 10, 20L, "c");
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03004");
}
}
@Test
@DecisionResource(resource = COLLECT_MAX_SINGLE)
public void testCollectMaxHitPolicySingleOutputMultipleMatchingRules() {
assertThatDecisionTableResult(true, true, false, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(20L);
assertThatDecisionTableResult(true, false, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(30.034);
assertThatDecisionTableResult(false, true, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(30.034);
assertThatDecisionTableResult(true, true, true, 10, 20L, 30.034)
.hasSingleResult()
.hasSingleEntry(30.034);
assertThatDecisionTableResult(true, true, false, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Long.MAX_VALUE);
assertThatDecisionTableResult(true, true, false, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry((long) MIN_VALUE);
assertThatDecisionTableResult(true, false, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Double.MAX_VALUE);
assertThatDecisionTableResult(true, false, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry((double) MIN_VALUE);
assertThatDecisionTableResult(false, true, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Double.MAX_VALUE);
assertThatDecisionTableResult(false, true, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry((double) Long.MIN_VALUE);
assertThatDecisionTableResult(true, true, true, MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE)
.hasSingleResult()
.hasSingleEntry(Double.MAX_VALUE);
assertThatDecisionTableResult(true, true, true, MIN_VALUE, Long.MIN_VALUE, DOUBLE_MIN)
.hasSingleResult()
.hasSingleEntry((double) MIN_VALUE);
assertThatDecisionTableResult(true, true, false, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(2L);
assertThatDecisionTableResult(true, false, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(3.0);
assertThatDecisionTableResult(false, true, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(3.0);
assertThatDecisionTableResult(true, true, true, (byte) 1, (short) 2, 3f)
.hasSingleResult()
.hasSingleEntry(3.0);
try {
evaluateDecisionTable(true, true, true, 10, 20L, true);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
} catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03004");
}
}
@Test
@DecisionResource(resource = COLLECT_MAX_COMPOUND)
public void testCollectMaxHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.isEmpty();
}
@Test
@DecisionResource(resource = COLLECT_MAX_COMPOUND)
public void testCollectMaxHitPolicyCompoundOutputSingleMatchingRule() {
try {
evaluateDecisionTable(true, false, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, true, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, false, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
}
@Test
@DecisionResource(resource = COLLECT_MAX_COMPOUND)
public void testCollectMaxHitPolicyCompoundOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(true, false, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, true, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(true, true, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
}
@Test
@DecisionResource(resource = COLLECT_COUNT_SINGLE)
public void testCollectCountHitPolicySingleOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, 10, "b", 30.034)
.hasSingleResult()
.hasSingleEntry(0);
}
@Test
@DecisionResource(resource = COLLECT_COUNT_SINGLE)
public void testCollectCountHitPolicySingleOutputSingleMatchingRule() {
assertThatDecisionTableResult(true, false, false, 10, "b", 30.034)
.hasSingleResult()
.hasSingleEntry(1);
assertThatDecisionTableResult(false, true, false, 10, "b", 30.034)
.hasSingleResult()
.hasSingleEntry(1);
assertThatDecisionTableResult(false, false, true, 10, "b", 30.034)
.hasSingleResult()
.hasSingleEntry(1);
}
@Test
@DecisionResource(resource = COLLECT_COUNT_SINGLE)
public void testCollectCountHitPolicySingleOutputMultipleMatchingRules() {
assertThatDecisionTableResult(true, true, false, 10, "b", 30.034)
.hasSingleResult()
.hasSingleEntry(2);
assertThatDecisionTableResult(true, false, true, 10, "b", 30.034)
.hasSingleResult()
.hasSingleEntry(2);
assertThatDecisionTableResult(false, true, true, 10, "b", 30.034)
.hasSingleResult()
.hasSingleEntry(2);
assertThatDecisionTableResult(true, true, true, 10, "b", 30.034)
.hasSingleResult()
.hasSingleEntry(3);
}
@Test
@DecisionResource(resource = COLLECT_COUNT_COMPOUND)
public void testCollectCountHitPolicyCompoundOutputNoMatchingRule() {
assertThatDecisionTableResult(false, false, false, "a", "b", "c")
.hasSingleResult()
.hasSingleEntry(0);
}
@Test
@DecisionResource(resource = COLLECT_COUNT_COMPOUND)
public void testCollectCountHitPolicyCompoundOutputSingleMatchingRule() {
try {
evaluateDecisionTable(true, false, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, true, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, false, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
}
@Test
@DecisionResource(resource = COLLECT_COUNT_COMPOUND)
public void testCollectCountHitPolicyCompoundOutputMultipleMatchingRules() {
try {
evaluateDecisionTable(true, true, false, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(true, false, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(false, true, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
try {
evaluateDecisionTable(true, true, true, 1, 2L, 3d);
failBecauseExceptionWasNotThrown(DmnHitPolicyException.class);
}
catch (DmnHitPolicyException e) {
assertThat(e).hasMessageStartingWith("DMN-03003");
}
}
// helper methods
public List<Object> collectSingleOutputEntries(DmnDecisionTableResult results) {
List<Object> values = new ArrayList<Object>();
for (DmnDecisionRuleResult result : results) {
values.add(result.getSingleEntry());
}
return values;
}
public DmnDecisionTableResult evaluateDecisionTable(Boolean input1, Boolean input2, Boolean input3, Object output1, Object output2, Object output3) {
variables.put("input1", input1);
variables.put("input2", input2);
variables.put("input3", input3);
variables.put("output1", output1);
variables.put("output2", output2);
variables.put("output3", output3);
return evaluateDecisionTable();
}
public DmnDecisionTableResultAssert assertThatDecisionTableResult(Boolean input1, Boolean input2, Boolean input3, Object output1, Object output2, Object output3) {
return assertThat(evaluateDecisionTable(input1, input2, input3, output1, output2, output3));
}
}
| |
/*
* Copyright (c) 2016, Salesforce.com, Inc.
* 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 Salesforce.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.salesforce.dva.argus.service;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.salesforce.dva.argus.entity.Metric;
/**
* The system service factory module. All services should be obtained from this class via injection.
*
* @author Tom Valine (tvaline@salesforce.com), Bhinav Sura (bhinav.sura@salesforce.com), Gaurav Kumar (gaurav.kumar@salesforce.com)
*/
public final class ServiceFactory {
//~ Instance fields ******************************************************************************************************************************
@Inject
Provider<TSDBService> _tsdbServiceProvider;
@Inject
Provider<AnnotationStorageService> _annotationStorageServiceProvider;
@Inject
Provider<CollectionService> _collectionServiceProvider;
@Inject
Provider<MQService> _mqServiceProvider;
@Inject
Provider<UserService> _userServiceProvider;
@Inject
Provider<DashboardService> _dashboardServiceProvider;
@Inject
Provider<OAuthAuthorizationCodeService> _oauthAuthorizationCodeServiceProvider;
@Inject
Provider<AlertService> _alertServiceProvider;
@Inject
Provider<MetricService> _metricServiceProvider;
@Inject
Provider<SchedulingService> _schedulingServiceProvider;
@Inject
Provider<GlobalInterlockService> _globalInterlockServiceProvider;
@Inject
Provider<MonitorService> _monitorServiceProvider;
@Inject
Provider<AnnotationService> _annotationServiceProvider;
@Inject
Provider<WardenService> _wardenServiceProvider;
@Inject
Provider<ManagementService> _managementServiceProvider;
@Inject
Provider<AuditService> _auditServiceProvider;
@Inject
Provider<MailService> _mailServiceProvider;
@Inject
Provider<AuthService> _authServiceProvider;
@Inject
Provider<HistoryService> _historyServiceProvider;
@Inject
Provider<SchemaService> _schemaServiceProvider;
@Inject
Provider<NamespaceService> _namespaceServiceProvider;
@Inject
Provider<CacheService> _cacheServiceProvider;
@Inject
Provider<DiscoveryService> _discoveryServiceProvider;
@Inject
Provider<BatchService> _batchServiceProvider;
@Inject
Provider<ChartService> _chartServiceProvider;
@Inject
Provider<ServiceManagementService> _serviceManagementServiceProvider;
@Inject
Provider<RefocusService> _refocusServiceProvider;
@Inject
Provider<QueryStoreService> _queryStoreServiceProvider;
@Inject
Provider<ImageService> _imageServiceProvider;
@Inject
Provider<MetricStorageService> _consumerOffsetMetricStorageService;
//~ Methods **************************************************************************************************************************************
/**
* Returns an instance of the TSDB service.
*
* @return An instance of the TSDB service.
*/
public synchronized TSDBService getTSDBService() {
return _tsdbServiceProvider.get();
}
/**
* Returns an instance of the annotation storage service.
*
* @return An instance of the annotation storage service.
*/
public synchronized AnnotationStorageService getAnnotationStorageService() {
return _annotationStorageServiceProvider.get();
}
/**
* Returns an instance of the Collection service.
*
* @return An instance of the Collection service.
*/
public synchronized CollectionService getCollectionService() {
return _collectionServiceProvider.get();
}
/**
* Returns an instance of the MQ service.
*
* @return An instance of the MQ service.
*/
public synchronized MQService getMQService() {
return _mqServiceProvider.get();
}
/**
* Returns an instance of the user service.
*
* @return An instance of the user service.
*/
public synchronized UserService getUserService() {
return _userServiceProvider.get();
}
/**
* Returns an instance of the dashboard service.
*
* @return An instance of the dashboard service.
*/
public synchronized DashboardService getDashboardService() {
return _dashboardServiceProvider.get();
}
/**
* Returns an instance of OAuth Authorization Code service.
*
* @return An instance of the OAuthAuthorizationCode service.
*/
public synchronized OAuthAuthorizationCodeService getOAuthAuthorizationCodeService() {
return _oauthAuthorizationCodeServiceProvider.get();
}
/**
* Returns an instance of the alert service.
*
* @return An instance of the alert service.
*/
public synchronized AlertService getAlertService() {
return _alertServiceProvider.get();
}
/**
* Returns an instance of the metric service.
*
* @return An instance of the metric service.
*/
public synchronized MetricService getMetricService() {
return _metricServiceProvider.get();
}
/**
* Returns an instance of the scheduling service.
*
* @return An instance of the scheduling service.
*/
public synchronized SchedulingService getSchedulingService() {
return _schedulingServiceProvider.get();
}
/**
* Returns an instance of the global interlock service.
*
* @return An instance of the global interlock service.
*/
public synchronized GlobalInterlockService getGlobalInterlockService() {
return _globalInterlockServiceProvider.get();
}
/**
* Returns an instance of the monitor service.
*
* @return An instance of the monitor service.
*/
public synchronized MonitorService getMonitorService() {
return _monitorServiceProvider.get();
}
/**
* Returns an instance of the mail service.
*
* @return An instance of the mail service.
*/
public synchronized MailService getMailService() {
return _mailServiceProvider.get();
}
/**
* Returns an instance of the annotation service.
*
* @return An instance of the annotation service.
*/
public synchronized AnnotationService getAnnotationService() {
return _annotationServiceProvider.get();
}
/**
* Returns an instance of the warden service.
*
* @return An instance of the warden service.
*/
public synchronized WardenService getWardenService() {
return _wardenServiceProvider.get();
}
/**
* Returns an instance of the management service.
*
* @return An instance of the management service.
*/
public synchronized ManagementService getManagementService() {
return _managementServiceProvider.get();
}
/**
* Returns an instance of the audit service.
*
* @return An instance of the audit service.
*/
public synchronized AuditService getAuditService() {
return _auditServiceProvider.get();
}
/**
* Returns an instance of the authentication service.
*
* @return An instance of the audit service.
*/
public synchronized AuthService getAuthService() {
return _authServiceProvider.get();
}
/**
* Returns an instance of the job history service.
*
* @return An instance of the job history service.
*/
public synchronized HistoryService getHistoryService() {
return _historyServiceProvider.get();
}
/**
* Returns an instance of the schema service.
*
* @return An instance of the schema service.
*/
public synchronized SchemaService getSchemaService() {
return _schemaServiceProvider.get();
}
/**
* Returns an instance of the namespace service.
*
* @return An instance of the namespace service.
*/
public synchronized NamespaceService getNamespaceService() {
return _namespaceServiceProvider.get();
}
/**
* Returns an instance of the cache service.
*
* @return An instance of the cache service.
*/
public synchronized CacheService getCacheService() {
return _cacheServiceProvider.get();
}
/**
* Returns an instance of the Discovery service.
*
* @return An instance of the Discovery service.
*/
public synchronized DiscoveryService getDiscoveryService() {
return _discoveryServiceProvider.get();
}
/**
* Returns an instance of the batch service.
*
* @return An instance of the batch service.
*/
public synchronized BatchService getBatchService() {
return _batchServiceProvider.get();
}
/**
* Returns an instance of the chart service.
*
* @return An instance of the chart service.
*/
public synchronized ChartService getChartService() {
return _chartServiceProvider.get();
}
/**
* Returns an instance of the service management service.
*
* @return An instance of the service management service.
*/
public synchronized ServiceManagementService getServiceManagementService() {
return _serviceManagementServiceProvider.get();
}
/**
* Returns an instance of the refocus service.
*
* @return An instance of the refocus service.
*/
public synchronized RefocusService getRefocusService() {
return _refocusServiceProvider.get();
}
/**
* Returns an instance of the Queries Store service.
*
* @return An instance of the Queries Store service.
*/
public synchronized QueryStoreService getQueryStoreService() {
return _queryStoreServiceProvider.get();
}
/**
* Returns an instance of the Image service.
*
* @return An instance of the Image service.
*/
public synchronized ImageService getImageService() {
return _imageServiceProvider.get();
}
/***
* Returns an instance of the Metric Storage service.
*
* @return An instance of the Metric Storage service.
*/
public synchronized MetricStorageService getConsumerOffsetMetricStorageService() { return _consumerOffsetMetricStorageService.get();}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
| |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.core.config.partitionedsearch;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
import org.optaplanner.core.config.heuristic.policy.HeuristicConfigPolicy;
import org.optaplanner.core.config.localsearch.LocalSearchPhaseConfig;
import org.optaplanner.core.config.phase.PhaseConfig;
import org.optaplanner.core.config.solver.EnvironmentMode;
import org.optaplanner.core.config.util.ConfigUtils;
import org.optaplanner.core.config.util.KeyAsElementMapConverter;
import org.optaplanner.core.impl.partitionedsearch.DefaultPartitionedSearchPhase;
import org.optaplanner.core.impl.partitionedsearch.PartitionedSearchPhase;
import org.optaplanner.core.impl.partitionedsearch.partitioner.SolutionPartitioner;
import org.optaplanner.core.impl.score.director.ScoreDirector;
import org.optaplanner.core.impl.solver.ChildThreadType;
import org.optaplanner.core.impl.solver.recaller.BestSolutionRecaller;
import org.optaplanner.core.impl.solver.termination.Termination;
import org.optaplanner.core.impl.solver.thread.DefaultSolverThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@XStreamAlias("partitionedSearch")
public class PartitionedSearchPhaseConfig extends PhaseConfig<PartitionedSearchPhaseConfig> {
public static final String ACTIVE_THREAD_COUNT_AUTO = "AUTO";
public static final String ACTIVE_THREAD_COUNT_UNLIMITED = "UNLIMITED";
private static final Logger logger = LoggerFactory.getLogger(PartitionedSearchPhaseConfig.class);
// Warning: all fields are null (and not defaulted) because they can be inherited
// and also because the input config file should match the output config file
protected Class<? extends SolutionPartitioner<?>> solutionPartitionerClass = null;
@XStreamConverter(KeyAsElementMapConverter.class)
protected Map<String, String> solutionPartitionerCustomProperties = null;
protected Class<? extends ThreadFactory> threadFactoryClass = null;
protected String runnablePartThreadLimit = null;
@XStreamImplicit()
protected List<PhaseConfig> phaseConfigList = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public Class<? extends SolutionPartitioner<?>> getSolutionPartitionerClass() {
return solutionPartitionerClass;
}
public void setSolutionPartitionerClass(Class<? extends SolutionPartitioner<?>> solutionPartitionerClass) {
this.solutionPartitionerClass = solutionPartitionerClass;
}
public Map<String, String> getSolutionPartitionerCustomProperties() {
return solutionPartitionerCustomProperties;
}
public void setSolutionPartitionerCustomProperties(Map<String, String> solutionPartitionerCustomProperties) {
this.solutionPartitionerCustomProperties = solutionPartitionerCustomProperties;
}
public Class<? extends ThreadFactory> getThreadFactoryClass() {
return threadFactoryClass;
}
public void setThreadFactoryClass(Class<? extends ThreadFactory> threadFactoryClass) {
this.threadFactoryClass = threadFactoryClass;
}
/**
* Similar to a thread pool size, but instead of limiting the number of {@link Thread}s,
* it limits the number of {@link java.lang.Thread.State#RUNNABLE runnable} {@link Thread}s to avoid consuming all
* CPU resources (which would starve UI, Servlets and REST threads).
* <p/>
* The number of {@link Thread}s is always equal to the number of partitions returned by
* {@link SolutionPartitioner#splitWorkingSolution(ScoreDirector, Integer)},
* because otherwise some partitions would never run (especially with {@link Solver#terminateEarly() asynchronous termination}).
* If this limit (or {@link Runtime#availableProcessors()}) is lower than the number of partitions,
* this results in a slower score calculation speed per partition {@link Solver}.
* <p/>
* Defaults to {@value #ACTIVE_THREAD_COUNT_AUTO} which consumes the majority
* but not all of the CPU cores on multi-core machines, preventing other processes (including your IDE or SSH connection)
* on the machine from hanging.
* <p/>
* Use {@value #ACTIVE_THREAD_COUNT_UNLIMITED} to give it all CPU cores.
* This is useful if you're handling the CPU consumption on an OS level.
* @return null, a number, {@value #ACTIVE_THREAD_COUNT_AUTO}, {@value #ACTIVE_THREAD_COUNT_UNLIMITED}
* or a JavaScript calculation using {@value org.optaplanner.core.config.util.ConfigUtils#AVAILABLE_PROCESSOR_COUNT}.
*/
public String getRunnablePartThreadLimit() {
return runnablePartThreadLimit;
}
public void setRunnablePartThreadLimit(String runnablePartThreadLimit) {
this.runnablePartThreadLimit = runnablePartThreadLimit;
}
public List<PhaseConfig> getPhaseConfigList() {
return phaseConfigList;
}
public void setPhaseConfigList(List<PhaseConfig> phaseConfigList) {
this.phaseConfigList = phaseConfigList;
}
// ************************************************************************
// Builder methods
// ************************************************************************
@Override
public PartitionedSearchPhase buildPhase(int phaseIndex, HeuristicConfigPolicy solverConfigPolicy,
BestSolutionRecaller bestSolutionRecaller, Termination solverTermination) {
HeuristicConfigPolicy phaseConfigPolicy = solverConfigPolicy.createPhaseConfigPolicy();
DefaultPartitionedSearchPhase phase = new DefaultPartitionedSearchPhase(
phaseIndex, solverConfigPolicy.getLogIndentation(), bestSolutionRecaller,
buildPhaseTermination(phaseConfigPolicy, solverTermination));
phase.setSolutionPartitioner(buildSolutionPartitioner());
phase.setThreadFactory(buildThreadFactory());
phase.setRunnablePartThreadLimit(resolvedActiveThreadCount());
List<PhaseConfig> phaseConfigList_ = phaseConfigList;
if (ConfigUtils.isEmptyCollection(phaseConfigList_)) {
phaseConfigList_ = Arrays.asList(
new ConstructionHeuristicPhaseConfig(),
new LocalSearchPhaseConfig());
}
phase.setPhaseConfigList(phaseConfigList_);
phase.setConfigPolicy(phaseConfigPolicy.createChildThreadConfigPolicy(ChildThreadType.PART_THREAD));
EnvironmentMode environmentMode = phaseConfigPolicy.getEnvironmentMode();
if (environmentMode.isNonIntrusiveFullAsserted()) {
phase.setAssertStepScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
phase.setAssertExpectedStepScore(true);
phase.setAssertShadowVariablesAreNotStaleAfterStep(true);
}
return phase;
}
private SolutionPartitioner buildSolutionPartitioner() {
if (solutionPartitionerClass != null) {
SolutionPartitioner<?> solutionPartitioner = ConfigUtils.newInstance(this,
"solutionPartitionerClass", solutionPartitionerClass);
ConfigUtils.applyCustomProperties(solutionPartitioner, "solutionPartitionerClass",
solutionPartitionerCustomProperties);
return solutionPartitioner;
} else {
if (solutionPartitionerCustomProperties != null) {
throw new IllegalStateException("If there is no solutionPartitionerClass (" + solutionPartitionerClass
+ "), then there can be no solutionPartitionerCustomProperties ("
+ solutionPartitionerCustomProperties + ") either.");
}
// TODO
throw new UnsupportedOperationException();
}
}
private ThreadFactory buildThreadFactory() {
if (threadFactoryClass != null) {
return ConfigUtils.newInstance(this, "threadFactoryClass", threadFactoryClass);
} else {
return new DefaultSolverThreadFactory("PartThread");
}
}
private Integer resolvedActiveThreadCount() {
int availableProcessorCount = Runtime.getRuntime().availableProcessors();
Integer resolvedActiveThreadCount;
if (runnablePartThreadLimit == null || runnablePartThreadLimit.equals(ACTIVE_THREAD_COUNT_AUTO)) {
// Leave one for the Operating System and 1 for the solver thread, take the rest
resolvedActiveThreadCount = Math.max(1, availableProcessorCount - 2);
} else if (runnablePartThreadLimit.equals(ACTIVE_THREAD_COUNT_UNLIMITED)) {
resolvedActiveThreadCount = null;
} else {
resolvedActiveThreadCount = ConfigUtils.resolveThreadPoolSizeScript(
"runnablePartThreadLimit", runnablePartThreadLimit, ACTIVE_THREAD_COUNT_AUTO, ACTIVE_THREAD_COUNT_UNLIMITED);
if (resolvedActiveThreadCount < 1) {
throw new IllegalArgumentException("The runnablePartThreadLimit (" + runnablePartThreadLimit
+ ") resulted in a resolvedActiveThreadCount (" + resolvedActiveThreadCount
+ ") that is lower than 1.");
}
if (resolvedActiveThreadCount > availableProcessorCount) {
logger.debug("The resolvedActiveThreadCount ({}) is higher than "
+ "the availableProcessorCount ({}), so the JVM will "
+ "round-robin the CPU instead.", resolvedActiveThreadCount, availableProcessorCount);
}
}
return resolvedActiveThreadCount;
}
@Override
public void inherit(PartitionedSearchPhaseConfig inheritedConfig) {
super.inherit(inheritedConfig);
solutionPartitionerClass = ConfigUtils.inheritOverwritableProperty(solutionPartitionerClass,
inheritedConfig.getSolutionPartitionerClass());
solutionPartitionerCustomProperties = ConfigUtils.inheritMergeableMapProperty(
solutionPartitionerCustomProperties, inheritedConfig.getSolutionPartitionerCustomProperties());
threadFactoryClass = ConfigUtils.inheritOverwritableProperty(threadFactoryClass,
inheritedConfig.getThreadFactoryClass());
runnablePartThreadLimit = ConfigUtils.inheritOverwritableProperty(runnablePartThreadLimit,
inheritedConfig.getRunnablePartThreadLimit());
phaseConfigList = ConfigUtils.inheritMergeableListConfig(
phaseConfigList, inheritedConfig.getPhaseConfigList());
}
}
| |
package org.targettest.org.apache.lucene.document;
/**
* 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.
*/
import org.targettest.org.apache.lucene.analysis.TokenStream;
import org.targettest.org.apache.lucene.index.IndexWriter;
import org.targettest.org.apache.lucene.util.StringHelper;
import java.io.Reader;
import java.io.Serializable;
/**
A field is a section of a Document. Each field has two parts, a name and a
value. Values may be free text, provided as a String or as a Reader, or they
may be atomic keywords, which are not further processed. Such keywords may
be used to represent dates, urls, etc. Fields are optionally stored in the
index, so that they may be returned with hits on the document.
*/
public final class Field extends AbstractField implements Fieldable, Serializable {
/** Specifies whether and how a field should be stored. */
public static enum Store {
/** Store the original field value in the index. This is useful for short texts
* like a document's title which should be displayed with the results. The
* value is stored in its original form, i.e. no analyzer is used before it is
* stored.
*/
YES {
@Override
public boolean isStored() { return true; }
},
/** Do not store the field value in the index. */
NO {
@Override
public boolean isStored() { return false; }
};
public abstract boolean isStored();
}
/** Specifies whether and how a field should be indexed. */
public static enum Index {
/** Do not index the field value. This field can thus not be searched,
* but one can still access its contents provided it is
* {@link Field.Store stored}. */
NO {
@Override
public boolean isIndexed() { return false; }
@Override
public boolean isAnalyzed() { return false; }
@Override
public boolean omitNorms() { return true; }
},
/** Index the tokens produced by running the field's
* value through an Analyzer. This is useful for
* common text. */
ANALYZED {
@Override
public boolean isIndexed() { return true; }
@Override
public boolean isAnalyzed() { return true; }
@Override
public boolean omitNorms() { return false; }
},
/** Index the field's value without using an Analyzer, so it can be searched.
* As no analyzer is used the value will be stored as a single term. This is
* useful for unique Ids like product numbers.
*/
NOT_ANALYZED {
@Override
public boolean isIndexed() { return true; }
@Override
public boolean isAnalyzed() { return false; }
@Override
public boolean omitNorms() { return false; }
},
/** Expert: Index the field's value without an Analyzer,
* and also disable the storing of norms. Note that you
* can also separately enable/disable norms by calling
* {@link Field#setOmitNorms}. No norms means that
* index-time field and document boosting and field
* length normalization are disabled. The benefit is
* less memory usage as norms take up one byte of RAM
* per indexed field for every document in the index,
* during searching. Note that once you index a given
* field <i>with</i> norms enabled, disabling norms will
* have no effect. In other words, for this to have the
* above described effect on a field, all instances of
* that field must be indexed with NOT_ANALYZED_NO_NORMS
* from the beginning. */
NOT_ANALYZED_NO_NORMS {
@Override
public boolean isIndexed() { return true; }
@Override
public boolean isAnalyzed() { return false; }
@Override
public boolean omitNorms() { return true; }
},
/** Expert: Index the tokens produced by running the
* field's value through an Analyzer, and also
* separately disable the storing of norms. See
* {@link #NOT_ANALYZED_NO_NORMS} for what norms are
* and why you may want to disable them. */
ANALYZED_NO_NORMS {
@Override
public boolean isIndexed() { return true; }
@Override
public boolean isAnalyzed() { return true; }
@Override
public boolean omitNorms() { return true; }
};
/** Get the best representation of the index given the flags. */
public static Index toIndex(boolean indexed, boolean analyzed) {
return toIndex(indexed, analyzed, false);
}
/** Expert: Get the best representation of the index given the flags. */
public static Index toIndex(boolean indexed, boolean analyzed, boolean omitNorms) {
// If it is not indexed nothing else matters
if (!indexed) {
return Index.NO;
}
// typical, non-expert
if (!omitNorms) {
if (analyzed) {
return Index.ANALYZED;
}
return Index.NOT_ANALYZED;
}
// Expert: Norms omitted
if (analyzed) {
return Index.ANALYZED_NO_NORMS;
}
return Index.NOT_ANALYZED_NO_NORMS;
}
public abstract boolean isIndexed();
public abstract boolean isAnalyzed();
public abstract boolean omitNorms();
}
/** Specifies whether and how a field should have term vectors. */
public static enum TermVector {
/** Do not store term vectors.
*/
NO {
@Override
public boolean isStored() { return false; }
@Override
public boolean withPositions() { return false; }
@Override
public boolean withOffsets() { return false; }
},
/** Store the term vectors of each document. A term vector is a list
* of the document's terms and their number of occurrences in that document. */
YES {
@Override
public boolean isStored() { return true; }
@Override
public boolean withPositions() { return false; }
@Override
public boolean withOffsets() { return false; }
},
/**
* Store the term vector + token position information
*
* @see #YES
*/
WITH_POSITIONS {
@Override
public boolean isStored() { return true; }
@Override
public boolean withPositions() { return true; }
@Override
public boolean withOffsets() { return false; }
},
/**
* Store the term vector + Token offset information
*
* @see #YES
*/
WITH_OFFSETS {
@Override
public boolean isStored() { return true; }
@Override
public boolean withPositions() { return false; }
@Override
public boolean withOffsets() { return true; }
},
/**
* Store the term vector + Token position and offset information
*
* @see #YES
* @see #WITH_POSITIONS
* @see #WITH_OFFSETS
*/
WITH_POSITIONS_OFFSETS {
@Override
public boolean isStored() { return true; }
@Override
public boolean withPositions() { return true; }
@Override
public boolean withOffsets() { return true; }
};
/** Get the best representation of a TermVector given the flags. */
public static TermVector toTermVector(boolean stored, boolean withOffsets, boolean withPositions) {
// If it is not stored, nothing else matters.
if (!stored) {
return TermVector.NO;
}
if (withOffsets) {
if (withPositions) {
return Field.TermVector.WITH_POSITIONS_OFFSETS;
}
return Field.TermVector.WITH_OFFSETS;
}
if (withPositions) {
return Field.TermVector.WITH_POSITIONS;
}
return Field.TermVector.YES;
}
public abstract boolean isStored();
public abstract boolean withPositions();
public abstract boolean withOffsets();
}
/** The value of the field as a String, or null. If null, the Reader value or
* binary value is used. Exactly one of stringValue(),
* readerValue(), and getBinaryValue() must be set. */
public String stringValue() { return fieldsData instanceof String ? (String)fieldsData : null; }
/** The value of the field as a Reader, or null. If null, the String value or
* binary value is used. Exactly one of stringValue(),
* readerValue(), and getBinaryValue() must be set. */
public Reader readerValue() { return fieldsData instanceof Reader ? (Reader)fieldsData : null; }
/** The TokesStream for this field to be used when indexing, or null. If null, the Reader value
* or String value is analyzed to produce the indexed tokens. */
public TokenStream tokenStreamValue() { return tokenStream; }
/** <p>Expert: change the value of this field. This can
* be used during indexing to re-use a single Field
* instance to improve indexing speed by avoiding GC cost
* of new'ing and reclaiming Field instances. Typically
* a single {@link Document} instance is re-used as
* well. This helps most on small documents.</p>
*
* <p>Each Field instance should only be used once
* within a single {@link Document} instance. See <a
* href="http://wiki.apache.org/lucene-java/ImproveIndexingSpeed">ImproveIndexingSpeed</a>
* for details.</p> */
public void setValue(String value) {
if (isBinary) {
throw new IllegalArgumentException("cannot set a String value on a binary field");
}
fieldsData = value;
}
/** Expert: change the value of this field. See <a href="#setValue(java.lang.String)">setValue(String)</a>. */
public void setValue(Reader value) {
if (isBinary) {
throw new IllegalArgumentException("cannot set a Reader value on a binary field");
}
if (isStored) {
throw new IllegalArgumentException("cannot set a Reader value on a stored field");
}
fieldsData = value;
}
/** Expert: change the value of this field. See <a href="#setValue(java.lang.String)">setValue(String)</a>. */
public void setValue(byte[] value) {
if (!isBinary) {
throw new IllegalArgumentException("cannot set a byte[] value on a non-binary field");
}
fieldsData = value;
binaryLength = value.length;
binaryOffset = 0;
}
/** Expert: change the value of this field. See <a href="#setValue(java.lang.String)">setValue(String)</a>. */
public void setValue(byte[] value, int offset, int length) {
if (!isBinary) {
throw new IllegalArgumentException("cannot set a byte[] value on a non-binary field");
}
fieldsData = value;
binaryLength = length;
binaryOffset = offset;
}
/** Expert: sets the token stream to be used for indexing and causes isIndexed() and isTokenized() to return true.
* May be combined with stored values from stringValue() or getBinaryValue() */
public void setTokenStream(TokenStream tokenStream) {
this.isIndexed = true;
this.isTokenized = true;
this.tokenStream = tokenStream;
}
/**
* Create a field by specifying its name, value and how it will
* be saved in the index. Term vectors will not be stored in the index.
*
* @param name The name of the field
* @param value The string to process
* @param store Whether <code>value</code> should be stored in the index
* @param index Whether the field should be indexed, and if so, if it should
* be tokenized before indexing
* @throws NullPointerException if name or value is <code>null</code>
* @throws IllegalArgumentException if the field is neither stored nor indexed
*/
public Field(String name, String value, Store store, Index index) {
this(name, value, store, index, TermVector.NO);
}
/**
* Create a field by specifying its name, value and how it will
* be saved in the index.
*
* @param name The name of the field
* @param value The string to process
* @param store Whether <code>value</code> should be stored in the index
* @param index Whether the field should be indexed, and if so, if it should
* be tokenized before indexing
* @param termVector Whether term vector should be stored
* @throws NullPointerException if name or value is <code>null</code>
* @throws IllegalArgumentException in any of the following situations:
* <ul>
* <li>the field is neither stored nor indexed</li>
* <li>the field is not indexed but termVector is <code>TermVector.YES</code></li>
* </ul>
*/
public Field(String name, String value, Store store, Index index, TermVector termVector) {
this(name, true, value, store, index, termVector);
}
/**
* Create a field by specifying its name, value and how it will
* be saved in the index.
*
* @param name The name of the field
* @param internName Whether to .intern() name or not
* @param value The string to process
* @param store Whether <code>value</code> should be stored in the index
* @param index Whether the field should be indexed, and if so, if it should
* be tokenized before indexing
* @param termVector Whether term vector should be stored
* @throws NullPointerException if name or value is <code>null</code>
* @throws IllegalArgumentException in any of the following situations:
* <ul>
* <li>the field is neither stored nor indexed</li>
* <li>the field is not indexed but termVector is <code>TermVector.YES</code></li>
* </ul>
*/
public Field(String name, boolean internName, String value, Store store, Index index, TermVector termVector) {
if (name == null)
throw new NullPointerException("name cannot be null");
if (value == null)
throw new NullPointerException("value cannot be null");
if (name.length() == 0 && value.length() == 0)
throw new IllegalArgumentException("name and value cannot both be empty");
if (index == Index.NO && store == Store.NO)
throw new IllegalArgumentException("it doesn't make sense to have a field that "
+ "is neither indexed nor stored");
if (index == Index.NO && termVector != TermVector.NO)
throw new IllegalArgumentException("cannot store term vector information "
+ "for a field that is not indexed");
if (internName) // field names are optionally interned
name = StringHelper.intern(name);
this.name = name;
this.fieldsData = value;
this.isStored = store.isStored();
this.isIndexed = index.isIndexed();
this.isTokenized = index.isAnalyzed();
this.omitNorms = index.omitNorms();
if (index == Index.NO) {
this.omitTermFreqAndPositions = false;
}
this.isBinary = false;
setStoreTermVector(termVector);
}
/**
* Create a tokenized and indexed field that is not stored. Term vectors will
* not be stored. The Reader is read only when the Document is added to the index,
* i.e. you may not close the Reader until {@link IndexWriter#addDocument(Document)}
* has been called.
*
* @param name The name of the field
* @param reader The reader with the content
* @throws NullPointerException if name or reader is <code>null</code>
*/
public Field(String name, Reader reader) {
this(name, reader, TermVector.NO);
}
/**
* Create a tokenized and indexed field that is not stored, optionally with
* storing term vectors. The Reader is read only when the Document is added to the index,
* i.e. you may not close the Reader until {@link IndexWriter#addDocument(Document)}
* has been called.
*
* @param name The name of the field
* @param reader The reader with the content
* @param termVector Whether term vector should be stored
* @throws NullPointerException if name or reader is <code>null</code>
*/
public Field(String name, Reader reader, TermVector termVector) {
if (name == null)
throw new NullPointerException("name cannot be null");
if (reader == null)
throw new NullPointerException("reader cannot be null");
this.name = StringHelper.intern(name); // field names are interned
this.fieldsData = reader;
this.isStored = false;
this.isIndexed = true;
this.isTokenized = true;
this.isBinary = false;
setStoreTermVector(termVector);
}
/**
* Create a tokenized and indexed field that is not stored. Term vectors will
* not be stored. This is useful for pre-analyzed fields.
* The TokenStream is read only when the Document is added to the index,
* i.e. you may not close the TokenStream until {@link IndexWriter#addDocument(Document)}
* has been called.
*
* @param name The name of the field
* @param tokenStream The TokenStream with the content
* @throws NullPointerException if name or tokenStream is <code>null</code>
*/
public Field(String name, TokenStream tokenStream) {
this(name, tokenStream, TermVector.NO);
}
/**
* Create a tokenized and indexed field that is not stored, optionally with
* storing term vectors. This is useful for pre-analyzed fields.
* The TokenStream is read only when the Document is added to the index,
* i.e. you may not close the TokenStream until {@link IndexWriter#addDocument(Document)}
* has been called.
*
* @param name The name of the field
* @param tokenStream The TokenStream with the content
* @param termVector Whether term vector should be stored
* @throws NullPointerException if name or tokenStream is <code>null</code>
*/
public Field(String name, TokenStream tokenStream, TermVector termVector) {
if (name == null)
throw new NullPointerException("name cannot be null");
if (tokenStream == null)
throw new NullPointerException("tokenStream cannot be null");
this.name = StringHelper.intern(name); // field names are interned
this.fieldsData = null;
this.tokenStream = tokenStream;
this.isStored = false;
this.isIndexed = true;
this.isTokenized = true;
this.isBinary = false;
setStoreTermVector(termVector);
}
/**
* Create a stored field with binary value. Optionally the value may be compressed.
*
* @param name The name of the field
* @param value The binary value
* @param store How <code>value</code> should be stored (compressed or not)
* @throws IllegalArgumentException if store is <code>Store.NO</code>
*/
public Field(String name, byte[] value, Store store) {
this(name, value, 0, value.length, store);
}
/**
* Create a stored field with binary value. Optionally the value may be compressed.
*
* @param name The name of the field
* @param value The binary value
* @param offset Starting offset in value where this Field's bytes are
* @param length Number of bytes to use for this Field, starting at offset
* @param store How <code>value</code> should be stored (compressed or not)
* @throws IllegalArgumentException if store is <code>Store.NO</code>
*/
public Field(String name, byte[] value, int offset, int length, Store store) {
if (name == null)
throw new IllegalArgumentException("name cannot be null");
if (value == null)
throw new IllegalArgumentException("value cannot be null");
this.name = StringHelper.intern(name); // field names are interned
fieldsData = value;
if (store == Store.NO)
throw new IllegalArgumentException("binary values can't be unstored");
isStored = store.isStored();
isIndexed = false;
isTokenized = false;
omitTermFreqAndPositions = false;
omitNorms = true;
isBinary = true;
binaryLength = length;
binaryOffset = offset;
setStoreTermVector(TermVector.NO);
}
}
| |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.service.contactsource;
import java.util.*;
import net.java.sip.communicator.service.protocol.*;
import org.jitsi.utils.*;
/**
* The <tt>ContactDetail</tt> is a detail of a <tt>SourceContact</tt>
* corresponding to a specific address (phone number, email, identifier, etc.),
* which defines the different possible types of communication and the preferred
* <tt>ProtocolProviderService</tt>s to go through.
*
* <p>
* Example: A <tt>ContactDetail</tt> could define two types of communication,
* by declaring two supported operation sets
* <tt>OperationSetBasicInstantMessaging</tt> to indicate the support of instant
* messages and <tt>OperationSetBasicTelephony</tt> to indicate the support of
* telephony. It may then specify a certain <tt>ProtocolProviderService</tt> to
* go through only for instant messages. This would mean that for sending an
* instant message to this <tt>ContactDetail</tt> one should obtain an instance
* of the <tt>OperationSetBasicInstantMessaging</tt> from the specific
* <tt>ProtocolProviderService</tt> and send a message through it. However when
* no provider is specified for telephony operations, then one should try to
* obtain all currently available telephony providers and let the user make
* their choice.
*
* @author Yana Stamcheva
* @author Lyubomir Marinov
*/
public class ContactDetail
{
/**
* Defines all possible categories for a <tt>ContactDetail</tt>.
*/
public enum Category
{
/**
* The standard/well-known category of a <tt>ContactDetail</tt>
* representing personal details, like name, last name, nickname.
*/
Personal("Personal"),
/**
* The standard/well-known category of a <tt>ContactDetail</tt>
* representing personal details, like web address.
*/
Web("Web"),
/**
* The standard/well-known category of a <tt>ContactDetail</tt>
* representing organization details, like organization name and job
* title.
*/
Organization("Organization"),
/**
* The standard/well-known category of a <tt>ContactDetail</tt>
* representing an e-mail address.
*/
Email("Email"),
/**
* The standard/well-known category of a <tt>ContactDetail</tt>
* representing a contact address for instant messaging.
*/
InstantMessaging("InstantMessaging"),
/**
* The standard/well-known category of a <tt>ContactDetail</tt>
* representing a phone number.
*/
Phone("Phone"),
/**
* The standard/well-known category of a <tt>ContactDetail</tt>
* representing a postal address.
*/
Address("Address");
/**
* Current enum value.
*/
private final String value;
/**
* Creates enum whith the specified value.
*
* @param value the value to set.
*/
Category(String value)
{
this.value = value;
}
/**
* Gets the value.
*
* @return the value
*/
public String value()
{
return value;
}
/**
* Creates enum from its value.
*
* @param value the enum's value.
* @return created enum.
*/
public static Category fromString(String value)
{
if (value != null)
{
for (Category category : Category.values())
{
if (value.equalsIgnoreCase(category.value()))
{
return category;
}
}
return null;
}
return null;
}
}
/**
* Defines all possible sub-categories for a <tt>ContactDetail</tt>.
*/
public enum SubCategory
{
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a name. It could be an organization name or a personal
* name.
*/
Name("Name"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a last name.
*/
LastName("LastName"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a nickname.
*/
Nickname("Nickname"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a postal code.
*/
HomePage("HomePage"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing an address of a contact at their home.
*/
Home("Home"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a mobile contact address (e.g. a cell phone number).
*/
Mobile("Mobile"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing an address of a contact at their work.
*/
Work("Work"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a fax number.
*/
Fax("Fax"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a different number.
*/
Other("Other"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing an IM network (like for example jabber).
*/
AIM("AIM"),
ICQ("ICQ"),
Jabber("XMPP"),
Skype("Skype"),
Yahoo("Yahoo"),
GoogleTalk("GoogleTalk"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a country name.
*/
Country("Country"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a state name.
*/
State("State"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a city name.
*/
City("City"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a street address.
*/
Street("Street"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a postal code.
*/
PostalCode("PostalCode"),
/**
* The standard/well-known label of a <tt>ContactDetail</tt>
* representing a job title.
*/
JobTitle("JobTitle");
/**
* Current enum value.
*/
private final String value;
/**
* Creates enum whith the specified value.
*
* @param value the value to set.
*/
SubCategory(String value)
{
this.value = value;
}
/**
* Gets the value.
*
* @return the value
*/
public String value()
{
return value;
}
/**
* Creates enum from its value.
*
* @param value the enum's value.
* @return created enum.
*/
public static SubCategory fromString(String value)
{
if (value != null)
{
for (SubCategory subCategory : SubCategory.values())
{
if (value.equalsIgnoreCase(subCategory.value()))
{
return subCategory;
}
}
return null;
}
return null;
}
}
/**
* The category of this <tt>ContactQuery</tt>.
*/
private final Category category;
/**
* The address of this contact detail. This should be the address through
* which the contact could be reached by one of the supported
* <tt>OperationSet</tt>s (e.g. by IM, call).
*/
protected String contactDetailValue;
/**
* The display name of this detail.
*/
private String detailDisplayName;
/**
* The set of labels of this <tt>ContactDetail</tt>. The labels may be
* arbitrary and may include any of the standard/well-known labels defined
* by the <tt>LABEL_XXX</tt> constants of the <tt>ContactDetail</tt> class.
*/
private final Collection<SubCategory> subCategories
= new LinkedList<SubCategory>();
/**
* A mapping of <tt>OperationSet</tt> classes and preferred protocol
* providers for them.
*/
private Map<Class<? extends OperationSet>, ProtocolProviderService>
preferredProviders;
/**
* A mapping of <tt>OperationSet</tt> classes and preferred protocol name
* for them.
*/
private Map<Class<? extends OperationSet>, String> preferredProtocols;
/**
* A list of all supported <tt>OperationSet</tt> classes.
*/
private List<Class<? extends OperationSet>> supportedOpSets = null;
/**
* Creates a <tt>ContactDetail</tt> by specifying the contact address,
* corresponding to this detail.
* @param contactDetailValue the contact detail value corresponding to this
* detail
*/
public ContactDetail(String contactDetailValue)
{
this(contactDetailValue, null, null, null);
}
/**
* Creates a <tt>ContactDetail</tt> by specifying the contact address,
* corresponding to this detail.
* @param contactDetailValue the contact detail value corresponding to this
* detail
* @param detailDisplayName the display name of this detail
*/
public ContactDetail(String contactDetailValue, String detailDisplayName)
{
this(contactDetailValue, detailDisplayName, null, null);
}
/**
* Initializes a new <tt>ContactDetail</tt> instance which is to represent a
* specific contact address and which is to be optionally labeled with a
* specific set of labels.
*
* @param contactDetailValue the contact detail value to be represented by
* the new <tt>ContactDetail</tt> instance
* @param category
*/
public ContactDetail( String contactDetailValue,
Category category)
{
this(contactDetailValue, null, category, null);
}
/**
* Initializes a new <tt>ContactDetail</tt> instance which is to represent a
* specific contact address and which is to be optionally labeled with a
* specific set of labels.
*
* @param contactDetailValue the contact detail value to be represented by
* the new <tt>ContactDetail</tt> instance
* @param detailDisplayName the display name of this detail
* @param category
*/
public ContactDetail( String contactDetailValue,
String detailDisplayName,
Category category)
{
this(contactDetailValue, detailDisplayName, category, null);
}
/**
* Initializes a new <tt>ContactDetail</tt> instance which is to represent a
* specific contact address and which is to be optionally labeled with a
* specific set of labels.
*
* @param contactDetailValue the contact detail value to be represented by
* the new <tt>ContactDetail</tt> instance
* @param category
* @param subCategories the set of sub categories with which the new
* <tt>ContactDetail</tt> instance is to be labeled.
*/
public ContactDetail( String contactDetailValue,
Category category,
SubCategory[] subCategories)
{
this(contactDetailValue, null, category, subCategories);
}
/**
* Initializes a new <tt>ContactDetail</tt> instance which is to represent a
* specific contact address and which is to be optionally labeled with a
* specific set of labels.
*
* @param contactDetailValue the contact detail value to be represented by
* the new <tt>ContactDetail</tt> instance
* @param detailDisplayName the display name of this detail
* @param category
* @param subCategories the set of sub categories with which the new
* <tt>ContactDetail</tt> instance is to be labeled.
*/
public ContactDetail( String contactDetailValue,
String detailDisplayName,
Category category,
SubCategory[] subCategories)
{
// the value of the detail
this.contactDetailValue = contactDetailValue;
if (!StringUtils.isNullOrEmpty(detailDisplayName))
{
this.detailDisplayName = detailDisplayName;
}
else if (category == Category.Phone)
{
this.detailDisplayName =
ContactSourceActivator.getPhoneNumberI18nService()
.formatForDisplay(contactDetailValue);
}
else
{
this.detailDisplayName = contactDetailValue;
}
// category & labels
this.category = category;
if (subCategories != null)
{
for (SubCategory subCategory : subCategories)
{
if ((subCategory != null)
&& !this.subCategories.contains(subCategory))
{
this.subCategories.add(subCategory);
}
}
}
}
/**
* Sets a mapping of preferred <tt>ProtocolProviderServices</tt> for
* a specific <tt>OperationSet</tt>.
* @param preferredProviders a mapping of preferred
* <tt>ProtocolProviderService</tt>s for specific <tt>OperationSet</tt>
* classes
*/
public void setPreferredProviders(
Map<Class<? extends OperationSet>, ProtocolProviderService>
preferredProviders)
{
this.preferredProviders = preferredProviders;
}
/**
* Sets a mapping of a preferred <tt>preferredProtocol</tt> for a specific
* <tt>OperationSet</tt>. The preferred protocols are meant to be set by
* contact source implementations that don't have a specific protocol
* providers to suggest, but are able to propose just the name of the
* protocol to be used for a specific operation. If both - preferred
* provider and preferred protocol are set, then the preferred protocol
* provider should be prioritized.
*
* @param preferredProtocols a mapping of preferred
* <tt>ProtocolProviderService</tt>s for specific <tt>OperationSet</tt>
* classes
*/
public void setPreferredProtocols(
Map<Class<? extends OperationSet>, String> preferredProtocols)
{
this.preferredProtocols = preferredProtocols;
// protocol added so an opset is supported, add it if missing
for(Class<? extends OperationSet> opsetClass
: preferredProtocols.keySet())
{
if(supportedOpSets == null || !supportedOpSets.contains(opsetClass))
addSupportedOpSet(opsetClass);
}
}
/**
* Creates a <tt>ContactDetail</tt> by specifying the corresponding contact
* address and a list of all <tt>supportedOpSets</tt>, indicating what are
* the supporting actions with this contact detail (e.g. sending a message,
* making a call, etc.)
* @param supportedOpSets a list of all <tt>supportedOpSets</tt>, indicating
* what are the supporting actions with this contact detail (e.g. sending a
* message, making a call, etc.)
*/
public void setSupportedOpSets(
List<Class<? extends OperationSet>> supportedOpSets)
{
this.supportedOpSets = supportedOpSets;
}
/**
* Adds a supported OpSet to the list of supported OpSets.
* @param supportedOpSet the OpSet to support.
*/
public void addSupportedOpSet(Class<? extends OperationSet> supportedOpSet)
{
if (this.supportedOpSets == null)
{
this.supportedOpSets
= new ArrayList<Class<? extends OperationSet>>(2);
}
this.supportedOpSets.add(supportedOpSet);
}
/**
* Gets the category, if any, of this <tt>ContactQuery</tt>.
*
* @return the category of this <tt>ContactQuery</tt> if it has any;
* otherwise, <tt>null</tt>
*/
public Category getCategory()
{
return category;
}
/**
* Returns the contact address corresponding to this detail.
*
* @return the contact address corresponding to this detail
*/
public String getDetail()
{
return contactDetailValue;
}
/**
* Returns the display name of this detail. By default returns the detail
* value.
*
* @return the display name of this detail
*/
public String getDisplayName()
{
return detailDisplayName;
}
/**
* Returns the preferred <tt>ProtocolProviderService</tt> when using the
* given <tt>opSetClass</tt>.
*
* @param opSetClass the <tt>OperationSet</tt> class corresponding to a
* certain action (e.g. sending an instant message, making a call, etc.).
* @return the preferred <tt>ProtocolProviderService</tt> corresponding to
* the given <tt>opSetClass</tt>
*/
public ProtocolProviderService getPreferredProtocolProvider(
Class<? extends OperationSet> opSetClass)
{
if (preferredProviders != null && preferredProviders.size() > 0)
return preferredProviders.get(opSetClass);
return null;
}
/**
* Returns the name of the preferred protocol for the operation given by
* the <tt>opSetClass</tt>. The preferred protocols are meant to be set by
* contact source implementations that don't have a specific protocol
* providers to suggest, but are able to propose just the name of the
* protocol to be used for a specific operation. If both - preferred
* provider and preferred protocol are set, then the preferred protocol
* provider should be prioritized.
*
* @param opSetClass the <tt>OperationSet</tt> class corresponding to a
* certain action (e.g. sending an instant message, making a call, etc.).
* @return the name of the preferred protocol for the operation given by
* the <tt>opSetClass</tt>
*/
public String getPreferredProtocol(Class<? extends OperationSet> opSetClass)
{
if (preferredProtocols != null && preferredProtocols.size() > 0)
return preferredProtocols.get(opSetClass);
return null;
}
/**
* Returns a list of all supported <tt>OperationSet</tt> classes, which
* would indicate what are the supported actions by this contact
* (e.g. write a message, make a call, etc.)
*
* @return a list of all supported <tt>OperationSet</tt> classes
*/
public List<Class<? extends OperationSet>> getSupportedOperationSets()
{
return supportedOpSets;
}
/**
* Determines whether the set of labels of this <tt>ContactDetail</tt>
* contains a specific label. The labels may be arbitrary and may include
* any of the standard/well-known labels defined by the <tt>LABEL_XXX</tt>
* constants of the <tt>ContactDetail</tt> class.
*
* @param subCategory the subCategory to be determined whether
* it is contained in this <tt>ContactDetail</tt>
* @return <tt>true</tt> if the specified <tt>label</tt> is contained in the
* set of labels of this <tt>ContactDetail</tt>
*/
public boolean containsSubCategory(SubCategory subCategory)
{
return subCategories.contains(subCategory);
}
/**
* Gets the set of labels of this <tt>ContactDetail</tt>. The labels may be
* arbitrary and may include any of the standard/well-known labels defined
* by the <tt>LABEL_XXX</tt> constants of the <tt>ContactDetail</tt> class.
*
* @return the set of labels of this <tt>ContactDetail</tt>. If this
* <tt>ContactDetail</tt> has no labels, the returned <tt>Collection</tt> is
* empty.
*/
public Collection<SubCategory> getSubCategories()
{
return Collections.unmodifiableCollection(subCategories);
}
}
| |
/*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.nucleus.regions;
import com.jcwhatever.nucleus.regions.file.IRegionFileFactory;
import com.jcwhatever.nucleus.regions.file.IRegionFileLoader.LoadSpeed;
import com.jcwhatever.nucleus.regions.file.basic.BasicFileFactory;
import com.jcwhatever.nucleus.storage.IDataNode;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.observer.future.FutureSubscriber;
import com.jcwhatever.nucleus.utils.observer.future.IFuture;
import com.jcwhatever.nucleus.utils.observer.future.IFuture.FutureStatus;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* An abstract implementation of a restorable region
* with multiple named saved snapshots.
*
* <p>The default snapshot name is "default".</p>
*/
public abstract class MultiSnapshotRegion extends RestorableRegion {
private final SnapshotFileFactory _fileFactory = new SnapshotFileFactory();
/**
* Constructor.
*
* @param plugin The owning plugin.
* @param name The name of the region.
*/
public MultiSnapshotRegion(Plugin plugin, String name) {
super(plugin, name);
}
/**
* Constructor.
*
* @param plugin The owning plugin.
* @param name The name of the region.
* @param dataNode The regions data node.
*/
public MultiSnapshotRegion(Plugin plugin, String name, IDataNode dataNode) {
super(plugin, name, dataNode);
}
@Override
public SnapshotFileFactory getFileFactory() {
if (_fileFactory.fileFactory == null)
_fileFactory.fileFactory = new BasicFileFactory();
return _fileFactory;
}
@Override
public void setFileFactory(IRegionFileFactory fileFactory) {
PreCon.notNull(fileFactory);
_fileFactory.fileFactory = fileFactory;
}
/**
* Get the name of the current snapshot.
*
* <p>The default snapshot name is "default".</p>
*/
public String getCurrentSnapshot() {
return getFileFactory().snapshotName;
}
/**
* Set the current snapshot name.
*
* @param snapshotName The snapshot name.
*/
public void setCurrentSnapshot(String snapshotName) {
PreCon.notNullOrEmpty(snapshotName);
getFileFactory().snapshotName = snapshotName;
}
/**
* Get the names of stored snapshots.
*
* <p>Snapshot names are retrieved by file name, therefore this
* only returns names of snapshots that have been saved.</p>
*
* @throws IOException
*/
public Set<String> getSnapshotNames() throws IOException {
return getSnapshotNames(new HashSet<String>(15));
}
/**
* Get the names of stored snapshots.
*
* <p>Snapshot names are retrieved by file name, therefore this
* only returns names of snapshots that have been saved.</p>
*
* @throws IOException
*/
public <T extends Collection<String>> T getSnapshotNames(T output) throws IOException {
File folder = _fileFactory.getRegionDirectory(this);
File[] files = folder.listFiles();
if (files == null)
return output;
for (File file : files) {
if (!file.isDirectory())
continue;
output.add(file.getName());
}
return output;
}
/**
* Determine if the specified snapshot can be restored.
*
* @param snapshotName The name of the snapshot.
*/
public boolean canRestore(String snapshotName) {
String current = getFileFactory().snapshotName;
getFileFactory().snapshotName = snapshotName;
boolean canRestore = getFileFormat().getLoader(this, _fileFactory).canRead();
getFileFactory().snapshotName = current;
return canRestore;
}
/**
* Restore the specified snapshot.
*
* @param loadSpeed The speed of the restore.
* @param snapshotName The name of the snapshot.
*
* @throws IOException
*/
public IFuture restoreData(LoadSpeed loadSpeed, final String snapshotName) throws IOException {
final String currentSnapshot = getFileFactory().snapshotName;
getFileFactory().snapshotName = snapshotName;
return super.restoreData(loadSpeed)
.onSuccess(new FutureSubscriber() {
@Override
public void on(FutureStatus status, @Nullable CharSequence message) {
getFileFactory().snapshotName = currentSnapshot;
}
});
}
/**
* Save the regions current state to the specified snapshot.
*
* @param snapshotName The name of the snapshot.
*
* @throws IOException
*/
public IFuture saveData(String snapshotName) throws IOException {
final String currentSnapshot = getFileFactory().snapshotName;
getFileFactory().snapshotName = snapshotName;
return super.saveData().onStatus(new FutureSubscriber() {
@Override
public void on(FutureStatus status, @Nullable CharSequence message) {
getFileFactory().snapshotName = currentSnapshot;
}
});
}
/**
* Delete the specified snapshots data.
*
* @param snapshotName The name of the snapshot.
*
* @throws IOException
*/
public void deleteData(String snapshotName) throws IOException {
PreCon.notNull(snapshotName);
final String currentSnapshot = getFileFactory().snapshotName;
getFileFactory().snapshotName = snapshotName;
super.deleteData();
getFileFactory().snapshotName = currentSnapshot;
}
public static class SnapshotFileFactory implements IRegionFileFactory {
String snapshotName = "default";
IRegionFileFactory fileFactory;
private SnapshotFileFactory() {}
@Override
public String getFilename(IRegion region) {
return fileFactory.getFilename(region);
}
@Override
public File getDirectory(IRegion region) throws IOException {
File regionFolder = getRegionDirectory(region);
File snapshotFolder = new File(regionFolder, snapshotName);
if (!snapshotFolder.exists() && !snapshotFolder.mkdirs()) {
throw new IOException("Failed to create snapshot folder.");
}
return snapshotFolder;
}
public File getRegionDirectory(IRegion region) throws IOException {
return fileFactory.getDirectory(region);
}
public String getSnapshotName() {
return snapshotName;
}
public IRegionFileFactory getInnerFactory() {
return fileFactory;
}
}
}
| |
/*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.httpserver;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.artifact_cache.ArtifactCache;
import com.facebook.buck.artifact_cache.ArtifactCaches;
import com.facebook.buck.artifact_cache.ArtifactInfo;
import com.facebook.buck.artifact_cache.CacheResult;
import com.facebook.buck.artifact_cache.CacheResultType;
import com.facebook.buck.artifact_cache.DirArtifactCacheTestUtil;
import com.facebook.buck.artifact_cache.TestArtifactCaches;
import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig;
import com.facebook.buck.config.BuckConfig;
import com.facebook.buck.config.BuckConfigTestUtils;
import com.facebook.buck.core.rulekey.RuleKey;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusForTests;
import com.facebook.buck.io.file.BorrowablePath;
import com.facebook.buck.io.file.LazyPath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.TestProjectFilesystems;
import com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystem;
import com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemDelegate;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.util.environment.Architecture;
import com.facebook.buck.util.environment.Platform;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.DataOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class ServedCacheIntegrationTest {
@Rule public TemporaryPaths tmpDir = new TemporaryPaths();
private static final Path A_FILE_PATH = Paths.get("aFile");
private static final String A_FILE_DATA = "somedata";
public static final RuleKey A_FILE_RULE_KEY = new RuleKey("0123456789");
private ProjectFilesystem projectFilesystem;
private WebServer webServer = null;
private BuckEventBus buckEventBus;
private ArtifactCache dirCache;
public static final ImmutableMap<String, String> A_FILE_METADATA =
ImmutableMap.of("key", "value");
private static final ListeningExecutorService DIRECT_EXECUTOR_SERVICE =
MoreExecutors.newDirectExecutorService();
@Before
public void setUp() throws Exception {
buckEventBus = BuckEventBusForTests.newInstance();
projectFilesystem = TestProjectFilesystems.createProjectFilesystem(tmpDir.getRoot());
projectFilesystem.writeContentsToPath(A_FILE_DATA, A_FILE_PATH);
dirCache = createArtifactCache(createMockLocalDirCacheConfig());
dirCache.store(
ArtifactInfo.builder().addRuleKeys(A_FILE_RULE_KEY).setMetadata(A_FILE_METADATA).build(),
BorrowablePath.notBorrowablePath(A_FILE_PATH));
}
@After
public void closeWebServer() throws Exception {
if (webServer != null) {
webServer.stop();
}
}
private ArtifactCacheBuckConfig createMockLocalConfig(String... configText) throws Exception {
BuckConfig config =
BuckConfigTestUtils.createFromReader(
new StringReader(Joiner.on('\n').join(configText)),
projectFilesystem,
Architecture.detect(),
Platform.detect(),
ImmutableMap.of());
return new ArtifactCacheBuckConfig(config);
}
private ArtifactCacheBuckConfig createMockLocalHttpCacheConfig(int port) throws Exception {
return createMockLocalHttpCacheConfig(port, 1);
}
private ArtifactCacheBuckConfig createMockLocalHttpCacheConfig(int port, int retryCount)
throws Exception {
return createMockLocalConfig(
"[cache]",
"mode = http",
String.format("http_url = http://127.0.0.1:%d/", port),
String.format("http_max_fetch_retries = %d", retryCount));
}
private ArtifactCacheBuckConfig createMockLocalDirCacheConfig() throws Exception {
return createMockLocalConfig(
"[cache]", "mode = dir", "dir = test-cache", "http_timeout_seconds = 10000");
}
@Test
public void testFetchFromServedDircache() throws Exception {
webServer = new WebServer(/* port */ 0, projectFilesystem);
webServer.updateAndStartIfNeeded(Optional.of(dirCache));
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get()));
Path fetchedContents = tmpDir.newFile();
CacheResult cacheResult =
Futures.getUnchecked(
serverBackedCache.fetchAsync(A_FILE_RULE_KEY, LazyPath.ofInstance(fetchedContents)));
assertThat(cacheResult.getType().isSuccess(), Matchers.is(true));
assertThat(cacheResult.getMetadata(), Matchers.equalTo(A_FILE_METADATA));
assertThat(
projectFilesystem.readFileIfItExists(fetchedContents).get(), Matchers.equalTo(A_FILE_DATA));
}
private static class ThrowAfterXBytesStream extends FilterInputStream {
private final long bytesToThrowAfter;
private long bytesRead = 0L;
public ThrowAfterXBytesStream(InputStream in, long bytesToThrowAfter) {
super(in);
this.bytesToThrowAfter = bytesToThrowAfter;
}
@Override
public int read() throws IOException {
return recordRead(super.read());
}
@Override
public int read(byte[] b) throws IOException {
return recordRead(super.read(b));
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return recordRead(super.read(b, off, len));
}
private int recordRead(int read) throws IOException {
bytesRead += read;
if (bytesRead >= bytesToThrowAfter) {
throw new IOException("Test exception while reading");
}
return read;
}
}
@Test
public void testExceptionDuringTheRead() throws Exception {
ProjectFilesystem throwingStreamFilesystem =
new DefaultProjectFilesystem(
tmpDir.getRoot(), new DefaultProjectFilesystemDelegate(tmpDir.getRoot())) {
private boolean throwingStreamServed = false;
@Override
public InputStream newFileInputStream(Path pathRelativeToProjectRoot) throws IOException {
InputStream inputStream = super.newFileInputStream(pathRelativeToProjectRoot);
if (!throwingStreamServed
&& pathRelativeToProjectRoot.toString().contains("outgoing_rulekey")) {
throwingStreamServed = true;
return new ThrowAfterXBytesStream(inputStream, 10L);
}
return inputStream;
}
};
webServer = new WebServer(/* port */ 0, throwingStreamFilesystem);
webServer.updateAndStartIfNeeded(Optional.of(dirCache));
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get()));
LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
CacheResult cacheResult =
Futures.getUnchecked(serverBackedCache.fetchAsync(A_FILE_RULE_KEY, fetchedContents));
assertThat(cacheResult.getType(), Matchers.equalTo(CacheResultType.ERROR));
// Try again to make sure the exception didn't kill the server.
cacheResult =
Futures.getUnchecked(serverBackedCache.fetchAsync(A_FILE_RULE_KEY, fetchedContents));
assertThat(cacheResult.getType(), Matchers.equalTo(CacheResultType.HIT));
}
@Test
public void testExceptionDuringTheReadRetryingFail() throws Exception {
ProjectFilesystem throwingStreamFilesystem =
new DefaultProjectFilesystem(
tmpDir.getRoot(), new DefaultProjectFilesystemDelegate(tmpDir.getRoot())) {
private int throwingStreamServedCount = 0;
@Override
public InputStream newFileInputStream(Path pathRelativeToProjectRoot) throws IOException {
InputStream inputStream = super.newFileInputStream(pathRelativeToProjectRoot);
if (throwingStreamServedCount < 3
&& pathRelativeToProjectRoot.toString().contains("outgoing_rulekey")) {
throwingStreamServedCount++;
return new ThrowAfterXBytesStream(inputStream, 10L);
}
return inputStream;
}
};
webServer = new WebServer(/* port */ 0, throwingStreamFilesystem);
webServer.updateAndStartIfNeeded(Optional.of(dirCache));
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get(), 3));
LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
CacheResult cacheResult =
Futures.getUnchecked(serverBackedCache.fetchAsync(A_FILE_RULE_KEY, fetchedContents));
assertThat(cacheResult.getType(), Matchers.equalTo(CacheResultType.ERROR));
}
@Test
public void testExceptionDuringTheReadRetryingSuccess() throws Exception {
ProjectFilesystem throwingStreamFilesystem =
new DefaultProjectFilesystem(
tmpDir.getRoot(), new DefaultProjectFilesystemDelegate(tmpDir.getRoot())) {
private int throwingStreamServedCount = 0;
@Override
public InputStream newFileInputStream(Path pathRelativeToProjectRoot) throws IOException {
InputStream inputStream = super.newFileInputStream(pathRelativeToProjectRoot);
if (throwingStreamServedCount < 3
&& pathRelativeToProjectRoot.toString().contains("outgoing_rulekey")) {
throwingStreamServedCount++;
return new ThrowAfterXBytesStream(inputStream, 10L);
}
return inputStream;
}
};
webServer = new WebServer(/* port */ 0, throwingStreamFilesystem);
webServer.updateAndStartIfNeeded(Optional.of(dirCache));
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get(), 4));
LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
CacheResult cacheResult =
Futures.getUnchecked(serverBackedCache.fetchAsync(A_FILE_RULE_KEY, fetchedContents));
assertThat(cacheResult.getType(), Matchers.equalTo(CacheResultType.HIT));
}
@Test
public void testMalformedDirCacheMetaData() throws Exception {
ArtifactCache cache =
TestArtifactCaches.createDirCacheForTest(
projectFilesystem.getRootPath(), Paths.get("test-cache"));
Path cacheFilePath =
DirArtifactCacheTestUtil.getPathForRuleKey(
cache, A_FILE_RULE_KEY, Optional.of(".metadata"));
assertThat(projectFilesystem.exists(cacheFilePath), Matchers.is(true));
try (DataOutputStream outputStream =
new DataOutputStream(projectFilesystem.newFileOutputStream(cacheFilePath))) {
outputStream.writeInt(1024);
}
webServer = new WebServer(/* port */ 0, projectFilesystem);
webServer.updateAndStartIfNeeded(Optional.of(dirCache));
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get()));
LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
CacheResult cacheResult =
Futures.getUnchecked(serverBackedCache.fetchAsync(A_FILE_RULE_KEY, fetchedContents));
assertThat(cacheResult.getType(), Matchers.equalTo(CacheResultType.MISS));
}
@Test
public void whenNoCacheIsServedLookupsAreErrors() throws Exception {
webServer = new WebServer(/* port */ 0, projectFilesystem);
webServer.updateAndStartIfNeeded(Optional.empty());
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get()));
LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
CacheResult cacheResult =
Futures.getUnchecked(serverBackedCache.fetchAsync(A_FILE_RULE_KEY, fetchedContents));
assertThat(cacheResult.getType(), Matchers.equalTo(CacheResultType.ERROR));
}
@Test
public void canSetArtifactCacheWithoutRestartingServer() throws Exception {
webServer = new WebServer(/* port */ 0, projectFilesystem);
webServer.updateAndStartIfNeeded(Optional.empty());
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get()));
LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
assertThat(
Futures.getUnchecked(serverBackedCache.fetchAsync(A_FILE_RULE_KEY, fetchedContents))
.getType(),
Matchers.equalTo(CacheResultType.ERROR));
webServer.updateAndStartIfNeeded(Optional.of(dirCache));
assertThat(
Futures.getUnchecked(serverBackedCache.fetchAsync(A_FILE_RULE_KEY, fetchedContents))
.getType(),
Matchers.equalTo(CacheResultType.HIT));
webServer.updateAndStartIfNeeded(Optional.empty());
assertThat(
Futures.getUnchecked(serverBackedCache.fetchAsync(A_FILE_RULE_KEY, fetchedContents))
.getType(),
Matchers.equalTo(CacheResultType.ERROR));
}
@Test
public void testStoreAndFetchNotBorrowable() throws Exception {
webServer = new WebServer(/* port */ 0, projectFilesystem);
webServer.updateAndStartIfNeeded(
ArtifactCaches.newServedCache(
createMockLocalConfig(
"[cache]",
"dir = test-cache",
"serve_local_cache = true",
"served_local_cache_mode = readwrite"),
projectFilesystem));
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get()));
RuleKey ruleKey = new RuleKey("00111222333444");
ImmutableMap<String, String> metadata = ImmutableMap.of("some key", "some value");
Path originalDataPath = tmpDir.newFile();
String data = "you won't believe this!";
projectFilesystem.writeContentsToPath(data, originalDataPath);
LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
CacheResult cacheResult =
Futures.getUnchecked(serverBackedCache.fetchAsync(ruleKey, fetchedContents));
assertThat(cacheResult.getType().isSuccess(), Matchers.is(false));
serverBackedCache.store(
ArtifactInfo.builder().addRuleKeys(ruleKey).setMetadata(metadata).build(),
BorrowablePath.notBorrowablePath(originalDataPath));
cacheResult = Futures.getUnchecked(serverBackedCache.fetchAsync(ruleKey, fetchedContents));
assertThat(cacheResult.getType().isSuccess(), Matchers.is(true));
assertThat(cacheResult.getMetadata(), Matchers.equalTo(metadata));
assertThat(
projectFilesystem.readFileIfItExists(fetchedContents.get()).get(), Matchers.equalTo(data));
}
@Test
public void testStoreAndFetchBorrowable() throws Exception {
webServer = new WebServer(/* port */ 0, projectFilesystem);
webServer.updateAndStartIfNeeded(
ArtifactCaches.newServedCache(
createMockLocalConfig(
"[cache]",
"dir = test-cache",
"serve_local_cache = true",
"served_local_cache_mode = readwrite"),
projectFilesystem));
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get()));
RuleKey ruleKey = new RuleKey("00111222333444");
ImmutableMap<String, String> metadata = ImmutableMap.of("some key", "some value");
Path originalDataPath = tmpDir.newFile();
String data = "you won't believe this!";
projectFilesystem.writeContentsToPath(data, originalDataPath);
LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
CacheResult cacheResult =
Futures.getUnchecked(serverBackedCache.fetchAsync(ruleKey, fetchedContents));
assertThat(cacheResult.getType().isSuccess(), Matchers.is(false));
serverBackedCache.store(
ArtifactInfo.builder().addRuleKeys(ruleKey).setMetadata(metadata).build(),
BorrowablePath.borrowablePath(originalDataPath));
cacheResult = Futures.getUnchecked(serverBackedCache.fetchAsync(ruleKey, fetchedContents));
assertThat(cacheResult.getType().isSuccess(), Matchers.is(true));
assertThat(cacheResult.getMetadata(), Matchers.equalTo(metadata));
assertThat(
projectFilesystem.readFileIfItExists(fetchedContents.get()).get(), Matchers.equalTo(data));
}
@Test
public void testStoreDisabled() throws Exception {
webServer = new WebServer(/* port */ 0, projectFilesystem);
webServer.updateAndStartIfNeeded(
ArtifactCaches.newServedCache(
createMockLocalConfig(
"[cache]",
"dir = test-cache",
"serve_local_cache = true",
"served_local_cache_mode = readonly"),
projectFilesystem));
ArtifactCache serverBackedCache =
createArtifactCache(createMockLocalHttpCacheConfig(webServer.getPort().get()));
RuleKey ruleKey = new RuleKey("00111222333444");
ImmutableMap<String, String> metadata = ImmutableMap.of("some key", "some value");
Path originalDataPath = tmpDir.newFile();
String data = "you won't believe this!";
projectFilesystem.writeContentsToPath(data, originalDataPath);
LazyPath fetchedContents = LazyPath.ofInstance(tmpDir.newFile());
CacheResult cacheResult =
Futures.getUnchecked(serverBackedCache.fetchAsync(ruleKey, fetchedContents));
assertThat(cacheResult.getType().isSuccess(), Matchers.is(false));
serverBackedCache.store(
ArtifactInfo.builder().addRuleKeys(ruleKey).setMetadata(metadata).build(),
BorrowablePath.notBorrowablePath(originalDataPath));
cacheResult = Futures.getUnchecked(serverBackedCache.fetchAsync(ruleKey, fetchedContents));
assertThat(cacheResult.getType().isSuccess(), Matchers.is(false));
}
@Test
public void fullStackIntegrationTest() throws Exception {
webServer = new WebServer(/* port */ 0, projectFilesystem);
webServer.updateAndStartIfNeeded(
ArtifactCaches.newServedCache(
createMockLocalConfig(
"[cache]",
"dir = test-cache",
"serve_local_cache = true",
"served_local_cache_mode = readonly"),
projectFilesystem));
ArtifactCache serverBackedCache =
createArtifactCache(
createMockLocalConfig(
"[cache]",
"mode = dir,http",
"two_level_cache_enabled=true",
"two_level_cache_minimum_size=0b",
"dir = server-backed-dir-cache",
String.format("http_url = http://127.0.0.1:%d/", webServer.getPort().get())));
ArtifactCache serverBackedDirCache =
createArtifactCache(
createMockLocalConfig("[cache]", "mode = dir", "dir = server-backed-dir-cache"));
assertFalse(containsKey(serverBackedDirCache, A_FILE_RULE_KEY));
assertTrue(containsKey(serverBackedCache, A_FILE_RULE_KEY));
// The previous call should have propagated the key into the dir-cache.
assertTrue(containsKey(serverBackedDirCache, A_FILE_RULE_KEY));
RuleKey ruleKey = new RuleKey("00111222333444");
ImmutableMap<String, String> metadata = ImmutableMap.of("some key", "some value");
Path originalDataPath = tmpDir.newFile();
String data = "you won't believe this!";
projectFilesystem.writeContentsToPath(data, originalDataPath);
assertFalse(containsKey(serverBackedCache, ruleKey));
serverBackedCache
.store(
ArtifactInfo.builder().addRuleKeys(ruleKey).setMetadata(metadata).build(),
BorrowablePath.borrowablePath(originalDataPath))
.get();
assertTrue(containsKey(serverBackedCache, ruleKey));
assertTrue(containsKey(serverBackedDirCache, ruleKey));
}
private boolean containsKey(ArtifactCache cache, RuleKey ruleKey) throws Exception {
Path fetchedContents = tmpDir.newFile();
CacheResult cacheResult =
Futures.getUnchecked(cache.fetchAsync(ruleKey, LazyPath.ofInstance(fetchedContents)));
assertThat(cacheResult.getType(), Matchers.oneOf(CacheResultType.HIT, CacheResultType.MISS));
return cacheResult.getType().isSuccess();
}
private ArtifactCache createArtifactCache(ArtifactCacheBuckConfig buckConfig) {
return new ArtifactCaches(
buckConfig,
buckEventBus,
projectFilesystem,
Optional.empty(),
DIRECT_EXECUTOR_SERVICE,
DIRECT_EXECUTOR_SERVICE,
DIRECT_EXECUTOR_SERVICE,
DIRECT_EXECUTOR_SERVICE)
.newInstance();
}
}
| |
/*
* 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.druid.indexing.overlord.sampler;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.druid.client.indexing.SamplerResponse;
import org.apache.druid.client.indexing.SamplerResponse.SamplerResponseRow;
import org.apache.druid.data.input.InputFormat;
import org.apache.druid.data.input.InputRow;
import org.apache.druid.data.input.InputRowListPlusRawValues;
import org.apache.druid.data.input.InputRowSchema;
import org.apache.druid.data.input.InputSource;
import org.apache.druid.data.input.InputSourceReader;
import org.apache.druid.data.input.Row;
import org.apache.druid.data.input.impl.DimensionsSpec;
import org.apache.druid.data.input.impl.TimedShutoffInputSourceReader;
import org.apache.druid.data.input.impl.TimestampSpec;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.FileUtils;
import org.apache.druid.java.util.common.io.Closer;
import org.apache.druid.java.util.common.parsers.CloseableIterator;
import org.apache.druid.java.util.common.parsers.ParseException;
import org.apache.druid.query.aggregation.Aggregator;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.query.aggregation.LongMinAggregatorFactory;
import org.apache.druid.segment.column.ColumnHolder;
import org.apache.druid.segment.incremental.IncrementalIndex;
import org.apache.druid.segment.incremental.IncrementalIndexAddResult;
import org.apache.druid.segment.incremental.IncrementalIndexSchema;
import org.apache.druid.segment.incremental.OnheapIncrementalIndex;
import org.apache.druid.segment.indexing.DataSchema;
import javax.annotation.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
public class InputSourceSampler
{
private static final String SAMPLER_DATA_SOURCE = "sampler";
private static final DataSchema DEFAULT_DATA_SCHEMA = new DataSchema(
SAMPLER_DATA_SOURCE,
new TimestampSpec(null, null, null),
new DimensionsSpec(null),
null,
null,
null
);
// We want to be able to sort the list of processed results back into the same order that we read them from the
// firehose so that the rows in the data loader are not always changing. To do this, we add a temporary column to the
// InputRow (in SamplerInputRow) and tag each row with a sortKey. We use an aggregator so that it will not affect
// rollup, and we use a longMin aggregator so that as rows get rolled up, the earlier rows stay stable and later
// rows may get rolled into these rows. After getting the results back from the IncrementalIndex, we sort by this
// column and then exclude it from the response.
private static final AggregatorFactory INTERNAL_ORDERING_AGGREGATOR = new LongMinAggregatorFactory(
SamplerInputRow.SAMPLER_ORDERING_COLUMN,
SamplerInputRow.SAMPLER_ORDERING_COLUMN
);
public SamplerResponse sample(
final InputSource inputSource,
// inputFormat can be null only if inputSource.needsFormat() = false or parser is specified.
@Nullable final InputFormat inputFormat,
@Nullable final DataSchema dataSchema,
@Nullable final SamplerConfig samplerConfig
)
{
Preconditions.checkNotNull(inputSource, "inputSource required");
if (inputSource.needsFormat()) {
Preconditions.checkNotNull(inputFormat, "inputFormat required");
}
final DataSchema nonNullDataSchema = dataSchema == null
? DEFAULT_DATA_SCHEMA
: dataSchema;
final SamplerConfig nonNullSamplerConfig = samplerConfig == null
? SamplerConfig.empty()
: samplerConfig;
final Closer closer = Closer.create();
final File tempDir = FileUtils.createTempDir();
closer.register(() -> FileUtils.deleteDirectory(tempDir));
final InputSourceReader reader = buildReader(
nonNullSamplerConfig,
nonNullDataSchema,
inputSource,
inputFormat,
tempDir
);
try (final CloseableIterator<InputRowListPlusRawValues> iterator = reader.sample();
final IncrementalIndex<Aggregator> index = buildIncrementalIndex(nonNullSamplerConfig, nonNullDataSchema);
final Closer closer1 = closer) {
List<SamplerResponseRow> responseRows = new ArrayList<>(nonNullSamplerConfig.getNumRows());
int numRowsIndexed = 0;
while (responseRows.size() < nonNullSamplerConfig.getNumRows() && iterator.hasNext()) {
final InputRowListPlusRawValues inputRowListPlusRawValues = iterator.next();
final List<Map<String, Object>> rawColumnsList = inputRowListPlusRawValues.getRawValuesList();
final ParseException parseException = inputRowListPlusRawValues.getParseException();
if (parseException != null) {
if (rawColumnsList != null) {
// add all rows to response
responseRows.addAll(rawColumnsList.stream()
.map(rawColumns -> new SamplerResponseRow(rawColumns, null, true, parseException.getMessage()))
.collect(Collectors.toList()));
} else {
// no data parsed, add one response row
responseRows.add(new SamplerResponseRow(null, null, true, parseException.getMessage()));
}
continue;
}
List<InputRow> inputRows = inputRowListPlusRawValues.getInputRows();
if (inputRows == null) {
continue;
}
for (int i = 0; i < inputRows.size(); i++) {
// InputRowListPlusRawValues guarantees the size of rawColumnsList and inputRows are the same
Map<String, Object> rawColumns = rawColumnsList == null ? null : rawColumnsList.get(i);
InputRow row = inputRows.get(i);
//keep the index of the row to be added to responseRows for further use
final int rowIndex = responseRows.size();
IncrementalIndexAddResult addResult = index.add(new SamplerInputRow(row, rowIndex), true);
if (addResult.hasParseException()) {
responseRows.add(new SamplerResponseRow(rawColumns, null, true, addResult.getParseException().getMessage()));
} else {
// store the raw value; will be merged with the data from the IncrementalIndex later
responseRows.add(new SamplerResponseRow(rawColumns, null, null, null));
numRowsIndexed++;
}
}
}
final List<String> columnNames = index.getColumnNames();
columnNames.remove(SamplerInputRow.SAMPLER_ORDERING_COLUMN);
for (Row row : index) {
Map<String, Object> parsed = new HashMap<>();
columnNames.forEach(k -> parsed.put(k, row.getRaw(k)));
parsed.put(ColumnHolder.TIME_COLUMN_NAME, row.getTimestampFromEpoch());
Number sortKey = row.getMetric(SamplerInputRow.SAMPLER_ORDERING_COLUMN);
if (sortKey != null) {
responseRows.set(sortKey.intValue(), responseRows.get(sortKey.intValue()).withParsed(parsed));
}
}
// make sure size of responseRows meets the input
if (responseRows.size() > nonNullSamplerConfig.getNumRows()) {
responseRows = responseRows.subList(0, nonNullSamplerConfig.getNumRows());
}
int numRowsRead = responseRows.size();
return new SamplerResponse(
numRowsRead,
numRowsIndexed,
responseRows.stream()
.filter(Objects::nonNull)
.filter(x -> x.getParsed() != null || x.isUnparseable() != null)
.collect(Collectors.toList())
);
}
catch (Exception e) {
throw new SamplerException(e, "Failed to sample data: %s", e.getMessage());
}
}
private InputSourceReader buildReader(
SamplerConfig samplerConfig,
DataSchema dataSchema,
InputSource inputSource,
@Nullable InputFormat inputFormat,
File tempDir
)
{
final List<String> metricsNames = Arrays.stream(dataSchema.getAggregators())
.map(AggregatorFactory::getName)
.collect(Collectors.toList());
final InputRowSchema inputRowSchema = new InputRowSchema(
dataSchema.getTimestampSpec(),
dataSchema.getDimensionsSpec(),
metricsNames
);
InputSourceReader reader = inputSource.reader(inputRowSchema, inputFormat, tempDir);
if (samplerConfig.getTimeoutMs() > 0) {
reader = new TimedShutoffInputSourceReader(reader, DateTimes.nowUtc().plusMillis(samplerConfig.getTimeoutMs()));
}
return dataSchema.getTransformSpec().decorate(reader);
}
private IncrementalIndex<Aggregator> buildIncrementalIndex(SamplerConfig samplerConfig, DataSchema dataSchema)
{
final IncrementalIndexSchema schema = new IncrementalIndexSchema.Builder()
.withTimestampSpec(dataSchema.getTimestampSpec())
.withQueryGranularity(dataSchema.getGranularitySpec().getQueryGranularity())
.withDimensionsSpec(dataSchema.getDimensionsSpec())
.withMetrics(ArrayUtils.addAll(dataSchema.getAggregators(), INTERNAL_ORDERING_AGGREGATOR))
.withRollup(dataSchema.getGranularitySpec().isRollup())
.build();
return new OnheapIncrementalIndex.Builder().setIndexSchema(schema)
.setMaxRowCount(samplerConfig.getNumRows())
.build();
}
}
| |
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* 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 copyright holders 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 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 com.sleepycat.asm;
/**
* A label represents a position in the bytecode of a method. Labels are used
* for jump, goto, and switch instructions, and for try catch blocks. A label
* designates the <i>instruction</i> that is just after. Note however that
* there can be other elements between a label and the instruction it
* designates (such as other labels, stack map frames, line numbers, etc.).
*
* @author Eric Bruneton
*/
public class Label {
/**
* Indicates if this label is only used for debug attributes. Such a label
* is not the start of a basic block, the target of a jump instruction, or
* an exception handler. It can be safely ignored in control flow graph
* analysis algorithms (for optimization purposes).
*/
static final int DEBUG = 1;
/**
* Indicates if the position of this label is known.
*/
static final int RESOLVED = 2;
/**
* Indicates if this label has been updated, after instruction resizing.
*/
static final int RESIZED = 4;
/**
* Indicates if this basic block has been pushed in the basic block stack.
* See {@link MethodWriter#visitMaxs visitMaxs}.
*/
static final int PUSHED = 8;
/**
* Indicates if this label is the target of a jump instruction, or the start
* of an exception handler.
*/
static final int TARGET = 16;
/**
* Indicates if a stack map frame must be stored for this label.
*/
static final int STORE = 32;
/**
* Indicates if this label corresponds to a reachable basic block.
*/
static final int REACHABLE = 64;
/**
* Indicates if this basic block ends with a JSR instruction.
*/
static final int JSR = 128;
/**
* Indicates if this basic block ends with a RET instruction.
*/
static final int RET = 256;
/**
* Indicates if this basic block is the start of a subroutine.
*/
static final int SUBROUTINE = 512;
/**
* Indicates if this subroutine basic block has been visited by a
* visitSubroutine(null, ...) call.
*/
static final int VISITED = 1024;
/**
* Indicates if this subroutine basic block has been visited by a
* visitSubroutine(!null, ...) call.
*/
static final int VISITED2 = 2048;
/**
* Field used to associate user information to a label. Warning: this field
* is used by the ASM tree package. In order to use it with the ASM tree
* package you must override the {@link
* org.objectweb.asm.tree.MethodNode#getLabelNode} method.
*/
public Object info;
/**
* Flags that indicate the status of this label.
*
* @see #DEBUG
* @see #RESOLVED
* @see #RESIZED
* @see #PUSHED
* @see #TARGET
* @see #STORE
* @see #REACHABLE
* @see #JSR
* @see #RET
*/
int status;
/**
* The line number corresponding to this label, if known.
*/
int line;
/**
* The position of this label in the code, if known.
*/
int position;
/**
* Number of forward references to this label, times two.
*/
private int referenceCount;
/**
* Informations about forward references. Each forward reference is
* described by two consecutive integers in this array: the first one is the
* position of the first byte of the bytecode instruction that contains the
* forward reference, while the second is the position of the first byte of
* the forward reference itself. In fact the sign of the first integer
* indicates if this reference uses 2 or 4 bytes, and its absolute value
* gives the position of the bytecode instruction. This array is also used
* as a bitset to store the subroutines to which a basic block belongs. This
* information is needed in {@linked MethodWriter#visitMaxs}, after all
* forward references have been resolved. Hence the same array can be used
* for both purposes without problems.
*/
private int[] srcAndRefPositions;
// ------------------------------------------------------------------------
/*
* Fields for the control flow and data flow graph analysis algorithms (used
* to compute the maximum stack size or the stack map frames). A control
* flow graph contains one node per "basic block", and one edge per "jump"
* from one basic block to another. Each node (i.e., each basic block) is
* represented by the Label object that corresponds to the first instruction
* of this basic block. Each node also stores the list of its successors in
* the graph, as a linked list of Edge objects.
*
* The control flow analysis algorithms used to compute the maximum stack
* size or the stack map frames are similar and use two steps. The first
* step, during the visit of each instruction, builds information about the
* state of the local variables and the operand stack at the end of each
* basic block, called the "output frame", <i>relatively</i> to the frame
* state at the beginning of the basic block, which is called the "input
* frame", and which is <i>unknown</i> during this step. The second step,
* in {@link MethodWriter#visitMaxs}, is a fix point algorithm that
* computes information about the input frame of each basic block, from the
* input state of the first basic block (known from the method signature),
* and by the using the previously computed relative output frames.
*
* The algorithm used to compute the maximum stack size only computes the
* relative output and absolute input stack heights, while the algorithm
* used to compute stack map frames computes relative output frames and
* absolute input frames.
*/
/**
* Start of the output stack relatively to the input stack. The exact
* semantics of this field depends on the algorithm that is used.
*
* When only the maximum stack size is computed, this field is the number of
* elements in the input stack.
*
* When the stack map frames are completely computed, this field is the
* offset of the first output stack element relatively to the top of the
* input stack. This offset is always negative or null. A null offset means
* that the output stack must be appended to the input stack. A -n offset
* means that the first n output stack elements must replace the top n input
* stack elements, and that the other elements must be appended to the input
* stack.
*/
int inputStackTop;
/**
* Maximum height reached by the output stack, relatively to the top of the
* input stack. This maximum is always positive or null.
*/
int outputStackMax;
/**
* Information about the input and output stack map frames of this basic
* block. This field is only used when {@link ClassWriter#COMPUTE_FRAMES}
* option is used.
*/
Frame frame;
/**
* The successor of this label, in the order they are visited. This linked
* list does not include labels used for debug info only. If
* {@link ClassWriter#COMPUTE_FRAMES} option is used then, in addition, it
* does not contain successive labels that denote the same bytecode position
* (in this case only the first label appears in this list).
*/
Label successor;
/**
* The successors of this node in the control flow graph. These successors
* are stored in a linked list of {@link Edge Edge} objects, linked to each
* other by their {@link Edge#next} field.
*/
Edge successors;
/**
* The next basic block in the basic block stack. This stack is used in the
* main loop of the fix point algorithm used in the second step of the
* control flow analysis algorithms. It is also used in
* {@link #visitSubroutine} to avoid using a recursive method.
*
* @see MethodWriter#visitMaxs
*/
Label next;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
/**
* Constructs a new label.
*/
public Label() {
}
// ------------------------------------------------------------------------
// Methods to compute offsets and to manage forward references
// ------------------------------------------------------------------------
/**
* Returns the offset corresponding to this label. This offset is computed
* from the start of the method's bytecode. <i>This method is intended for
* {@link Attribute} sub classes, and is normally not needed by class
* generators or adapters.</i>
*
* @return the offset corresponding to this label.
* @throws IllegalStateException if this label is not resolved yet.
*/
public int getOffset() {
if ((status & RESOLVED) == 0) {
throw new IllegalStateException("Label offset position has not been resolved yet");
}
return position;
}
/**
* Puts a reference to this label in the bytecode of a method. If the
* position of the label is known, the offset is computed and written
* directly. Otherwise, a null offset is written and a new forward reference
* is declared for this label.
*
* @param owner the code writer that calls this method.
* @param out the bytecode of the method.
* @param source the position of first byte of the bytecode instruction that
* contains this label.
* @param wideOffset <tt>true</tt> if the reference must be stored in 4
* bytes, or <tt>false</tt> if it must be stored with 2 bytes.
* @throws IllegalArgumentException if this label has not been created by
* the given code writer.
*/
void put(
final MethodWriter owner,
final ByteVector out,
final int source,
final boolean wideOffset)
{
if ((status & RESOLVED) == 0) {
if (wideOffset) {
addReference(-1 - source, out.length);
out.putInt(-1);
} else {
addReference(source, out.length);
out.putShort(-1);
}
} else {
if (wideOffset) {
out.putInt(position - source);
} else {
out.putShort(position - source);
}
}
}
/**
* Adds a forward reference to this label. This method must be called only
* for a true forward reference, i.e. only if this label is not resolved
* yet. For backward references, the offset of the reference can be, and
* must be, computed and stored directly.
*
* @param sourcePosition the position of the referencing instruction. This
* position will be used to compute the offset of this forward
* reference.
* @param referencePosition the position where the offset for this forward
* reference must be stored.
*/
private void addReference(
final int sourcePosition,
final int referencePosition)
{
if (srcAndRefPositions == null) {
srcAndRefPositions = new int[6];
}
if (referenceCount >= srcAndRefPositions.length) {
int[] a = new int[srcAndRefPositions.length + 6];
System.arraycopy(srcAndRefPositions,
0,
a,
0,
srcAndRefPositions.length);
srcAndRefPositions = a;
}
srcAndRefPositions[referenceCount++] = sourcePosition;
srcAndRefPositions[referenceCount++] = referencePosition;
}
/**
* Resolves all forward references to this label. This method must be called
* when this label is added to the bytecode of the method, i.e. when its
* position becomes known. This method fills in the blanks that where left
* in the bytecode by each forward reference previously added to this label.
*
* @param owner the code writer that calls this method.
* @param position the position of this label in the bytecode.
* @param data the bytecode of the method.
* @return <tt>true</tt> if a blank that was left for this label was to
* small to store the offset. In such a case the corresponding jump
* instruction is replaced with a pseudo instruction (using unused
* opcodes) using an unsigned two bytes offset. These pseudo
* instructions will need to be replaced with true instructions with
* wider offsets (4 bytes instead of 2). This is done in
* {@link MethodWriter#resizeInstructions}.
* @throws IllegalArgumentException if this label has already been resolved,
* or if it has not been created by the given code writer.
*/
boolean resolve(
final MethodWriter owner,
final int position,
final byte[] data)
{
boolean needUpdate = false;
this.status |= RESOLVED;
this.position = position;
int i = 0;
while (i < referenceCount) {
int source = srcAndRefPositions[i++];
int reference = srcAndRefPositions[i++];
int offset;
if (source >= 0) {
offset = position - source;
if (offset < Short.MIN_VALUE || offset > Short.MAX_VALUE) {
/*
* changes the opcode of the jump instruction, in order to
* be able to find it later (see resizeInstructions in
* MethodWriter). These temporary opcodes are similar to
* jump instruction opcodes, except that the 2 bytes offset
* is unsigned (and can therefore represent values from 0 to
* 65535, which is sufficient since the size of a method is
* limited to 65535 bytes).
*/
int opcode = data[reference - 1] & 0xFF;
if (opcode <= Opcodes.JSR) {
// changes IFEQ ... JSR to opcodes 202 to 217
data[reference - 1] = (byte) (opcode + 49);
} else {
// changes IFNULL and IFNONNULL to opcodes 218 and 219
data[reference - 1] = (byte) (opcode + 20);
}
needUpdate = true;
}
data[reference++] = (byte) (offset >>> 8);
data[reference] = (byte) offset;
} else {
offset = position + source + 1;
data[reference++] = (byte) (offset >>> 24);
data[reference++] = (byte) (offset >>> 16);
data[reference++] = (byte) (offset >>> 8);
data[reference] = (byte) offset;
}
}
return needUpdate;
}
/**
* Returns the first label of the series to which this label belongs. For an
* isolated label or for the first label in a series of successive labels,
* this method returns the label itself. For other labels it returns the
* first label of the series.
*
* @return the first label of the series to which this label belongs.
*/
Label getFirst() {
return !ClassReader.FRAMES || frame == null ? this : frame.owner;
}
// ------------------------------------------------------------------------
// Methods related to subroutines
// ------------------------------------------------------------------------
/**
* Returns true is this basic block belongs to the given subroutine.
*
* @param id a subroutine id.
* @return true is this basic block belongs to the given subroutine.
*/
boolean inSubroutine(final long id) {
if ((status & Label.VISITED) != 0) {
return (srcAndRefPositions[(int) (id >>> 32)] & (int) id) != 0;
}
return false;
}
/**
* Returns true if this basic block and the given one belong to a common
* subroutine.
*
* @param block another basic block.
* @return true if this basic block and the given one belong to a common
* subroutine.
*/
boolean inSameSubroutine(final Label block) {
if ((status & VISITED) == 0 || (block.status & VISITED) == 0) {
return false;
}
for (int i = 0; i < srcAndRefPositions.length; ++i) {
if ((srcAndRefPositions[i] & block.srcAndRefPositions[i]) != 0) {
return true;
}
}
return false;
}
/**
* Marks this basic block as belonging to the given subroutine.
*
* @param id a subroutine id.
* @param nbSubroutines the total number of subroutines in the method.
*/
void addToSubroutine(final long id, final int nbSubroutines) {
if ((status & VISITED) == 0) {
status |= VISITED;
srcAndRefPositions = new int[(nbSubroutines - 1) / 32 + 1];
}
srcAndRefPositions[(int) (id >>> 32)] |= (int) id;
}
/**
* Finds the basic blocks that belong to a given subroutine, and marks these
* blocks as belonging to this subroutine. This method follows the control
* flow graph to find all the blocks that are reachable from the current
* block WITHOUT following any JSR target.
*
* @param JSR a JSR block that jumps to this subroutine. If this JSR is not
* null it is added to the successor of the RET blocks found in the
* subroutine.
* @param id the id of this subroutine.
* @param nbSubroutines the total number of subroutines in the method.
*/
void visitSubroutine(final Label JSR, final long id, final int nbSubroutines)
{
// user managed stack of labels, to avoid using a recursive method
// (recursivity can lead to stack overflow with very large methods)
Label stack = this;
while (stack != null) {
// removes a label l from the stack
Label l = stack;
stack = l.next;
l.next = null;
if (JSR != null) {
if ((l.status & VISITED2) != 0) {
continue;
}
l.status |= VISITED2;
// adds JSR to the successors of l, if it is a RET block
if ((l.status & RET) != 0) {
if (!l.inSameSubroutine(JSR)) {
Edge e = new Edge();
e.info = l.inputStackTop;
e.successor = JSR.successors.successor;
e.next = l.successors;
l.successors = e;
}
}
} else {
// if the l block already belongs to subroutine 'id', continue
if (l.inSubroutine(id)) {
continue;
}
// marks the l block as belonging to subroutine 'id'
l.addToSubroutine(id, nbSubroutines);
}
// pushes each successor of l on the stack, except JSR targets
Edge e = l.successors;
while (e != null) {
// if the l block is a JSR block, then 'l.successors.next' leads
// to the JSR target (see {@link #visitJumpInsn}) and must
// therefore not be followed
if ((l.status & Label.JSR) == 0 || e != l.successors.next) {
// pushes e.successor on the stack if it not already added
if (e.successor.next == null) {
e.successor.next = stack;
stack = e.successor;
}
}
e = e.next;
}
}
}
// ------------------------------------------------------------------------
// Overriden Object methods
// ------------------------------------------------------------------------
/**
* Returns a string representation of this label.
*
* @return a string representation of this label.
*/
@Override
public String toString() {
return "L" + System.identityHashCode(this);
}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.codeInsight.*;
import com.intellij.codeInsight.completion.scope.JavaCompletionProcessor;
import com.intellij.codeInsight.lookup.*;
import com.intellij.openapi.util.Key;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PatternCondition;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.patterns.PsiJavaPatterns;
import com.intellij.psi.*;
import com.intellij.psi.filters.ElementExtractorFilter;
import com.intellij.psi.filters.ElementFilter;
import com.intellij.psi.filters.OrFilter;
import com.intellij.psi.filters.getters.ExpectedTypesGetter;
import com.intellij.psi.filters.getters.InstanceOfLeftPartTypeGetter;
import com.intellij.psi.filters.getters.JavaMembersGetter;
import com.intellij.psi.filters.types.AssignableFromFilter;
import com.intellij.psi.filters.types.AssignableToFilter;
import com.intellij.psi.impl.source.PsiLabelReference;
import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import gnu.trove.TObjectHashingStrategy;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.patterns.PlatformPatterns.psiElement;
import static com.intellij.patterns.PsiJavaPatterns.psiMethod;
import static com.intellij.patterns.StandardPatterns.*;
/**
* @author peter
*/
public class JavaSmartCompletionContributor extends CompletionContributor {
private static final TObjectHashingStrategy<ExpectedTypeInfo> EXPECTED_TYPE_INFO_STRATEGY = new TObjectHashingStrategy<ExpectedTypeInfo>() {
@Override
public int computeHashCode(final ExpectedTypeInfo object) {
return object.getType().hashCode();
}
@Override
public boolean equals(final ExpectedTypeInfo o1, final ExpectedTypeInfo o2) {
return o1.getType().equals(o2.getType());
}
};
private static final ElementExtractorFilter THROWABLES_FILTER = new ElementExtractorFilter(new AssignableFromFilter(CommonClassNames.JAVA_LANG_THROWABLE));
@NonNls private static final String EXCEPTION_TAG = "exception";
public static final ElementPattern<PsiElement> AFTER_NEW =
psiElement().afterLeaf(
psiElement().withText(PsiKeyword.NEW).andNot(
psiElement().afterLeaf(
psiElement().withText(PsiKeyword.THROW))));
static final ElementPattern<PsiElement> AFTER_THROW_NEW = psiElement().afterLeaf(psiElement().withText(PsiKeyword.NEW).afterLeaf(PsiKeyword.THROW));
public static final ElementPattern<PsiElement> INSIDE_EXPRESSION = or(
psiElement().withParent(PsiExpression.class).andNot(psiElement().withParent(PsiLiteralExpression.class)).andNot(psiElement().withParent(PsiMethodReferenceExpression.class)),
psiElement().inside(PsiClassObjectAccessExpression.class),
psiElement().inside(PsiThisExpression.class),
psiElement().inside(PsiSuperExpression.class)
);
static final ElementPattern<PsiElement> INSIDE_TYPECAST_EXPRESSION = psiElement().withParent(
psiElement(PsiReferenceExpression.class).afterLeaf(
psiElement().withText(")").withParent(PsiTypeCastExpression.class)));
static final PsiElementPattern.Capture<PsiElement> IN_TYPE_ARGS =
psiElement().inside(psiElement(PsiReferenceParameterList.class));
static final PsiElementPattern.Capture<PsiElement> LAMBDA = psiElement().with(new PatternCondition<PsiElement>("LAMBDA_CONTEXT") {
@Override
public boolean accepts(@NotNull PsiElement element, ProcessingContext context) {
final PsiElement rulezzRef = element.getParent();
return rulezzRef != null &&
rulezzRef instanceof PsiReferenceExpression &&
((PsiReferenceExpression)rulezzRef).getQualifier() == null &&
LambdaUtil.isValidLambdaContext(rulezzRef.getParent());
}});
static final PsiElementPattern.Capture<PsiElement> METHOD_REFERENCE = psiElement().with(new PatternCondition<PsiElement>("METHOD_REFERENCE_CONTEXT") {
@Override
public boolean accepts(@NotNull PsiElement element, ProcessingContext context) {
final PsiElement rulezzRef = element.getParent();
return rulezzRef != null &&
LambdaUtil.isValidLambdaContext(rulezzRef.getParent());
}});
@Nullable
private static ElementFilter getReferenceFilter(PsiElement element) {
//throw new foo
if (AFTER_THROW_NEW.accepts(element)) {
return THROWABLES_FILTER;
}
//new xxx.yyy
if (psiElement().afterLeaf(psiElement().withText(".")).withSuperParent(2, psiElement(PsiNewExpression.class)).accepts(element)) {
if (((PsiNewExpression)element.getParent().getParent()).getClassReference() == element.getParent()) {
PsiType[] types = ExpectedTypesGetter.getExpectedTypes(element, false);
return new OrFilter(ContainerUtil.map2Array(types, ElementFilter.class, new Function<PsiType, ElementFilter>() {
@Override
public ElementFilter fun(PsiType type) {
return new AssignableFromFilter(type);
}
}));
}
}
return null;
}
public JavaSmartCompletionContributor() {
extend(CompletionType.SMART, SmartCastProvider.TYPECAST_TYPE_CANDIDATE, new SmartCastProvider());
extend(CompletionType.SMART, SameSignatureCallParametersProvider.IN_CALL_ARGUMENT, new SameSignatureCallParametersProvider());
extend(CompletionType.SMART, MethodReturnTypeProvider.IN_METHOD_RETURN_TYPE, new MethodReturnTypeProvider());
extend(CompletionType.SMART, psiElement().afterLeaf(PsiKeyword.INSTANCEOF), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext context, @NotNull final CompletionResultSet result) {
final PsiElement position = parameters.getPosition();
final PsiType[] leftTypes = InstanceOfLeftPartTypeGetter.getLeftTypes(position);
final Set<PsiClassType> expectedClassTypes = new LinkedHashSet<PsiClassType>();
final Set<PsiClass> parameterizedTypes = new THashSet<PsiClass>();
for (final PsiType type : leftTypes) {
if (type instanceof PsiClassType) {
final PsiClassType classType = (PsiClassType)type;
if (!classType.isRaw()) {
ContainerUtil.addIfNotNull(classType.resolve(), parameterizedTypes);
}
expectedClassTypes.add(classType.rawType());
}
}
JavaInheritorsGetter
.processInheritors(parameters, expectedClassTypes, result.getPrefixMatcher(), new Consumer<PsiType>() {
@Override
public void consume(PsiType type) {
final PsiClass psiClass = PsiUtil.resolveClassInType(type);
if (psiClass == null || psiClass instanceof PsiTypeParameter) return;
//noinspection SuspiciousMethodCalls
if (expectedClassTypes.contains(type)) return;
result.addElement(createInstanceofLookupElement(psiClass, parameterizedTypes));
}
});
}
});
extend(CompletionType.SMART, psiElement(), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext context, @NotNull final CompletionResultSet result) {
if (SmartCastProvider.shouldSuggestCast(parameters)) return;
final PsiElement element = parameters.getPosition();
final PsiReference reference = element.getContainingFile().findReferenceAt(parameters.getOffset());
if (reference != null) {
ElementFilter filter = getReferenceFilter(element);
if (filter != null) {
final List<ExpectedTypeInfo> infos = Arrays.asList(getExpectedTypes(parameters));
for (final LookupElement item : completeReference(element, reference, filter, true, false, parameters, result.getPrefixMatcher())) {
if (item.getObject() instanceof PsiClass) {
result.addElement(decorate(LookupElementDecorator.withInsertHandler(item, ConstructorInsertHandler.SMART_INSTANCE), infos));
}
}
}
else if (INSIDE_TYPECAST_EXPRESSION.accepts(element)) {
final PsiTypeCastExpression cast = PsiTreeUtil.getContextOfType(element, PsiTypeCastExpression.class, true);
if (cast != null && cast.getCastType() != null) {
filter = new AssignableToFilter(cast.getCastType().getType());
for (final LookupElement item : completeReference(element, reference, filter, false, true, parameters, result.getPrefixMatcher())) {
result.addElement(item);
}
}
}
}
}
});
//method throws clause
extend(CompletionType.SMART, psiElement().inside(
psiElement(PsiReferenceList.class).save("refList").withParent(
psiMethod().withThrowsList(get("refList")))), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
ProcessingContext context,
@NotNull CompletionResultSet result) {
final PsiElement element = parameters.getPosition();
final PsiReference reference = element.getContainingFile().findReferenceAt(parameters.getOffset());
assert reference != null;
for (final LookupElement item : completeReference(element, reference, THROWABLES_FILTER, true, false, parameters, result.getPrefixMatcher())) {
result.addElement(item);
}
}
});
extend(CompletionType.SMART, INSIDE_EXPRESSION, new ExpectedTypeBasedCompletionProvider() {
@Override
protected void addCompletions(final CompletionParameters params, final CompletionResultSet result, final Collection<ExpectedTypeInfo> _infos) {
if (SmartCastProvider.shouldSuggestCast(params)) return;
Consumer<LookupElement> noTypeCheck = decorateWithoutTypeCheck(result, _infos);
THashSet<ExpectedTypeInfo> mergedInfos = new THashSet<ExpectedTypeInfo>(_infos, EXPECTED_TYPE_INFO_STRATEGY);
List<Runnable> chainedEtc = new ArrayList<Runnable>();
for (final ExpectedTypeInfo info : mergedInfos) {
Runnable slowContinuation =
ReferenceExpressionCompletionContributor.fillCompletionVariants(new JavaSmartCompletionParameters(params, info), noTypeCheck);
ContainerUtil.addIfNotNull(chainedEtc, slowContinuation);
}
addExpectedTypeMembers(params, mergedInfos, true, noTypeCheck);
PsiElement parent = params.getPosition().getParent();
if (parent instanceof PsiReferenceExpression) {
CollectConversion.addCollectConversion((PsiReferenceExpression)parent, mergedInfos, noTypeCheck);
}
for (final ExpectedTypeInfo info : mergedInfos) {
BasicExpressionCompletionContributor.fillCompletionVariants(new JavaSmartCompletionParameters(params, info), new Consumer<LookupElement>() {
@Override
public void consume(LookupElement lookupElement) {
final TypedLookupItem typed = lookupElement.as(TypedLookupItem.CLASS_CONDITION_KEY);
if (typed != null) {
final PsiType psiType = typed.getType();
if (psiType != null && info.getType().isAssignableFrom(psiType)) {
result.addElement(decorate(lookupElement, _infos));
}
}
}
}, result.getPrefixMatcher());
}
for (Runnable runnable : chainedEtc) {
runnable.run();
}
final boolean searchInheritors = params.getInvocationCount() > 1;
if (searchInheritors) {
addExpectedTypeMembers(params, mergedInfos, false, noTypeCheck);
}
}
});
extend(CompletionType.SMART, or(
PsiJavaPatterns.psiElement().withParent(PsiNameValuePair.class),
PsiJavaPatterns.psiElement().withSuperParent(2, PsiNameValuePair.class)), new CompletionProvider<CompletionParameters>() {
@Override
public void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext context, @NotNull final CompletionResultSet result) {
final PsiElement element = parameters.getPosition();
for (final PsiType type : ExpectedTypesGetter.getExpectedTypes(element, false)) {
final PsiClass psiClass = PsiUtil.resolveClassInType(type);
if (psiClass != null && psiClass.isAnnotationType()) {
result.addElement(AllClassesGetter.createLookupItem(psiClass, AnnotationInsertHandler.INSTANCE));
}
}
}
});
extend(CompletionType.SMART, psiElement().inside(
psiElement(PsiDocTag.class).withName(
string().oneOf(PsiKeyword.THROWS, EXCEPTION_TAG))), new CompletionProvider<CompletionParameters>() {
@Override
public void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext context, @NotNull final CompletionResultSet result) {
final PsiElement element = parameters.getPosition();
final Set<PsiClass> throwsSet = new HashSet<PsiClass>();
final PsiMethod method = PsiTreeUtil.getContextOfType(element, PsiMethod.class, true);
if(method != null){
for (PsiClassType ref : method.getThrowsList().getReferencedTypes()) {
final PsiClass exception = ref.resolve();
if (exception != null && throwsSet.add(exception)) {
result.addElement(TailTypeDecorator.withTail(new JavaPsiClassReferenceElement(exception), TailType.HUMBLE_SPACE_BEFORE_WORD));
}
}
}
}
});
final Key<PsiTryStatement> tryKey = Key.create("try");
extend(CompletionType.SMART, psiElement().insideStarting(
psiElement(PsiTypeElement.class).withParent(
psiElement(PsiCatchSection.class).withParent(
psiElement(PsiTryStatement.class).save(tryKey)))), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull final CompletionParameters parameters, final ProcessingContext context, @NotNull final CompletionResultSet result) {
final PsiCodeBlock tryBlock = context.get(tryKey).getTryBlock();
if (tryBlock == null) return;
final InheritorsHolder holder = new InheritorsHolder(result);
for (final PsiClassType type : ExceptionUtil.getThrownExceptions(tryBlock.getStatements())) {
PsiClass typeClass = type.resolve();
if (typeClass != null) {
result.addElement(createCatchTypeVariant(tryBlock, type));
holder.registerClass(typeClass);
}
}
final Collection<PsiClassType> expectedClassTypes = ContainerUtil.createMaybeSingletonList(JavaPsiFacade.getElementFactory(
tryBlock.getProject()).createTypeByFQClassName(CommonClassNames.JAVA_LANG_THROWABLE));
JavaInheritorsGetter.processInheritors(parameters, expectedClassTypes, result.getPrefixMatcher(), new Consumer<PsiType>() {
@Override
public void consume(PsiType type) {
final PsiClass psiClass = type instanceof PsiClassType ? ((PsiClassType)type).resolve() : null;
if (psiClass == null || psiClass instanceof PsiTypeParameter) return;
if (!holder.alreadyProcessed(psiClass)) {
result.addElement(createCatchTypeVariant(tryBlock, (PsiClassType)type));
}
}
});
}
@NotNull
private LookupElement createCatchTypeVariant(PsiCodeBlock tryBlock, PsiClassType type) {
return TailTypeDecorator.withTail(PsiTypeLookupItem.createLookupItem(type, tryBlock).setInsertHandler(new DefaultInsertHandler()),
TailType.HUMBLE_SPACE_BEFORE_WORD);
}
});
extend(CompletionType.SMART, IN_TYPE_ARGS, new TypeArgumentCompletionProvider(true, null));
extend(CompletionType.SMART, AFTER_NEW, new JavaInheritorsGetter(ConstructorInsertHandler.SMART_INSTANCE));
extend(CompletionType.SMART, psiElement().afterLeaf(PsiKeyword.BREAK, PsiKeyword.CONTINUE), new CompletionProvider<CompletionParameters>() {
@Override
protected void addCompletions(@NotNull CompletionParameters parameters,
ProcessingContext context,
@NotNull CompletionResultSet result) {
PsiReference ref = parameters.getPosition().getContainingFile().findReferenceAt(parameters.getOffset());
if (ref instanceof PsiLabelReference) {
JavaCompletionContributor.processLabelReference(result, (PsiLabelReference)ref);
}
}
});
extend(CompletionType.SMART, LAMBDA, new FunctionalExpressionCompletionProvider());
extend(CompletionType.SMART, METHOD_REFERENCE, new MethodReferenceCompletionProvider());
}
@NotNull
static Consumer<LookupElement> decorateWithoutTypeCheck(final CompletionResultSet result, final Collection<ExpectedTypeInfo> infos) {
return new Consumer<LookupElement>() {
@Override
public void consume(final LookupElement lookupElement) {
result.addElement(decorate(lookupElement, infos));
}
};
}
private static void addExpectedTypeMembers(CompletionParameters params,
THashSet<ExpectedTypeInfo> mergedInfos,
boolean quick,
Consumer<LookupElement> consumer) {
PsiElement position = params.getPosition();
if (!JavaKeywordCompletion.AFTER_DOT.accepts(position)) {
for (ExpectedTypeInfo info : mergedInfos) {
new JavaMembersGetter(info.getType(), params).addMembers(!quick, consumer);
if (!info.getDefaultType().equals(info.getType())) {
new JavaMembersGetter(info.getDefaultType(), params).addMembers(!quick, consumer);
}
}
}
}
@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
super.fillCompletionVariants(parameters, JavaCompletionSorting.addJavaSorting(parameters, result));
}
public static SmartCompletionDecorator decorate(LookupElement lookupElement, Collection<ExpectedTypeInfo> infos) {
LookupItem item = lookupElement.as(LookupItem.CLASS_CONDITION_KEY);
if (item != null && item.getInsertHandler() == null) {
item.setInsertHandler(DefaultInsertHandler.NO_TAIL_HANDLER);
}
return new SmartCompletionDecorator(lookupElement, infos);
}
private static LookupElement createInstanceofLookupElement(PsiClass psiClass, Set<PsiClass> toWildcardInheritors) {
final PsiTypeParameter[] typeParameters = psiClass.getTypeParameters();
if (typeParameters.length > 0) {
for (final PsiClass parameterizedType : toWildcardInheritors) {
if (psiClass.isInheritor(parameterizedType, true)) {
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
final PsiWildcardType wildcard = PsiWildcardType.createUnbounded(psiClass.getManager());
for (final PsiTypeParameter typeParameter : typeParameters) {
substitutor = substitutor.put(typeParameter, wildcard);
}
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject());
return PsiTypeLookupItem.createLookupItem(factory.createType(psiClass, substitutor), psiClass);
}
}
}
return new JavaPsiClassReferenceElement(psiClass);
}
@NotNull
public static ExpectedTypeInfo[] getExpectedTypes(final CompletionParameters parameters) {
return getExpectedTypes(parameters, parameters.getCompletionType() == CompletionType.SMART);
}
@NotNull
public static ExpectedTypeInfo[] getExpectedTypes(final CompletionParameters parameters, boolean voidable) {
final PsiElement position = parameters.getPosition();
if (psiElement().withParent(psiElement(PsiReferenceExpression.class).withParent(PsiThrowStatement.class)).accepts(position)) {
final PsiElementFactory factory = JavaPsiFacade.getInstance(position.getProject()).getElementFactory();
final PsiClassType classType = factory
.createTypeByFQClassName(CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION, position.getResolveScope());
final List<ExpectedTypeInfo> result = new SmartList<ExpectedTypeInfo>();
result.add(new ExpectedTypeInfoImpl(classType, ExpectedTypeInfo.TYPE_OR_SUBTYPE, classType, TailType.SEMICOLON, null, ExpectedTypeInfoImpl.NULL));
final PsiMethod method = PsiTreeUtil.getContextOfType(position, PsiMethod.class, true);
if (method != null) {
for (final PsiClassType type : method.getThrowsList().getReferencedTypes()) {
result.add(new ExpectedTypeInfoImpl(type, ExpectedTypeInfo.TYPE_OR_SUBTYPE, type, TailType.SEMICOLON, null, ExpectedTypeInfoImpl.NULL));
}
}
return result.toArray(new ExpectedTypeInfo[result.size()]);
}
PsiExpression expression = PsiTreeUtil.getContextOfType(position, PsiExpression.class, true);
if (expression == null) return ExpectedTypeInfo.EMPTY_ARRAY;
return ExpectedTypesProvider.getExpectedTypes(expression, true, voidable, false);
}
static Set<LookupElement> completeReference(final PsiElement element,
PsiReference reference,
final ElementFilter filter,
final boolean acceptClasses,
final boolean acceptMembers,
CompletionParameters parameters, final PrefixMatcher matcher) {
if (reference instanceof PsiMultiReference) {
reference = ContainerUtil.findInstance(((PsiMultiReference) reference).getReferences(), PsiJavaReference.class);
}
if (reference instanceof PsiJavaReference) {
final PsiJavaReference javaReference = (PsiJavaReference)reference;
ElementFilter checkClass = new ElementFilter() {
@Override
public boolean isAcceptable(Object element, PsiElement context) {
return filter.isAcceptable(element, context);
}
@Override
public boolean isClassAcceptable(Class hintClass) {
if (ReflectionUtil.isAssignable(PsiClass.class, hintClass)) {
return acceptClasses;
}
if (ReflectionUtil.isAssignable(PsiVariable.class, hintClass) ||
ReflectionUtil.isAssignable(PsiMethod.class, hintClass) ||
ReflectionUtil.isAssignable(CandidateInfo.class, hintClass)) {
return acceptMembers;
}
return false;
}
};
JavaCompletionProcessor.Options options =
JavaCompletionProcessor.Options.DEFAULT_OPTIONS.withFilterStaticAfterInstance(parameters.getInvocationCount() <= 1);
return JavaCompletionUtil.processJavaReference(element, javaReference, checkClass, options, matcher, parameters);
}
return Collections.emptySet();
}
@Override
public void beforeCompletion(@NotNull CompletionInitializationContext context) {
if (context.getCompletionType() != CompletionType.SMART) {
return;
}
if (!context.getEditor().getSelectionModel().hasSelection()) {
final PsiFile file = context.getFile();
PsiElement element = file.findElementAt(context.getStartOffset());
if (element instanceof PsiIdentifier) {
element = element.getParent();
while (element instanceof PsiJavaCodeReferenceElement || element instanceof PsiCall ||
element instanceof PsiThisExpression || element instanceof PsiSuperExpression ||
element instanceof PsiTypeElement ||
element instanceof PsiClassObjectAccessExpression) {
int newEnd = element.getTextRange().getEndOffset();
if (element instanceof PsiMethodCallExpression) {
newEnd = ((PsiMethodCallExpression)element).getMethodExpression().getTextRange().getEndOffset();
}
else if (element instanceof PsiNewExpression) {
final PsiJavaCodeReferenceElement classReference = ((PsiNewExpression)element).getClassReference();
if (classReference != null) {
newEnd = classReference.getTextRange().getEndOffset();
}
}
context.setReplacementOffset(newEnd);
element = element.getParent();
}
}
}
PsiElement lastElement = context.getFile().findElementAt(context.getStartOffset() - 1);
if (lastElement != null && lastElement.getText().equals("(") && lastElement.getParent() instanceof PsiParenthesizedExpression) {
// don't trim dummy identifier or we won't be able to determine the type of the expression after '('
// which is needed to insert correct cast
return;
}
context.setDummyIdentifier(CompletionUtil.DUMMY_IDENTIFIER_TRIMMED);
}
}
| |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.pricing;
import javax.annotation.Generated;
import com.amazonaws.services.pricing.model.*;
import com.amazonaws.client.AwsAsyncClientParams;
import com.amazonaws.annotation.ThreadSafe;
import java.util.concurrent.ExecutorService;
/**
* Client for accessing AWS Pricing asynchronously. Each asynchronous method will return a Java Future object
* representing the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive
* notification when an asynchronous operation completes.
* <p>
* <p>
* AWS Price List Service API (AWS Price List Service) is a centralized and convenient way to programmatically query
* Amazon Web Services for services, products, and pricing information. The AWS Price List Service uses standardized
* product attributes such as <code>Location</code>, <code>Storage Class</code>, and <code>Operating System</code>, and
* provides prices at the SKU level. You can use the AWS Price List Service to build cost control and scenario planning
* tools, reconcile billing data, forecast future spend for budgeting purposes, and provide cost benefit analysis that
* compare your internal workloads with AWS.
* </p>
* <p>
* Use <code>GetServices</code> without a service code to retrieve the service codes for all AWS services, then
* <code>GetServices</code> with a service code to retreive the attribute names for that service. After you have the
* service code and attribute names, you can use <code>GetAttributeValues</code> to see what values are available for an
* attribute. With the service code and an attribute name and value, you can use <code>GetProducts</code> to find
* specific products that you're interested in, such as an <code>AmazonEC2</code> instance, with a
* <code>Provisioned IOPS</code> <code>volumeType</code>.
* </p>
* <p>
* Service Endpoint
* </p>
* <p>
* AWS Price List Service API provides the following two endpoints:
* </p>
* <ul>
* <li>
* <p>
* https://api.pricing.us-east-1.amazonaws.com
* </p>
* </li>
* <li>
* <p>
* https://api.pricing.ap-south-1.amazonaws.com
* </p>
* </li>
* </ul>
*/
@ThreadSafe
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AWSPricingAsyncClient extends AWSPricingClient implements AWSPricingAsync {
private static final int DEFAULT_THREAD_POOL_SIZE = 50;
private final java.util.concurrent.ExecutorService executorService;
public static AWSPricingAsyncClientBuilder asyncBuilder() {
return AWSPricingAsyncClientBuilder.standard();
}
/**
* Constructs a new asynchronous client to invoke service methods on AWS Pricing using the specified parameters.
*
* @param asyncClientParams
* Object providing client parameters.
*/
AWSPricingAsyncClient(AwsAsyncClientParams asyncClientParams) {
super(asyncClientParams);
this.executorService = asyncClientParams.getExecutor();
}
/**
* Returns the executor service used by this client to execute async requests.
*
* @return The executor service used by this client to execute async requests.
*/
public ExecutorService getExecutorService() {
return executorService;
}
@Override
public java.util.concurrent.Future<DescribeServicesResult> describeServicesAsync(DescribeServicesRequest request) {
return describeServicesAsync(request, null);
}
@Override
public java.util.concurrent.Future<DescribeServicesResult> describeServicesAsync(final DescribeServicesRequest request,
final com.amazonaws.handlers.AsyncHandler<DescribeServicesRequest, DescribeServicesResult> asyncHandler) {
final DescribeServicesRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<DescribeServicesResult>() {
@Override
public DescribeServicesResult call() throws Exception {
DescribeServicesResult result = null;
try {
result = executeDescribeServices(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetAttributeValuesResult> getAttributeValuesAsync(GetAttributeValuesRequest request) {
return getAttributeValuesAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetAttributeValuesResult> getAttributeValuesAsync(final GetAttributeValuesRequest request,
final com.amazonaws.handlers.AsyncHandler<GetAttributeValuesRequest, GetAttributeValuesResult> asyncHandler) {
final GetAttributeValuesRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetAttributeValuesResult>() {
@Override
public GetAttributeValuesResult call() throws Exception {
GetAttributeValuesResult result = null;
try {
result = executeGetAttributeValues(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
@Override
public java.util.concurrent.Future<GetProductsResult> getProductsAsync(GetProductsRequest request) {
return getProductsAsync(request, null);
}
@Override
public java.util.concurrent.Future<GetProductsResult> getProductsAsync(final GetProductsRequest request,
final com.amazonaws.handlers.AsyncHandler<GetProductsRequest, GetProductsResult> asyncHandler) {
final GetProductsRequest finalRequest = beforeClientExecution(request);
return executorService.submit(new java.util.concurrent.Callable<GetProductsResult>() {
@Override
public GetProductsResult call() throws Exception {
GetProductsResult result = null;
try {
result = executeGetProducts(finalRequest);
} catch (Exception ex) {
if (asyncHandler != null) {
asyncHandler.onError(ex);
}
throw ex;
}
if (asyncHandler != null) {
asyncHandler.onSuccess(finalRequest, result);
}
return result;
}
});
}
/**
* Shuts down the client, releasing all managed resources. This includes forcibly terminating all pending
* asynchronous service calls. Clients who wish to give pending asynchronous service calls time to complete should
* call {@code getExecutorService().shutdown()} followed by {@code getExecutorService().awaitTermination()} prior to
* calling this method.
*/
@Override
public void shutdown() {
super.shutdown();
executorService.shutdownNow();
}
}
| |
/*===============================================================================
Copyright (c) 2016 PTC Inc. All Rights Reserved.
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of PTC Inc., registered in the United States and other
countries.
===============================================================================*/
package com.vuforia.samples.VuforiaSamples.app.CylinderTargets;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;
import com.vuforia.CylinderTargetResult;
import com.vuforia.Device;
import com.vuforia.Matrix44F;
import com.vuforia.Renderer;
import com.vuforia.State;
import com.vuforia.Tool;
import com.vuforia.TrackableResult;
import com.vuforia.Vuforia;
import com.vuforia.samples.SampleApplication.SampleAppRenderer;
import com.vuforia.samples.SampleApplication.SampleAppRendererControl;
import com.vuforia.samples.SampleApplication.SampleApplicationSession;
import com.vuforia.samples.SampleApplication.utils.CubeShaders;
import com.vuforia.samples.SampleApplication.utils.LoadingDialogHandler;
import com.vuforia.samples.SampleApplication.utils.SampleApplication3DModel;
import com.vuforia.samples.SampleApplication.utils.SampleUtils;
import com.vuforia.samples.SampleApplication.utils.Texture;
// The renderer class for the ImageTargets sample.
public class CylinderTargetRenderer implements GLSurfaceView.Renderer, SampleAppRendererControl
{
private static final String LOGTAG = "CylinderTargetRenderer";
// Reference to main activity
private CylinderTargets mActivity;
private SampleApplicationSession vuforiaAppSession;
private SampleAppRenderer mSampleAppRenderer;
private Vector<Texture> mTextures;
private int shaderProgramID;
private int vertexHandle;
private int textureCoordHandle;
private int mvpMatrixHandle;
private int texSampler2DHandle;
private Renderer mRenderer;
private CylinderModel mCylinderModel;
// dimensions of the cylinder (as set in the TMS tool)
private float kCylinderHeight = 95.0f;
private float kCylinderTopDiameter = 65.0f;
private float kCylinderBottomDiameter = 65.0f;
// ratio between top and bottom diameter
// used to generate the model of the cylinder
private float kCylinderTopRadiusRatio = kCylinderTopDiameter
/ kCylinderBottomDiameter;
// the height of the tea pot
private float kObjectHeight = 1.0f;
// we want the object to be the 1/3 of the height of the cylinder
private float kRatioCylinderObjectHeight = 3.0f;
// Scaling of the object to match the ratio we want
private float kObjectScale = kCylinderHeight
/ (kRatioCylinderObjectHeight * kObjectHeight);
// scaling of the cylinder model to fit the actual cylinder
private float kCylinderScaleX = kCylinderBottomDiameter / 2.0f;
private float kCylinderScaleY = kCylinderBottomDiameter / 2.0f;
private float kCylinderScaleZ = kCylinderHeight;
private SampleApplication3DModel mSphereModel;
private double prevTime;
private float rotateBallAngle;
private boolean mIsActive = false;
private boolean mModelIsLoaded = false;
public CylinderTargetRenderer(CylinderTargets activity,
SampleApplicationSession session)
{
mActivity = activity;
vuforiaAppSession = session;
// SampleAppRenderer used to encapsulate the use of RenderingPrimitives setting
// the device mode AR/VR and stereo mode
mSampleAppRenderer = new SampleAppRenderer(this, mActivity, Device.MODE.MODE_AR, false, 10f, 5000f);
}
// Called when the surface is created or recreated.
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
Log.d(LOGTAG, "GLRenderer.onSurfaceCreated");
// Call Vuforia function to (re)initialize rendering after first use
// or after OpenGL ES context was lost (e.g. after onPause/onResume):
vuforiaAppSession.onSurfaceCreated();
mSampleAppRenderer.onSurfaceCreated();
}
// Called when the surface changed size.
public void onSurfaceChanged(GL10 gl, int width, int height)
{
Log.d(LOGTAG, "GLRenderer.onSurfaceChanged");
// Call Vuforia function to handle render surface size changes:
vuforiaAppSession.onSurfaceChanged(width, height);
// RenderingPrimitives to be updated when some rendering change is done
mSampleAppRenderer.onConfigurationChanged(mIsActive);
// Call function to initialize rendering:
initRendering();
}
// Called to draw the current frame.
@Override
public void onDrawFrame(GL10 gl)
{
if (!mIsActive)
return;
// Call our function to render content from SampleAppRenderer class
mSampleAppRenderer.render();
}
public void setActive(boolean active)
{
mIsActive = active;
if(mIsActive)
mSampleAppRenderer.configureVideoBackground();
}
private void initRendering()
{
// Define clear color
GLES20.glClearColor(0.0f, 0.0f, 0.0f, Vuforia.requiresAlpha() ? 0.0f
: 1.0f);
mRenderer = Renderer.getInstance();
// Now generate the OpenGL texture objects and add settings
for (Texture t : mTextures)
{
GLES20.glGenTextures(1, t.mTextureID, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t.mTextureID[0]);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA,
t.mWidth, t.mHeight, 0, GLES20.GL_RGBA,
GLES20.GL_UNSIGNED_BYTE, t.mData);
}
SampleUtils.checkGLError("CylinderTargets GLInitRendering");
shaderProgramID = SampleUtils.createProgramFromShaderSrc(
CubeShaders.CUBE_MESH_VERTEX_SHADER,
CubeShaders.CUBE_MESH_FRAGMENT_SHADER);
SampleUtils.checkGLError("GLInitRendering");
vertexHandle = GLES20.glGetAttribLocation(shaderProgramID,
"vertexPosition");
textureCoordHandle = GLES20.glGetAttribLocation(shaderProgramID,
"vertexTexCoord");
mvpMatrixHandle = GLES20.glGetUniformLocation(shaderProgramID,
"modelViewProjectionMatrix");
texSampler2DHandle = GLES20.glGetUniformLocation(shaderProgramID,
"texSampler2D");
SampleUtils.checkGLError("GLInitRendering due");
SampleUtils
.checkGLError("CylinderTargets GLInitRendering getting location att and unif");
if(!mModelIsLoaded) {
try {
mSphereModel = new SampleApplication3DModel();
mSphereModel.loadModel(mActivity.getResources().getAssets(),
"CylinderTargets/Sphere.txt");
mModelIsLoaded = true;
} catch (IOException e) {
Log.e(LOGTAG, "Unable to load soccer ball");
}
prevTime = System.currentTimeMillis();
rotateBallAngle = 0;
mCylinderModel = new CylinderModel(kCylinderTopRadiusRatio);
// Hide the Loading Dialog
mActivity.loadingDialogHandler
.sendEmptyMessage(LoadingDialogHandler.HIDE_LOADING_DIALOG);
}
}
// The render function called from SampleAppRendering by using RenderingPrimitives views.
// The state is owned by SampleAppRenderer which is controlling it's lifecycle.
// State should not be cached outside this method.
public void renderFrame(State state, float[] projectionMatrix)
{
// Renders video background replacing Renderer.DrawVideoBackground()
mSampleAppRenderer.renderVideoBackground();
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
SampleUtils.checkGLError("CylinderTargets drawVideoBackground");
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glCullFace(GLES20.GL_BACK);
// did we find any trackables this frame?
for (int tIdx = 0; tIdx < state.getNumTrackableResults(); tIdx++)
{
TrackableResult result = state.getTrackableResult(tIdx);
if (!result.isOfType(CylinderTargetResult.getClassType()))
continue;
Matrix44F modelViewMatrix_Vuforia;
float[] modelViewProjection = new float[16];
// prepare the cylinder
modelViewMatrix_Vuforia = Tool.convertPose2GLMatrix(result
.getPose());
float[] modelViewMatrix = modelViewMatrix_Vuforia.getData();
Matrix.scaleM(modelViewMatrix, 0, kCylinderScaleX, kCylinderScaleY,
kCylinderScaleZ);
Matrix.multiplyMM(modelViewProjection, 0, projectionMatrix, 0, modelViewMatrix, 0);
SampleUtils.checkGLError("CylinderTargets prepareCylinder");
GLES20.glUseProgram(shaderProgramID);
// Draw the cylinder:
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glCullFace(GLES20.GL_BACK);
GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT,
false, 0, mCylinderModel.getVertices());
GLES20.glVertexAttribPointer(textureCoordHandle, 2,
GLES20.GL_FLOAT, false, 0, mCylinderModel.getTexCoords());
GLES20.glEnableVertexAttribArray(vertexHandle);
GLES20.glEnableVertexAttribArray(textureCoordHandle);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,
mTextures.get(0).mTextureID[0]);
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false,
modelViewProjection, 0);
GLES20.glUniform1i(texSampler2DHandle, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
mCylinderModel.getNumObjectIndex(), GLES20.GL_UNSIGNED_SHORT,
mCylinderModel.getIndices());
GLES20.glDisable(GLES20.GL_CULL_FACE);
SampleUtils.checkGLError("CylinderTargets drawCylinder");
// prepare the object
modelViewMatrix = Tool.convertPose2GLMatrix(result.getPose())
.getData();
// draw the anchored object
animateObject(modelViewMatrix);
// we move away the object from the target
Matrix.translateM(modelViewMatrix, 0, 1.0f * kCylinderTopDiameter,
0.0f, kObjectScale);
Matrix.scaleM(modelViewMatrix, 0, kObjectScale, kObjectScale,
kObjectScale);
Matrix.multiplyMM(modelViewProjection, 0, projectionMatrix, 0, modelViewMatrix, 0);
GLES20.glUseProgram(shaderProgramID);
GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT,
false, 0, mSphereModel.getVertices());
GLES20.glVertexAttribPointer(textureCoordHandle, 2,
GLES20.GL_FLOAT, false, 0, mSphereModel.getTexCoords());
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,
mTextures.get(1).mTextureID[0]);
GLES20.glUniform1i(texSampler2DHandle, 0);
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false,
modelViewProjection, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0,
mSphereModel.getNumObjectVertex());
GLES20.glDisableVertexAttribArray(vertexHandle);
GLES20.glDisableVertexAttribArray(textureCoordHandle);
SampleUtils.checkGLError("CylinderTargets renderFrame");
}
GLES20.glDisable(GLES20.GL_BLEND);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
mRenderer.end();
}
private void animateObject(float[] modelViewMatrix)
{
double time = System.currentTimeMillis(); // Get real time difference
float dt = (float) (time - prevTime) / 1000; // from frame to frame
rotateBallAngle += dt * 180.0f / 3.1415f; // Animate angle based on time
rotateBallAngle %= 360;
Matrix.rotateM(modelViewMatrix, 0, rotateBallAngle, 0.0f, 0.0f, 1.0f);
prevTime = time;
}
public void setTextures(Vector<Texture> textures)
{
mTextures = textures;
}
}
| |
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.engine.test.bpmn.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.camunda.bpm.engine.ParseException;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;
import org.camunda.bpm.engine.impl.pvm.runtime.operation.PvmAtomicOperation;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.Job;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.TaskQuery;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.bpmn.event.error.ThrowBpmnErrorDelegate;
import org.camunda.bpm.engine.test.util.PluggableProcessEngineTest;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* @author Daniel Meyer
* @author Stefan Hentschel
*
*/
public class AsyncAfterTest extends PluggableProcessEngineTest {
@Test
public void testTransitionIdRequired() {
// if an outgoing sequence flow has no id, we cannot use it in asyncAfter
try {
repositoryService.createDeployment()
.addClasspathResource("org/camunda/bpm/engine/test/bpmn/async/AsyncAfterTest.testTransitionIdRequired.bpmn20.xml")
.deploy();
fail("Exception expected");
} catch (ParseException e) {
testRule.assertTextPresent("Sequence flow with sourceRef='service' must have an id, activity with id 'service' uses 'asyncAfter'.", e.getMessage());
assertThat(e.getResorceReports().get(0).getErrors().get(0).getElementIds()).containsExactly("service");
}
}
@Deployment
@Test
public void testAsyncAfterServiceTask() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess");
// listeners should be fired by now
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// the process should wait *after* the catch event
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// if the waiting job is executed, the process instance should end
managementService.executeJob(job.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterMultiInstanceUserTask() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("process");
List<Task> list = taskService.createTaskQuery().list();
// multiinstance says three in the bpmn
assertThat(list).hasSize(3);
for (Task task : list) {
taskService.complete(task.getId());
}
testRule.waitForJobExecutorToProcessAllJobs(TimeUnit.MILLISECONDS.convert(5L, TimeUnit.SECONDS));
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterAndBeforeServiceTask() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess");
// the service task is not yet invoked
assertNotListenerStartInvoked(pi);
assertNotBehaviorInvoked(pi);
assertNotListenerEndInvoked(pi);
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// if the job is executed
managementService.executeJob(job.getId());
// the manual task is invoked
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// and now the process is waiting *after* the manual task
job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// after executing the waiting job, the process instance will end
managementService.executeJob(job.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterServiceTaskMultipleTransitions() {
// start process instance
Map<String, Object> varMap = new HashMap<String, Object>();
varMap.put("flowToTake", "flow2");
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", varMap);
// the service task is completely invoked
assertListenerStartInvoked(pi);
assertBehaviorInvoked(pi);
assertListenerEndInvoked(pi);
// and the execution is waiting *after* the service task
Job continuationJob = managementService.createJobQuery().singleResult();
assertNotNull(continuationJob);
// if we execute the job, the process instance continues along the selected path
managementService.executeJob(continuationJob.getId());
assertNotNull(runtimeService.createExecutionQuery().activityId("taskAfterFlow2").singleResult());
assertNull(runtimeService.createExecutionQuery().activityId("taskAfterFlow3").singleResult());
// end the process
runtimeService.signal(pi.getId());
//////////////////////////////////////////////////////////////
// start process instance
varMap = new HashMap<String, Object>();
varMap.put("flowToTake", "flow3");
pi = runtimeService.startProcessInstanceByKey("testProcess", varMap);
// the service task is completely invoked
assertListenerStartInvoked(pi);
assertBehaviorInvoked(pi);
assertListenerEndInvoked(pi);
// and the execution is waiting *after* the service task
continuationJob = managementService.createJobQuery().singleResult();
assertNotNull(continuationJob);
// if we execute the job, the process instance continues along the selected path
managementService.executeJob(continuationJob.getId());
assertNull(runtimeService.createExecutionQuery().activityId("taskAfterFlow2").singleResult());
assertNotNull(runtimeService.createExecutionQuery().activityId("taskAfterFlow3").singleResult());
}
@Deployment
@Test
public void testAsyncAfterServiceTaskMultipleTransitionsConcurrent() {
// start process instance
Map<String, Object> varMap = new HashMap<String, Object>();
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", varMap);
// the service task is completely invoked
assertListenerStartInvoked(pi);
assertBehaviorInvoked(pi);
assertListenerEndInvoked(pi);
// there are two async jobs
List<Job> jobs = managementService.createJobQuery().list();
assertEquals(2, jobs.size());
managementService.executeJob(jobs.get(0).getId());
managementService.executeJob(jobs.get(1).getId());
// both subsequent tasks are activated
assertNotNull(runtimeService.createExecutionQuery().activityId("taskAfterFlow2").singleResult());
assertNotNull(runtimeService.createExecutionQuery().activityId("taskAfterFlow3").singleResult());
}
@Deployment
@Test
public void testAsyncAfterWithoutTransition() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess");
// the service task is completely invoked
assertListenerStartInvoked(pi);
assertBehaviorInvoked(pi);
assertListenerEndInvoked(pi);
// and the execution is waiting *after* the service task
Job continuationJob = managementService.createJobQuery().singleResult();
assertNotNull(continuationJob);
// but the process end listeners have not been invoked yet
assertNull(runtimeService.getVariable(pi.getId(), "process-listenerEndInvoked"));
// if we execute the job, the process instance ends.
managementService.executeJob(continuationJob.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterInNestedWithoutTransition() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess");
// the service task is completely invoked
assertListenerStartInvoked(pi);
assertBehaviorInvoked(pi);
assertListenerEndInvoked(pi);
// and the execution is waiting *after* the service task
Job continuationJob = managementService.createJobQuery().singleResult();
assertNotNull(continuationJob);
// but the subprocess end listeners have not been invoked yet
assertNull(runtimeService.getVariable(pi.getId(), "subprocess-listenerEndInvoked"));
// if we execute the job, the listeners are invoked;
managementService.executeJob(continuationJob.getId());
assertTrue((Boolean)runtimeService.getVariable(pi.getId(), "subprocess-listenerEndInvoked"));
}
@Deployment
@Test
public void testAsyncAfterManualTask() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testManualTask");
// listeners should be fired by now
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// the process should wait *after* the catch event
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// if the waiting job is executed, the process instance should end
managementService.executeJob(job.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterAndBeforeManualTask() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testManualTask");
// the service task is not yet invoked
assertNotListenerStartInvoked(pi);
assertNotListenerEndInvoked(pi);
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// if the job is executed
managementService.executeJob(job.getId());
// the manual task is invoked
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// and now the process is waiting *after* the manual task
job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// after executing the waiting job, the process instance will end
managementService.executeJob(job.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterIntermediateCatchEvent() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testIntermediateCatchEvent");
// the intermediate catch event is waiting for its message
runtimeService.correlateMessage("testMessage1");
// listeners should be fired by now
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// the process should wait *after* the catch event
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// if the waiting job is executed, the process instance should end
managementService.executeJob(job.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterAndBeforeIntermediateCatchEvent() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testIntermediateCatchEvent");
// check that no listener is invoked by now
assertNotListenerStartInvoked(pi);
assertNotListenerEndInvoked(pi);
// the process is waiting before the message event
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// execute job to get to the message event
testRule.executeAvailableJobs();
// now we need to trigger the message to proceed
runtimeService.correlateMessage("testMessage1");
// now the listener should be invoked
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// and now the process is waiting *after* the intermediate catch event
job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// after executing the waiting job, the process instance will end
managementService.executeJob(job.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterIntermediateThrowEvent() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testIntermediateThrowEvent");
// listeners should be fired by now
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// the process should wait *after* the throw event
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// if the waiting job is executed, the process instance should end
managementService.executeJob(job.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterAndBeforeIntermediateThrowEvent() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testIntermediateThrowEvent");
// the throw event is not yet invoked
assertNotListenerStartInvoked(pi);
assertNotListenerEndInvoked(pi);
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// if the job is executed
managementService.executeJob(job.getId());
// the listeners are invoked
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// and now the process is waiting *after* the throw event
job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// after executing the waiting job, the process instance will end
managementService.executeJob(job.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterInclusiveGateway() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testInclusiveGateway");
// listeners should be fired
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// the process should wait *after* the gateway
assertEquals(2, managementService.createJobQuery().active().count());
testRule.executeAvailableJobs();
// if the waiting job is executed there should be 2 user tasks
TaskQuery taskQuery = taskService.createTaskQuery();
assertEquals(2, taskQuery.active().count());
// finish tasks
List<Task> tasks = taskQuery.active().list();
for(Task task : tasks) {
taskService.complete(task.getId());
}
testRule.assertProcessEnded(pi.getProcessInstanceId());
}
@Deployment
@Test
public void testAsyncAfterAndBeforeInclusiveGateway() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testInclusiveGateway");
// no listeners are fired:
assertNotListenerStartInvoked(pi);
assertNotListenerEndInvoked(pi);
// we should wait *before* the gateway:
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// after executing the gateway:
managementService.executeJob(job.getId());
// the listeners are fired:
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// and we will wait *after* the gateway:
List<Job> jobs = managementService.createJobQuery().active().list();
assertEquals(2, jobs.size());
}
@Deployment
@Test
public void testAsyncAfterExclusiveGateway() {
// start process instance with variables
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("flow", false);
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testExclusiveGateway", variables);
// listeners should be fired
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// the process should wait *after* the gateway
assertEquals(1, managementService.createJobQuery().active().count());
testRule.executeAvailableJobs();
// if the waiting job is executed there should be 2 user tasks
TaskQuery taskQuery = taskService.createTaskQuery();
assertEquals(1, taskQuery.active().count());
// finish tasks
List<Task> tasks = taskQuery.active().list();
for(Task task : tasks) {
taskService.complete(task.getId());
}
testRule.assertProcessEnded(pi.getProcessInstanceId());
}
@Deployment
@Test
public void testAsyncAfterAndBeforeExclusiveGateway() {
// start process instance with variables
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("flow", false);
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testExclusiveGateway", variables);
// no listeners are fired:
assertNotListenerStartInvoked(pi);
assertNotListenerEndInvoked(pi);
// we should wait *before* the gateway:
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
// after executing the gateway:
managementService.executeJob(job.getId());
// the listeners are fired:
assertListenerStartInvoked(pi);
assertListenerEndInvoked(pi);
// and we will wait *after* the gateway:
assertEquals(1, managementService.createJobQuery().active().count());
}
/**
* Test for CAM-2518: Fixes an issue that creates an infinite loop when using
* asyncAfter together with an execution listener on sequence flow event "take".
* So the only required assertion here is that the process executes successfully.
*/
@Deployment
@Test
public void testAsyncAfterWithExecutionListener() {
// given an async after job and an execution listener on that task
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testProcess");
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
assertNotListenerTakeInvoked(processInstance);
// when the job is executed
managementService.executeJob(job.getId());
// then the process should advance and not recreate the job
job = managementService.createJobQuery().singleResult();
assertNull(job);
Task task = taskService.createTaskQuery().singleResult();
assertNotNull(task);
assertListenerTakeInvoked(processInstance);
}
@Deployment
@Test
public void testAsyncAfterOnParallelGatewayFork() {
String configuration = PvmAtomicOperation.TRANSITION_NOTIFY_LISTENER_TAKE.getCanonicalName();
String config1 = configuration + "$afterForkFlow1";
String config2 = configuration + "$afterForkFlow2";
runtimeService.startProcessInstanceByKey("process");
// there are two jobs
List<Job> jobs = managementService.createJobQuery().list();
assertEquals(2, jobs.size());
Job jobToExecute = fetchFirstJobByHandlerConfiguration(jobs, config1);
assertNotNull(jobToExecute);
managementService.executeJob(jobToExecute.getId());
Task task1 = taskService.createTaskQuery().taskDefinitionKey("theTask1").singleResult();
assertNotNull(task1);
// there is one left
jobs = managementService.createJobQuery().list();
assertEquals(1, jobs.size());
jobToExecute = fetchFirstJobByHandlerConfiguration(jobs, config2);
managementService.executeJob(jobToExecute.getId());
Task task2 = taskService.createTaskQuery().taskDefinitionKey("theTask2").singleResult();
assertNotNull(task2);
assertEquals(2, taskService.createTaskQuery().count());
}
@Deployment
@Test
public void testAsyncAfterParallelMultiInstanceWithServiceTask() {
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess");
// listeners and behavior should be invoked by now
assertListenerStartInvoked(pi);
assertBehaviorInvoked(pi, 5);
assertListenerEndInvoked(pi);
// the process should wait *after* execute all service tasks
testRule.executeAvailableJobs(1);
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterServiceWrappedInParallelMultiInstance(){
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess");
// listeners and behavior should be invoked by now
assertListenerStartInvoked(pi);
assertBehaviorInvoked(pi, 5);
assertListenerEndInvoked(pi);
// the process should wait *after* execute each service task wrapped in the multi-instance body
assertEquals(5L, managementService.createJobQuery().count());
// execute all jobs - one for each service task
testRule.executeAvailableJobs(5);
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Test
public void testAsyncAfterServiceWrappedInSequentialMultiInstance(){
// start process instance
ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess");
// listeners and behavior should be invoked by now
assertListenerStartInvoked(pi);
assertBehaviorInvoked(pi, 1);
assertListenerEndInvoked(pi);
// the process should wait *after* execute each service task step-by-step
assertEquals(1L, managementService.createJobQuery().count());
// execute all jobs - one for each service task wrapped in the multi-instance body
testRule.executeAvailableJobs(5);
// behavior should be invoked for each service task
assertBehaviorInvoked(pi, 5);
// the process should wait on user task after execute all service tasks
Task task = taskService.createTaskQuery().singleResult();
assertNotNull(task);
taskService.complete(task.getId());
testRule.assertProcessEnded(pi.getId());
}
@Deployment
@Ignore
@Test
public void testAsyncAfterOnParallelGatewayJoin() {
String configuration = PvmAtomicOperation.ACTIVITY_END.getCanonicalName();
runtimeService.startProcessInstanceByKey("process");
// there are three jobs
List<Job> jobs = managementService.createJobQuery().list();
assertEquals(3, jobs.size());
Job jobToExecute = fetchFirstJobByHandlerConfiguration(jobs, configuration);
assertNotNull(jobToExecute);
managementService.executeJob(jobToExecute.getId());
// there are two jobs left
jobs = managementService.createJobQuery().list();
assertEquals(2, jobs.size());
jobToExecute = fetchFirstJobByHandlerConfiguration(jobs, configuration);
managementService.executeJob(jobToExecute.getId());
// there is one job left
jobToExecute = managementService.createJobQuery().singleResult();
assertNotNull(jobToExecute);
managementService.executeJob(jobToExecute.getId());
// the process should stay in the user task
Task task = taskService.createTaskQuery().singleResult();
assertNotNull(task);
}
@Deployment
@Test
public void testAsyncAfterBoundaryEvent() {
// given process instance
runtimeService.startProcessInstanceByKey("Process");
// assume
Task task = taskService.createTaskQuery().singleResult();
assertNotNull(task);
// when we trigger the event
runtimeService.correlateMessage("foo");
// then
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
task = taskService.createTaskQuery().singleResult();
assertNull(task);
}
@Deployment
@Test
public void testAsyncBeforeBoundaryEvent() {
// given process instance
runtimeService.startProcessInstanceByKey("Process");
// assume
Task task = taskService.createTaskQuery().singleResult();
assertNotNull(task);
// when we trigger the event
runtimeService.correlateMessage("foo");
// then
Job job = managementService.createJobQuery().singleResult();
assertNotNull(job);
task = taskService.createTaskQuery().singleResult();
assertNull(task);
}
@Test
public void testAsyncAfterErrorEvent() {
// given
BpmnModelInstance instance = Bpmn.createExecutableProcess("process")
.startEvent()
.serviceTask("servTask")
.camundaClass(ThrowBpmnErrorDelegate.class)
.boundaryEvent()
.camundaAsyncAfter(true)
.camundaFailedJobRetryTimeCycle("R10/PT10S")
.errorEventDefinition()
.errorEventDefinitionDone()
.serviceTask()
.camundaClass("foo")
.endEvent()
.moveToActivity("servTask")
.endEvent().done();
testRule.deploy(instance);
runtimeService.startProcessInstanceByKey("process");
Job job = managementService.createJobQuery().singleResult();
// when job fails
try {
managementService.executeJob(job.getId());
} catch (Exception e) {
// ignore
}
// then
job = managementService.createJobQuery().singleResult();
Assert.assertEquals(9, job.getRetries());
}
protected Job fetchFirstJobByHandlerConfiguration(List<Job> jobs, String configuration) {
for (Job job : jobs) {
JobEntity jobEntity = (JobEntity) job;
String jobConfig = jobEntity.getJobHandlerConfigurationRaw();
if (configuration.equals(jobConfig)) {
return job;
}
}
return null;
}
protected void assertListenerStartInvoked(Execution e) {
assertTrue((Boolean) runtimeService.getVariable(e.getId(), "listenerStartInvoked"));
}
protected void assertListenerTakeInvoked(Execution e) {
assertTrue((Boolean) runtimeService.getVariable(e.getId(), "listenerTakeInvoked"));
}
protected void assertListenerEndInvoked(Execution e) {
assertTrue((Boolean) runtimeService.getVariable(e.getId(), "listenerEndInvoked"));
}
protected void assertBehaviorInvoked(Execution e) {
assertTrue((Boolean) runtimeService.getVariable(e.getId(), "behaviorInvoked"));
}
private void assertBehaviorInvoked(ProcessInstance pi, int times) {
Long behaviorInvoked = (Long) runtimeService.getVariable(pi.getId(), "behaviorInvoked");
assertNotNull("behavior was not invoked", behaviorInvoked);
assertEquals(times , behaviorInvoked.intValue());
}
protected void assertNotListenerStartInvoked(Execution e) {
assertNull(runtimeService.getVariable(e.getId(), "listenerStartInvoked"));
}
protected void assertNotListenerTakeInvoked(Execution e) {
assertNull(runtimeService.getVariable(e.getId(), "listenerTakeInvoked"));
}
protected void assertNotListenerEndInvoked(Execution e) {
assertNull(runtimeService.getVariable(e.getId(), "listenerEndInvoked"));
}
protected void assertNotBehaviorInvoked(Execution e) {
assertNull(runtimeService.getVariable(e.getId(), "behaviorInvoked"));
}
}
| |
/*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.struct.image;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Array;
/**
* <p>
* Multi-band image composed of discontinuous planar images for each band. The bands are discontinuous in that
* each one is an independent memory and are of type {@link ImageGray}. Planar images fully supports all
* functions inside of {@link ImageBase}. Each internal image has the same width, height, startIndex, and stride.
* </p>
*
* <p>
* For example, in a RGB image there would be three bands one for each color,
* and each color would be stored in its own gray scale image. To access the image for a particular
* band call {@link #getBand(int)}. To get the RGB value for a pixel (x,y) one would need to:
* <pre>
* int red = image.getBand(0).get(x,y);
* int green = image.getBand(1).get(x,y);
* int blue = image.getBand(2).get(x,y);
* </pre>
* Setting the RGB value of pixel (x,y) is done in a similar manner:
* <pre>
* image.getBand(0).set(x,y,red);
* image.getBand(1).set(x,y,green);
* image.getBand(2).set(x,y,blue);
* </pre>
* </p>
*
* <p>
* May image processing operations can be run independently on each color band. This is useful since many
* operations have been written for {@link ImageGray}, but not Planar yet.
* <pre>
* for( int i = 0; i < image.numBands(); i++ ) {
* SomeGrayImageFilter.process( image.getBand(0) );
* }
* </pre>
* </p>
*
* @author Peter Abeles
*/
public class Planar<T extends ImageGray<T>> extends ImageMultiBand<Planar<T>>{
/**
* Type of image in each band
*/
public Class<T> type;
/**
* Set of gray scale images
*/
public T[] bands;
/**
* Creates a Planar image with the specified properties.
*
* @param type The type of image which each band is stored as.
* @param width Width of the image.
* @param height Height of the image.
* @param numBands Total number of bands.
*/
public Planar(Class<T> type, int width, int height, int numBands) {
this.type = type;
this.stride = width;
this.width = width;
this.height = height;
this.bands = (T[]) Array.newInstance(type, numBands);
for (int i = 0; i < numBands; i++) {
bands[i] = ImageGray.create(type, width, height);
}
this.imageType = ImageType.pl(numBands,type);
}
/**
* Declares internal arrays for storing each band, but not the images in each band.
*
* @param type The type of image which each band is stored as.
* @param numBands Number of bands in the image.
*/
public Planar(Class<T> type, int numBands) {
this.type = type;
this.bands = (T[]) Array.newInstance(type, numBands);
this.imageType = ImageType.pl(numBands,type);
}
/**
* Type of image each band is stored as.
*
* @return The type of ImageGray which each band is stored as.
*/
public Class<T> getBandType() {
return type;
}
/**
* Returns the number of bands or colors stored in this image.
*
* @return Number of bands in the image.
*/
@Override
public int getNumBands() {
return bands.length;
}
/**
* Returns a band in the multi-band image.
*
* @param band Which band should be returned.
* @return Image band
*/
public T getBand(int band) {
if (band >= bands.length || band < 0)
throw new IllegalArgumentException("The specified band is out of range. "+band+" / "+bands.length);
return bands[band];
}
/**
* Creates a sub-image from 'this' image. The subimage will share the same internal array
* that stores each pixel's value, but will only pertain to an axis-aligned rectangular segment
* of the original.
*
*
* @param x0 x-coordinate of top-left corner of the sub-image.
* @param y0 y-coordinate of top-left corner of the sub-image.
* @param x1 x-coordinate of bottom-right corner of the sub-image.
* @param y1 y-coordinate of bottom-right corner of the sub-image.
* @param output Optional storage for subimage
* @return A sub-image of this image.
*/
@Override
public Planar<T> subimage(int x0, int y0, int x1, int y1, @Nullable Planar<T> output) {
if (x0 < 0 || y0 < 0)
throw new IllegalArgumentException("x0 or y0 is less than zero");
if (x1 < x0 || y1 < y0)
throw new IllegalArgumentException("x1 or y1 is less than x0 or y0 respectively");
if (x1 > width || y1 > height)
throw new IllegalArgumentException("x1 or y1 is more than the width or height respectively");
if (output != null) {
output.type = type;
output.bands = (T[]) Array.newInstance(type, bands.length);
} else {
output = new Planar<>(type, bands.length);
}
output.stride = Math.max(width, stride);
output.width = x1 - x0;
output.height = y1 - y0;
output.startIndex = startIndex + y0 * stride + x0;
output.subImage = true;
for( int i = 0; i < bands.length; i++ ) {
output.bands[i] = (T)bands[i].subimage(x0,y0,x1,y1);
}
return output;
}
/**
* Sets the values of each pixel equal to the pixels in the specified matrix.
* Automatically resized to match the input image.
*
* @param orig The original image whose value is to be copied into this one
*/
@Override
public void setTo( Planar<T> orig) {
if (orig.width != width || orig.height != height)
reshape(orig.width,orig.height);
if( orig.getBandType() != getBandType() )
throw new IllegalArgumentException("The band type must be the same");
int N = orig.getNumBands();
if( N != getNumBands() ) {
setNumberOfBands(orig.getNumBands());
}
for( int i = 0; i < N; i++ ) {
bands[i].setTo(orig.getBand(i));
}
}
/**
* Changes the image's width and height without declaring new memory. If the internal array
* is not large enough to store the new image an IllegalArgumentException is thrown.
*
* @param width The new width.
* @param height The new height.
*/
@Override
public void reshape(int width, int height) {
if( this.width == width && this.height == height )
return;
if( isSubimage() )
throw new IllegalArgumentException("Can't reshape subimage");
for( int i = 0; i < bands.length; i++ ) {
bands[i].reshape(width,height);
}
this.startIndex = 0;
this.stride = width;
this.width = width;
this.height = height;
}
@Override
public void reshape(int width, int height, int numberOfBands) {
if( getNumBands() != numberOfBands ) {
if( isSubimage() )
throw new RuntimeException("Can't reshape subimage");
T[] bands = (T[]) Array.newInstance(type, numberOfBands);
int N = Math.min(numberOfBands, this.bands.length );
for (int i = 0; i < N; i++) {
bands[i] = this.bands[i];
bands[i].reshape(width, height);
}
for (int i = N; i < bands.length; i++) {
bands[i] = ImageGray.create(type, width, height);
}
this.startIndex = 0;
this.bands = bands;
this.stride = width;
this.width = width;
this.height = height;
this.imageType.numBands = numberOfBands;
} else {
reshape(width, height);
}
}
/**
* Creates a new image of the same type and number of bands
*
* @param imgWidth image width
* @param imgHeight image height
* @return new image
*/
@Override
public Planar<T> createNew(int imgWidth, int imgHeight) {
return new Planar<>(type, imgWidth, imgHeight, bands.length);
}
@Override
public void copyRow(int row, int col0, int col1, int offset, Object array) {
throw new IllegalArgumentException("Not supported for planar images");
}
@Override
public void copyCol(int col, int row0, int row1, int offset, Object array) {
throw new IllegalArgumentException("Not supported for planar images");
}
/**
* Returns a new {@link Planar} which references the same internal single band images at this one.
*
* @param which List of bands which will comprise the new image
* @return New image
*/
public Planar<T> partialSpectrum(int ...which ) {
Planar<T> out = new Planar<>(getBandType(), which.length);
out.setWidth(width);
out.setHeight(height);
out.setStride(stride);
for (int i = 0; i < which.length; i++) {
out.setBand(i,getBand(which[i]));
}
return out;
}
/**
* Changes the bands order
* @param order The new band order
*/
public void reorderBands( int ...order ) {
T[] bands = (T[]) Array.newInstance(type, order.length);
for (int i = 0; i < order.length; i++) {
bands[i] = this.bands[order[i]];
}
this.bands = bands;
}
/**
* Changes the number of bands in the image. A new array is declared and individual bands are recycled
* if possible
* @param numberOfBands New number of bands in the image.
*/
@Override
public void setNumberOfBands( int numberOfBands ) {
if( numberOfBands == this.bands.length )
return;
T[] bands = (T[]) Array.newInstance(type, numberOfBands);
int N = Math.min(numberOfBands, this.bands.length );
for (int i = 0; i < N; i++) {
bands[i] = this.bands[i];
}
for (int i = N; i < bands.length; i++) {
bands[i] = ImageGray.create(type, width, height);
}
this.bands = bands;
this.imageType.numBands = this.bands.length;
}
/**
* Returns an integer formed from 4 bands. band[0]<<24 | band[1] << 16 | band[2]<<8 | band[3]. Assumes
* arrays are U8 type.
*
* @param x column
* @param y row
* @return 32 bit integer
*/
public int get32u8( int x , int y ) {
int i = startIndex + y*stride+x;
return ((((GrayU8)bands[0]).data[i]&0xFF) << 24) |
((((GrayU8)bands[1]).data[i]&0xFF) << 16) |
((((GrayU8)bands[2]).data[i]&0xFF) << 8) |
(((GrayU8)bands[3]).data[i]&0xFF);
}
/**
* Returns an integer formed from 3 bands. band[0]<<16| band[1] << 8 | band[2]
*
* @param x column
* @param y row
* @return 32 bit integer
*/
public int get24u8( int x , int y ) {
int i = startIndex + y*stride+x;
return ((((GrayU8)bands[0]).data[i]&0xFF) << 16) |
((((GrayU8)bands[1]).data[i]&0xFF) << 8) |
(((GrayU8)bands[2]).data[i]&0xFF);
}
public void set24u8( int x , int y , int value ) {
int i = startIndex + y*stride+x;
((GrayU8)bands[0]).data[i] = (byte)(value>>>16);
((GrayU8)bands[1]).data[i] = (byte)(value>>>8);
((GrayU8)bands[2]).data[i] = (byte)value;
}
public void set32u8( int x , int y , int value ) {
int i = startIndex + y*stride+x;
((GrayU8)bands[0]).data[i] = (byte)(value>>>24);
((GrayU8)bands[1]).data[i] = (byte)(value>>>16);
((GrayU8)bands[2]).data[i] = (byte)(value>>>8);
((GrayU8)bands[3]).data[i] = (byte)value;
}
public void setBandType(Class<T> type) {
if( this.type != null && this.type != type )
throw new RuntimeException("Once the band type has been set you can't change it");
this.type = type;
}
public T[] getBands() {
return bands;
}
public void setBands(T[] bands) {
this.bands = bands;
}
public void setBand( int which , T image ) {
this.bands[which] = image;
}
}
| |
/*
* ====================================================================
* 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.hc.core5.http.message;
import org.apache.hc.core5.http.HeaderElement;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.util.CharArrayBuffer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for header value parsing.
*
* @version $Id$
*/
public class TestBasicHeaderValueParser {
private BasicHeaderValueParser parser;
@Before
public void setup() {
this.parser = BasicHeaderValueParser.INSTANCE;
}
@Test
public void testParseHeaderElements() throws Exception {
final String headerValue = "name1 = value1; name2; name3=\"value3\" , name4=value4; " +
"name5=value5, name6= ; name7 = value7; name8 = \" value8\"";
final CharArrayBuffer buf = new CharArrayBuffer(64);
buf.append(headerValue);
final ParserCursor cursor = new ParserCursor(0, buf.length());
final HeaderElement[] elements = this.parser.parseElements(buf, cursor);
// there are 3 elements
Assert.assertEquals(3,elements.length);
// 1st element
Assert.assertEquals("name1",elements[0].getName());
Assert.assertEquals("value1",elements[0].getValue());
// 1st element has 2 getParameters()
Assert.assertEquals(2,elements[0].getParameters().length);
Assert.assertEquals("name2",elements[0].getParameters()[0].getName());
Assert.assertEquals(null, elements[0].getParameters()[0].getValue());
Assert.assertEquals("name3",elements[0].getParameters()[1].getName());
Assert.assertEquals("value3",elements[0].getParameters()[1].getValue());
// 2nd element
Assert.assertEquals("name4",elements[1].getName());
Assert.assertEquals("value4",elements[1].getValue());
// 2nd element has 1 parameter
Assert.assertEquals(1,elements[1].getParameters().length);
Assert.assertEquals("name5",elements[1].getParameters()[0].getName());
Assert.assertEquals("value5",elements[1].getParameters()[0].getValue());
// 3rd element
Assert.assertEquals("name6",elements[2].getName());
Assert.assertEquals("",elements[2].getValue());
// 3rd element has 2 getParameters()
Assert.assertEquals(2,elements[2].getParameters().length);
Assert.assertEquals("name7",elements[2].getParameters()[0].getName());
Assert.assertEquals("value7",elements[2].getParameters()[0].getValue());
Assert.assertEquals("name8",elements[2].getParameters()[1].getName());
Assert.assertEquals(" value8",elements[2].getParameters()[1].getValue());
}
@Test
public void testParseHEEscaped() {
final String headerValue =
"test1 = \"\\\"stuff\\\"\", test2= \"\\\\\", test3 = \"stuff, stuff\"";
final CharArrayBuffer buf = new CharArrayBuffer(64);
buf.append(headerValue);
final ParserCursor cursor = new ParserCursor(0, buf.length());
final HeaderElement[] elements = this.parser.parseElements(buf, cursor);
Assert.assertEquals(3, elements.length);
Assert.assertEquals("test1", elements[0].getName());
Assert.assertEquals("\"stuff\"", elements[0].getValue());
Assert.assertEquals("test2", elements[1].getName());
Assert.assertEquals("\\", elements[1].getValue());
Assert.assertEquals("test3", elements[2].getName());
Assert.assertEquals("stuff, stuff", elements[2].getValue());
}
@Test
public void testHEFringeCase1() throws Exception {
final String headerValue = "name1 = value1,";
final CharArrayBuffer buf = new CharArrayBuffer(64);
buf.append(headerValue);
final ParserCursor cursor = new ParserCursor(0, buf.length());
final HeaderElement[] elements = this.parser.parseElements(buf, cursor);
Assert.assertEquals("Number of elements", 1, elements.length);
}
@Test
public void testHEFringeCase2() throws Exception {
final String headerValue = "name1 = value1, ";
final CharArrayBuffer buf = new CharArrayBuffer(64);
buf.append(headerValue);
final ParserCursor cursor = new ParserCursor(0, buf.length());
final HeaderElement[] elements = this.parser.parseElements(buf, cursor);
Assert.assertEquals("Number of elements", 1, elements.length);
}
@Test
public void testHEFringeCase3() throws Exception {
final String headerValue = ",, ,, ,";
final CharArrayBuffer buf = new CharArrayBuffer(64);
buf.append(headerValue);
final ParserCursor cursor = new ParserCursor(0, buf.length());
final HeaderElement[] elements = this.parser.parseElements(buf, cursor);
Assert.assertEquals("Number of elements", 0, elements.length);
}
@Test
public void testNVParse() {
String s = "test";
CharArrayBuffer buffer = new CharArrayBuffer(64);
buffer.append(s);
ParserCursor cursor = new ParserCursor(0, s.length());
NameValuePair param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("test", param.getName());
Assert.assertEquals(null, param.getValue());
Assert.assertEquals(s.length(), cursor.getPos());
Assert.assertTrue(cursor.atEnd());
s = "test;";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("test", param.getName());
Assert.assertEquals(null, param.getValue());
Assert.assertEquals(s.length(), cursor.getPos());
Assert.assertTrue(cursor.atEnd());
s = "test ,12";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("test", param.getName());
Assert.assertEquals(null, param.getValue());
Assert.assertEquals(s.length() - 2, cursor.getPos());
Assert.assertFalse(cursor.atEnd());
s = "test=stuff";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("test", param.getName());
Assert.assertEquals("stuff", param.getValue());
Assert.assertEquals(s.length(), cursor.getPos());
Assert.assertTrue(cursor.atEnd());
s = " test = stuff ";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("test", param.getName());
Assert.assertEquals("stuff", param.getValue());
Assert.assertEquals(s.length(), cursor.getPos());
Assert.assertTrue(cursor.atEnd());
s = " test = stuff ;1234";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("test", param.getName());
Assert.assertEquals("stuff", param.getValue());
Assert.assertEquals(s.length() - 4, cursor.getPos());
Assert.assertFalse(cursor.atEnd());
s = "test = \"stuff\"";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("test", param.getName());
Assert.assertEquals("stuff", param.getValue());
s = "test = \" stuff\\\"\"";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("test", param.getName());
Assert.assertEquals(" stuff\"", param.getValue());
s = " test";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("test", param.getName());
Assert.assertEquals(null, param.getValue());
s = " ";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("", param.getName());
Assert.assertEquals(null, param.getValue());
s = " = stuff ";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
param = this.parser.parseNameValuePair(buffer, cursor);
Assert.assertEquals("", param.getName());
Assert.assertEquals("stuff", param.getValue());
}
@Test
public void testNVParseAll() {
String s =
"test; test1 = stuff ; test2 = \"stuff; stuff\"; test3=\"stuff";
CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append(s);
ParserCursor cursor = new ParserCursor(0, s.length());
NameValuePair[] params = this.parser.parseParameters(buffer, cursor);
Assert.assertEquals("test", params[0].getName());
Assert.assertEquals(null, params[0].getValue());
Assert.assertEquals("test1", params[1].getName());
Assert.assertEquals("stuff", params[1].getValue());
Assert.assertEquals("test2", params[2].getName());
Assert.assertEquals("stuff; stuff", params[2].getValue());
Assert.assertEquals("test3", params[3].getName());
Assert.assertEquals("stuff", params[3].getValue());
Assert.assertEquals(s.length(), cursor.getPos());
Assert.assertTrue(cursor.atEnd());
s =
"test; test1 = stuff ; test2 = \"stuff; stuff\"; test3=\"stuff\",123";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
params = this.parser.parseParameters(buffer, cursor);
Assert.assertEquals("test", params[0].getName());
Assert.assertEquals(null, params[0].getValue());
Assert.assertEquals("test1", params[1].getName());
Assert.assertEquals("stuff", params[1].getValue());
Assert.assertEquals("test2", params[2].getName());
Assert.assertEquals("stuff; stuff", params[2].getValue());
Assert.assertEquals("test3", params[3].getName());
Assert.assertEquals("stuff", params[3].getValue());
Assert.assertEquals(s.length() - 3, cursor.getPos());
Assert.assertFalse(cursor.atEnd());
s = " ";
buffer = new CharArrayBuffer(16);
buffer.append(s);
cursor = new ParserCursor(0, s.length());
params = this.parser.parseParameters(buffer, cursor);
Assert.assertEquals(0, params.length);
}
@Test
public void testNVParseEscaped() {
final String headerValue =
"test1 = \"\\\"stuff\\\"\"; test2= \"\\\\\"; test3 = \"stuff; stuff\"";
final CharArrayBuffer buf = new CharArrayBuffer(64);
buf.append(headerValue);
final ParserCursor cursor = new ParserCursor(0, buf.length());
final NameValuePair[] params = this.parser.parseParameters(buf, cursor);
Assert.assertEquals(3, params.length);
Assert.assertEquals("test1", params[0].getName());
Assert.assertEquals("\"stuff\"", params[0].getValue());
Assert.assertEquals("test2", params[1].getName());
Assert.assertEquals("\\", params[1].getValue());
Assert.assertEquals("test3", params[2].getName());
Assert.assertEquals("stuff; stuff", params[2].getValue());
}
}
| |
// Copyright 2000-2017 JetBrains s.r.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.intellij.psi.codeStyle;
import com.intellij.lang.Language;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.ApiStatus;
/**
* Contains fields which are left for compatibility with earlier versions. These fields shouldn't be used anymore. Every language must have
* its own settings which can be retrieved using {@link CodeStyleSettings#getCommonSettings(Language)} or
* {@link com.intellij.application.options.CodeStyle#getLanguageSettings(PsiFile)}.
*
* @see LanguageCodeStyleSettingsProvider
*/
@SuppressWarnings("FieldNameHidesFieldInSuperclass")
public class LegacyCodeStyleSettings extends CommonCodeStyleSettings {
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean KEEP_LINE_BREAKS = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean KEEP_FIRST_COLUMN_COMMENT = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public int KEEP_BLANK_LINES_IN_DECLARATIONS = 2;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public int KEEP_BLANK_LINES_IN_CODE = 2;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public int BLANK_LINES_AROUND_CLASS = 1;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean INDENT_CASE_FROM_SWITCH = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean ALIGN_MULTILINE_BINARY_OPERATION = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated
public boolean SPACE_AROUND_ASSIGNMENT_OPERATORS = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AROUND_LOGICAL_OPERATORS = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AROUND_EQUALITY_OPERATORS = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AROUND_RELATIONAL_OPERATORS = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AROUND_BITWISE_OPERATORS = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AROUND_ADDITIVE_OPERATORS = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AROUND_MULTIPLICATIVE_OPERATORS = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AROUND_SHIFT_OPERATORS = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AFTER_COMMA = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_COMMA = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AFTER_SEMICOLON = true; // in for-statement
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_SEMICOLON = false; // in for-statement
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_WITHIN_PARENTHESES = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_WITHIN_METHOD_CALL_PARENTHESES = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_WITHIN_METHOD_PARENTHESES = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_WITHIN_IF_PARENTHESES = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_WITHIN_WHILE_PARENTHESES = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_WITHIN_BRACKETS = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AFTER_TYPE_CAST = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_METHOD_CALL_PARENTHESES = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_METHOD_PARENTHESES = false;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_IF_PARENTHESES = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_WHILE_PARENTHESES = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_CLASS_LBRACE = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_METHOD_LBRACE = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_IF_LBRACE = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_WHILE_LBRACE = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_QUEST = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AFTER_QUEST = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_BEFORE_COLON = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean SPACE_AFTER_COLON = true;
/**
* @deprecated See {@link LegacyCodeStyleSettings}
*/
@Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
public boolean KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false;
public LegacyCodeStyleSettings() {
super(null);
}
}
| |
package mil.army.usace.ehlschlaeger.rgik.util;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import mil.army.usace.ehlschlaeger.rgik.io.StringOutputStream;
/**
* Helper to clean and organize our use of java.util.logging.
* <P>
* Recommended startup:<PRE>
* LogUtil.getRootLogger().setLevel(Level.INFO);
* LogUtil.cleanFormat();
* </PRE>
* <P>
* Use this sequence to log to a file, while sending a reduced copy to the console:<PRE>
* LogUtil.getRootLogger().setLevel(Level.INFO);
* LogUtil.quietConsole();
* LogUtil.cleanFormat();
* LogUtil.setOutput(new File("dir/output.log").getCanonicalPath());
* </PRE>
* <p>
* Copyright <a href="http://faculty.wiu.edu/CR-Ehlschlaeger2/">Charles R.
* Ehlschlaeger</a>, work: 309-298-1841, fax: 309-298-3003, This software is
* freely usable for research and educational purposes. Contact C. R.
* Ehlschlaeger for permission for other purposes. Use of this software requires
* appropriate citation in all published and unpublished documentation.
*
* @author William R. Zwicky
*/
public class LogUtil {
// OFF Integer.MAX_VALUE
// SEVERE 1000
// WARNING 900
/** Level for announcing progress (percent complete, phase finished, etc.) */
public static final Level PROGRESS = new LogLevel("PROGRESS", 890);
/** Level for announcing results (numbers of things). */
public static final Level RESULT = new LogLevel("RESULT", 880);
/** Level for announcing details leading to results (items skipped, intermediate values). */
public static final Level DETAIL = new LogLevel("DETAIL", 870);
// INFO 800
// CONFIG 700
// FINE 500
// FINER 400
// FINEST 300
/** Log a blank line at all levels. */
protected static final LogRecord NEWLINE = new LogRecord(Level.OFF, "");
/** Current output file. */
protected static FileHandler fh = null;
/** Instantiation is forbidden. */
private LogUtil() {
}
/** Helper to fetch root logger. */
public static Logger getRootLogger() {
return Logger.getLogger("");
}
/**
* Reset all handlers to our one-line CleanForammter.
*/
public static void cleanFormat() {
Logger root = getRootLogger();
Formatter fmt = new CleanFormatter();
for(Handler h : root.getHandlers()) {
if (h instanceof ConsoleHandler) {
h.setFormatter(fmt);
}
}
}
/**
* Reset all handlers to our one-line CleanForammter.
*/
public static void cleanFormat(Logger log) {
Formatter fmt = new CleanFormatter();
for(Handler h : log.getHandlers()) {
h.setFormatter(fmt);
}
}
/**
* Copy logging output to a file. Closes previous file.
* Uses our "clean" format.
*
* @param pattern
* @throws SecurityException
* @throws IOException
*/
public static void setOutput(String pattern) throws SecurityException, IOException {
FileHandler new_fh = new FileHandler(pattern);
new_fh.setFormatter(new CleanFormatter());
Logger root = getRootLogger();
synchronized (root) {
root.addHandler(new_fh);
if(fh != null)
root.removeHandler(fh);
}
if(fh != null)
fh.close();
fh = new_fh;
}
/**
* Set console to only print progress reports and errors.
*/
public static void quietConsole() {
Logger root = getRootLogger();
for(Handler h : root.getHandlers()) {
if (h instanceof ConsoleHandler) {
h.setLevel(PROGRESS);
}
}
}
/**
* Stops all logging to the console.
*/
public static void disableConsole() {
Logger root = getRootLogger();
for(Handler h : root.getHandlers()) {
if (h instanceof ConsoleHandler) {
root.removeHandler(h);
}
}
}
/**
* Helper to find currently configured log level.
*
* @param log
*
* @return configured or inherited log level of given logger, or null if no
* logger is configured
*/
public static Level getEffectiveLevel(Logger log) {
Level level;
do {
level = log.getLevel();
if(level == null)
log = log.getParent();
else
break;
} while(log != null);
return level;
}
/**
* Helper to determine if a logger will write output from a given level.
*
* @param log logger that will be used to write messages
* @param desiredLevel level at which messages will be written
*
* @return 'true' if messages will be written; 'false' if not
*/
public static boolean allowed(Logger log, Level desiredLevel) {
return getEffectiveLevel(log).intValue() >= desiredLevel.intValue();
}
/**
* Log a blank line at all levels.
* @param log
*/
public static void cr(Logger log) {
log.log(NEWLINE);
}
/**
* Log a progress message.
* @param log
* @param message
*/
public static void progress(Logger log, Object message) {
log.log(PROGRESS, message.toString());
}
/**
* Log a progress message.
* @param log
* @param format
* @param args
*/
public static void progress(Logger log, String format, Object... args) {
log.log(PROGRESS, String.format(format, args));
}
/**
* Log the result of some computation.
*
* @param log
* @param message
*/
public static void result(Logger log, Object message) {
log.log(RESULT, message.toString());
}
/**
* Log the result of some computation.
*
* @param log
* @param format
* @param args
*/
public static void result(Logger log, String format, Object... args) {
log.log(RESULT, String.format(format, args));
}
/**
* Log detail explaining a computation or result.
* @param log
* @param message
*/
public static void detail(Logger log, Object message) {
log.log(DETAIL, message.toString());
}
/**
* Log detail explaining a computation or result.
*
* @param log
* @param format
* @param args
*/
public static void detail(Logger log, String format, Object... args) {
log.log(DETAIL, String.format(format, args));
}
}
/**
* Makes logging.Level instantiable.
*/
class LogLevel extends Level {
public LogLevel(String name, int value) {
super(name, value);
}
}
/**
* Print only messages to output, not names, dates, or levels.
*/
class CleanFormatter extends Formatter {
private boolean did_cr = false;
@Override
public String format(LogRecord record) {
// Our caller filters levels.
// Print only one blank line.
if("".equals(record.getMessage())) {
if(did_cr)
return "";
else {
did_cr = true;
return "\n";
}
}
else {
did_cr = false;
StringBuffer buf = new StringBuffer();
// Header only in emergencies.
if(record.getLevel().intValue() >= Level.WARNING.intValue())
buf.append(record.getLevel()).append(": ");
// buf.append(record.getLevel()).append(": ").append(record.getLoggerName()).append(": ");
buf.append(formatMessage(record));
// Ensure a newline at the end.
char tail = (buf.length() == 0 ? '\0' : buf.charAt(buf.length() - 1));
switch (tail) {
case '\n':
case '\r':
break;
default:
buf.append("\n");
}
if(record.getThrown() != null) {
StringOutputStream sw = new StringOutputStream();
record.getThrown().printStackTrace(sw);
buf.append(" ").append(sw.toString());
}
return buf.toString();
}
}
}
| |
/*
* Xero Payroll NZ
* This is the Xero Payroll API for orgs in the NZ region.
*
* Contact: api@xero.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.xero.models.payrollnz;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.xero.api.StringUtil;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
/** Pagination */
public class Pagination {
StringUtil util = new StringUtil();
@JsonProperty("page")
private Integer page;
@JsonProperty("pageSize")
private Integer pageSize;
@JsonProperty("pageCount")
private Integer pageCount;
@JsonProperty("itemCount")
private Integer itemCount;
/**
* page
*
* @param page Integer
* @return Pagination
*/
public Pagination page(Integer page) {
this.page = page;
return this;
}
/**
* Get page
*
* @return page
*/
@ApiModelProperty(example = "1", value = "")
/**
* page
*
* @return page Integer
*/
public Integer getPage() {
return page;
}
/**
* page
*
* @param page Integer
*/
public void setPage(Integer page) {
this.page = page;
}
/**
* pageSize
*
* @param pageSize Integer
* @return Pagination
*/
public Pagination pageSize(Integer pageSize) {
this.pageSize = pageSize;
return this;
}
/**
* Get pageSize
*
* @return pageSize
*/
@ApiModelProperty(example = "10", value = "")
/**
* pageSize
*
* @return pageSize Integer
*/
public Integer getPageSize() {
return pageSize;
}
/**
* pageSize
*
* @param pageSize Integer
*/
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
/**
* pageCount
*
* @param pageCount Integer
* @return Pagination
*/
public Pagination pageCount(Integer pageCount) {
this.pageCount = pageCount;
return this;
}
/**
* Get pageCount
*
* @return pageCount
*/
@ApiModelProperty(example = "1", value = "")
/**
* pageCount
*
* @return pageCount Integer
*/
public Integer getPageCount() {
return pageCount;
}
/**
* pageCount
*
* @param pageCount Integer
*/
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
/**
* itemCount
*
* @param itemCount Integer
* @return Pagination
*/
public Pagination itemCount(Integer itemCount) {
this.itemCount = itemCount;
return this;
}
/**
* Get itemCount
*
* @return itemCount
*/
@ApiModelProperty(example = "2", value = "")
/**
* itemCount
*
* @return itemCount Integer
*/
public Integer getItemCount() {
return itemCount;
}
/**
* itemCount
*
* @param itemCount Integer
*/
public void setItemCount(Integer itemCount) {
this.itemCount = itemCount;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pagination pagination = (Pagination) o;
return Objects.equals(this.page, pagination.page)
&& Objects.equals(this.pageSize, pagination.pageSize)
&& Objects.equals(this.pageCount, pagination.pageCount)
&& Objects.equals(this.itemCount, pagination.itemCount);
}
@Override
public int hashCode() {
return Objects.hash(page, pageSize, pageCount, itemCount);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pagination {\n");
sb.append(" page: ").append(toIndentedString(page)).append("\n");
sb.append(" pageSize: ").append(toIndentedString(pageSize)).append("\n");
sb.append(" pageCount: ").append(toIndentedString(pageCount)).append("\n");
sb.append(" itemCount: ").append(toIndentedString(itemCount)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| |
package com.jetbrains.edu.learning.ui;
import com.intellij.icons.AllIcons;
import com.intellij.ide.BrowserUtil;
import com.intellij.ide.ui.LafManager;
import com.intellij.ide.ui.LafManagerListener;
import com.intellij.ide.ui.laf.darcula.DarculaLookAndFeelInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.util.io.StreamUtil;
import com.jetbrains.edu.learning.StudyPluginConfigurator;
import javafx.application.Platform;
import javafx.concurrent.Worker;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.*;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
class StudyBrowserWindow extends JFrame {
private static final Logger LOG = Logger.getInstance(StudyToolWindow.class);
private static final String EVENT_TYPE_CLICK = "click";
private JFXPanel myPanel;
private WebView myWebComponent;
private StackPane myPane;
private WebEngine myEngine;
private ProgressBar myProgressBar;
private boolean myLinkInNewBrowser = true;
private boolean myShowProgress = false;
public StudyBrowserWindow(final boolean linkInNewWindow, final boolean showProgress) {
myLinkInNewBrowser = linkInNewWindow;
myShowProgress = showProgress;
setSize(new Dimension(900, 800));
setLayout(new BorderLayout());
setPanel(new JFXPanel());
setTitle("Study Browser");
LafManager.getInstance().addLafManagerListener(new StudyLafManagerListener());
initComponents();
}
private void updateLaf(boolean isDarcula) {
if (isDarcula) {
updateLafDarcula();
}
else {
updateIntellijAndGTKLaf();
}
}
private void updateIntellijAndGTKLaf() {
Platform.runLater(() -> {
final URL scrollBarStyleUrl = getClass().getResource("/style/javaFXBrowserScrollBar.css");
myPane.getStylesheets().add(scrollBarStyleUrl.toExternalForm());
myEngine.setUserStyleSheetLocation(null);
myEngine.reload();
});
}
private void updateLafDarcula() {
Platform.runLater(() -> {
final URL engineStyleUrl = getClass().getResource("/style/javaFXBrowserDarcula.css");
final URL scrollBarStyleUrl = getClass().getResource("/style/javaFXBrowserDarculaScrollBar.css");
myEngine.setUserStyleSheetLocation(engineStyleUrl.toExternalForm());
myPane.getStylesheets().add(scrollBarStyleUrl.toExternalForm());
myPane.setStyle("-fx-background-color: #3c3f41");
myPanel.getScene().getStylesheets().add(engineStyleUrl.toExternalForm());
myEngine.reload();
});
}
private void initComponents() {
Platform.runLater(() -> {
myPane = new StackPane();
myWebComponent = new WebView();
myEngine = myWebComponent.getEngine();
if (myShowProgress) {
myProgressBar = makeProgressBarWithListener();
myWebComponent.setVisible(false);
myPane.getChildren().addAll(myWebComponent, myProgressBar);
}
else {
myPane.getChildren().add(myWebComponent);
}
if (myLinkInNewBrowser) {
initHyperlinkListener();
}
Scene scene = new Scene(myPane);
myPanel.setScene(scene);
myPanel.setVisible(true);
updateLaf(LafManager.getInstance().getCurrentLookAndFeel() instanceof DarculaLookAndFeelInfo);
});
add(myPanel, BorderLayout.CENTER);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public void load(@NotNull final String url) {
Platform.runLater(() -> {
updateLookWithProgressBarIfNeeded();
myEngine.load(url);
});
}
public void loadContent(@NotNull final String content, @Nullable StudyPluginConfigurator configurator) {
if (configurator == null) {
Platform.runLater(() -> myEngine.loadContent(content));
}
else {
String withCodeHighlighting = createHtmlWithCodeHighlighting(content, configurator);
Platform.runLater(() -> {
updateLookWithProgressBarIfNeeded();
myEngine.loadContent(withCodeHighlighting);
});
}
}
@Nullable
private String createHtmlWithCodeHighlighting(@NotNull final String content, @NotNull StudyPluginConfigurator configurator) {
String template = null;
InputStream stream = getClass().getResourceAsStream("/code-mirror/template.html");
try {
template = StreamUtil.readText(stream, "utf-8");
}
catch (IOException e) {
LOG.warn(e.getMessage());
}
finally {
try {
stream.close();
}
catch (IOException e) {
LOG.warn(e.getMessage());
}
}
if (template == null) {
LOG.warn("Code mirror template is null");
return null;
}
final EditorColorsScheme editorColorsScheme = EditorColorsManager.getInstance().getGlobalScheme();
int fontSize = editorColorsScheme.getEditorFontSize();
template = template.replace("${font_size}", String.valueOf(fontSize- 2));
template = template.replace("${codemirror}", getClass().getResource("/code-mirror/codemirror.js").toExternalForm());
template = template.replace("${language_script}", configurator.getLanguageScriptUrl());
template = template.replace("${default_mode}", configurator.getDefaultHighlightingMode());
template = template.replace("${runmode}", getClass().getResource("/code-mirror/runmode.js").toExternalForm());
template = template.replace("${colorize}", getClass().getResource("/code-mirror/colorize.js").toExternalForm());
template = template.replace("${javascript}", getClass().getResource("/code-mirror/javascript.js").toExternalForm());
if (LafManager.getInstance().getCurrentLookAndFeel() instanceof DarculaLookAndFeelInfo) {
template = template.replace("${css_oldcodemirror}", getClass().getResource("/code-mirror/codemirror-old-darcula.css").toExternalForm());
template = template.replace("${css_codemirror}", getClass().getResource("/code-mirror/codemirror-darcula.css").toExternalForm());
}
else {
template = template.replace("${css_oldcodemirror}", getClass().getResource("/code-mirror/codemirror-old.css").toExternalForm());
template = template.replace("${css_codemirror}", getClass().getResource("/code-mirror/codemirror.css").toExternalForm());
}
template = template.replace("${code}", content);
return template;
}
private void updateLookWithProgressBarIfNeeded() {
if (myShowProgress) {
myProgressBar.setVisible(true);
myWebComponent.setVisible(false);
}
}
private void initHyperlinkListener() {
myEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
final EventListener listener = makeHyperLinkListener();
addListenerToAllHyperlinkItems(listener);
}
});
}
private void addListenerToAllHyperlinkItems(EventListener listener) {
final Document doc = myEngine.getDocument();
if (doc != null) {
final NodeList nodeList = doc.getElementsByTagName("a");
for (int i = 0; i < nodeList.getLength(); i++) {
((EventTarget)nodeList.item(i)).addEventListener(EVENT_TYPE_CLICK, listener, false);
}
}
}
@NotNull
private EventListener makeHyperLinkListener() {
return new EventListener() {
@Override
public void handleEvent(Event ev) {
String domEventType = ev.getType();
if (domEventType.equals(EVENT_TYPE_CLICK)) {
myEngine.setJavaScriptEnabled(true);
myEngine.getLoadWorker().cancel();
ev.preventDefault();
final String href = getLink((Element)ev.getTarget());
if (href == null) return;
BrowserUtil.browse(href);
}
}
@Nullable
private String getLink(@NotNull Element element) {
final String href = element.getAttribute("href");
return href == null ? getLinkFromNodeWithCodeTag(element) : href;
}
@Nullable
private String getLinkFromNodeWithCodeTag(@NotNull Element element) {
Node parentNode = element.getParentNode();
NamedNodeMap attributes = parentNode.getAttributes();
while (attributes.getLength() > 0 && attributes.getNamedItem("class") != null) {
parentNode = parentNode.getParentNode();
attributes = parentNode.getAttributes();
}
return attributes.getNamedItem("href").getNodeValue();
}
};
}
public void addBackAndOpenButtons() {
ApplicationManager.getApplication().invokeLater(() -> {
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
final JButton backButton = makeGoButton("Click to go back", AllIcons.Actions.Back, -1);
final JButton forwardButton = makeGoButton("Click to go forward", AllIcons.Actions.Forward, 1);
final JButton openInBrowser = new JButton(AllIcons.Actions.Browser_externalJavaDoc);
openInBrowser.addActionListener(e -> BrowserUtil.browse(myEngine.getLocation()));
openInBrowser.setToolTipText("Click to open link in browser");
addButtonsAvailabilityListeners(backButton, forwardButton);
panel.setMaximumSize(new Dimension(40, getPanel().getHeight()));
panel.add(backButton);
panel.add(forwardButton);
panel.add(openInBrowser);
add(panel, BorderLayout.PAGE_START);
});
}
private void addButtonsAvailabilityListeners(JButton backButton, JButton forwardButton) {
Platform.runLater(() -> myEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
final WebHistory history = myEngine.getHistory();
boolean isGoBackAvailable = history.getCurrentIndex() > 0;
boolean isGoForwardAvailable = history.getCurrentIndex() < history.getEntries().size() - 1;
ApplicationManager.getApplication().invokeLater(() -> {
backButton.setEnabled(isGoBackAvailable);
forwardButton.setEnabled(isGoForwardAvailable);
});
}
}));
}
private JButton makeGoButton(@NotNull final String toolTipText, @NotNull final Icon icon, final int direction) {
final JButton button = new JButton(icon);
button.setEnabled(false);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
Platform.runLater(() -> myEngine.getHistory().go(direction));
}
}
});
button.setToolTipText(toolTipText);
return button;
}
private ProgressBar makeProgressBarWithListener() {
final ProgressBar progress = new ProgressBar();
progress.progressProperty().bind(myWebComponent.getEngine().getLoadWorker().progressProperty());
myWebComponent.getEngine().getLoadWorker().stateProperty().addListener(
(ov, oldState, newState) -> {
if (myWebComponent.getEngine().getLocation().contains("http") && newState == Worker.State.SUCCEEDED) {
myProgressBar.setVisible(false);
myWebComponent.setVisible(true);
}
});
return progress;
}
public JFXPanel getPanel() {
return myPanel;
}
private void setPanel(JFXPanel panel) {
myPanel = panel;
}
private class StudyLafManagerListener implements LafManagerListener {
@Override
public void lookAndFeelChanged(LafManager manager) {
updateLaf(manager.getCurrentLookAndFeel() instanceof DarculaLookAndFeelInfo);
}
}
}
| |
/*
* 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.activemq.artemis.component;
import javax.servlet.DispatcherType;
import java.io.File;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.activemq.artemis.ActiveMQWebLogger;
import org.apache.activemq.artemis.components.ExternalComponent;
import org.apache.activemq.artemis.dto.AppDTO;
import org.apache.activemq.artemis.dto.BindingDTO;
import org.apache.activemq.artemis.dto.ComponentDTO;
import org.apache.activemq.artemis.dto.WebServerDTO;
import org.eclipse.jetty.security.DefaultAuthenticatorFactory;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.CustomRequestLog;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.RequestLogWriter;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.webapp.WebAppContext;
import org.jboss.logging.Logger;
public class WebServerComponent implements ExternalComponent {
private static final Logger logger = Logger.getLogger(WebServerComponent.class);
private Server server;
private HandlerList handlers;
private WebServerDTO webServerConfig;
private final List<String> consoleUrls = new ArrayList<>();
private final List<String> jolokiaUrls = new ArrayList<>();
private List<WebAppContext> webContexts;
private ServerConnector[] connectors;
private Path artemisHomePath;
private Path temporaryWarDir;
@Override
public void configure(ComponentDTO config, String artemisInstance, String artemisHome) throws Exception {
webServerConfig = (WebServerDTO) config;
server = new Server();
HttpConfiguration httpConfiguration = new HttpConfiguration();
if (webServerConfig.customizer != null) {
try {
httpConfiguration.addCustomizer((HttpConfiguration.Customizer) Class.forName(webServerConfig.customizer).getConstructor().newInstance());
} catch (Throwable t) {
ActiveMQWebLogger.LOGGER.customizerNotLoaded(webServerConfig.customizer, t);
}
}
List<BindingDTO> bindings = webServerConfig.getBindings();
connectors = new ServerConnector[bindings.size()];
String[] virtualHosts = new String[bindings.size()];
for (int i = 0; i < bindings.size(); i++) {
BindingDTO binding = bindings.get(i);
URI uri = new URI(binding.uri);
String scheme = uri.getScheme();
ServerConnector connector;
if ("https".equals(scheme)) {
SslContextFactory.Server sslFactory = new SslContextFactory.Server();
sslFactory.setKeyStorePath(binding.keyStorePath == null ? artemisInstance + "/etc/keystore.jks" : binding.keyStorePath);
sslFactory.setKeyStorePassword(binding.getKeyStorePassword() == null ? "password" : binding.getKeyStorePassword());
if (binding.getIncludedTLSProtocols() != null) {
sslFactory.setIncludeProtocols(binding.getIncludedTLSProtocols());
}
if (binding.getExcludedTLSProtocols() != null) {
sslFactory.setExcludeProtocols(binding.getExcludedTLSProtocols());
}
if (binding.getIncludedCipherSuites() != null) {
sslFactory.setIncludeCipherSuites(binding.getIncludedCipherSuites());
}
if (binding.getExcludedCipherSuites() != null) {
sslFactory.setExcludeCipherSuites(binding.getExcludedCipherSuites());
}
if (binding.clientAuth != null) {
sslFactory.setNeedClientAuth(binding.clientAuth);
if (binding.clientAuth) {
sslFactory.setTrustStorePath(binding.trustStorePath);
sslFactory.setTrustStorePassword(binding.getTrustStorePassword());
}
}
SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslFactory, "HTTP/1.1");
httpConfiguration.addCustomizer(new SecureRequestCustomizer());
httpConfiguration.setSendServerVersion(false);
HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfiguration);
connector = new ServerConnector(server, sslConnectionFactory, httpFactory);
} else {
httpConfiguration.setSendServerVersion(false);
ConnectionFactory connectionFactory = new HttpConnectionFactory(httpConfiguration);
connector = new ServerConnector(server, connectionFactory);
}
connector.setPort(uri.getPort());
connector.setHost(uri.getHost());
connector.setName("Connector-" + i);
connectors[i] = connector;
virtualHosts[i] = "@Connector-" + i;
}
server.setConnectors(connectors);
handlers = new HandlerList();
this.artemisHomePath = Paths.get(artemisHome != null ? artemisHome : ".");
Path homeWarDir = artemisHomePath.resolve(webServerConfig.path).toAbsolutePath();
Path instanceWarDir = Paths.get(artemisInstance != null ? artemisInstance : ".").resolve(webServerConfig.path).toAbsolutePath();
temporaryWarDir = Paths.get(artemisInstance != null ? artemisInstance : ".").resolve("tmp").resolve("webapps").toAbsolutePath();
if (!Files.exists(temporaryWarDir)) {
Files.createDirectories(temporaryWarDir);
}
for (int i = 0; i < bindings.size(); i++) {
BindingDTO binding = bindings.get(i);
if (binding.apps != null && binding.apps.size() > 0) {
webContexts = new ArrayList<>();
for (AppDTO app : binding.apps) {
Path dirToUse = homeWarDir;
if (new File(instanceWarDir.toFile().toString() + File.separator + app.war).exists()) {
dirToUse = instanceWarDir;
}
WebAppContext webContext = deployWar(app.url, app.war, dirToUse, virtualHosts[i]);
webContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
webContexts.add(webContext);
if (app.war.startsWith("console")) {
consoleUrls.add(binding.uri + "/" + app.url);
jolokiaUrls.add(binding.uri + "/" + app.url + "/jolokia");
}
}
}
}
ResourceHandler homeResourceHandler = new ResourceHandler();
homeResourceHandler.setResourceBase(homeWarDir.toString());
homeResourceHandler.setDirectoriesListed(false);
homeResourceHandler.setWelcomeFiles(new String[]{"index.html"});
ContextHandler homeContext = new ContextHandler();
homeContext.setContextPath("/");
homeContext.setResourceBase(homeWarDir.toString());
homeContext.setHandler(homeResourceHandler);
homeContext.setVirtualHosts(virtualHosts);
homeContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
ResourceHandler instanceResourceHandler = new ResourceHandler();
instanceResourceHandler.setResourceBase(instanceWarDir.toString());
instanceResourceHandler.setDirectoriesListed(false);
instanceResourceHandler.setWelcomeFiles(new String[]{"index.html"});
ContextHandler instanceContext = new ContextHandler();
instanceContext.setContextPath("/");
instanceContext.setResourceBase(instanceWarDir.toString());
instanceContext.setHandler(instanceResourceHandler);
instanceContext.setVirtualHosts(virtualHosts);
homeContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
DefaultHandler defaultHandler = new DefaultHandler();
defaultHandler.setServeIcon(false);
if (webServerConfig.requestLog != null) {
handlers.addHandler(getLogHandler());
}
handlers.addHandler(homeContext);
handlers.addHandler(instanceContext);
handlers.addHandler(defaultHandler); // this should be last
server.setHandler(handlers);
}
private RequestLogHandler getLogHandler() {
RequestLogWriter requestLogWriter = new RequestLogWriter();
CustomRequestLog requestLog;
// required via config so no check necessary
requestLogWriter.setFilename(webServerConfig.requestLog.filename);
if (webServerConfig.requestLog.append != null) {
requestLogWriter.setAppend(webServerConfig.requestLog.append);
}
if (webServerConfig.requestLog.filenameDateFormat != null) {
requestLogWriter.setFilenameDateFormat(webServerConfig.requestLog.filenameDateFormat);
}
if (webServerConfig.requestLog.retainDays != null) {
requestLogWriter.setRetainDays(webServerConfig.requestLog.retainDays);
}
if (webServerConfig.requestLog.format != null) {
requestLog = new CustomRequestLog(requestLogWriter, webServerConfig.requestLog.format);
} else if (webServerConfig.requestLog.extended != null && webServerConfig.requestLog.extended) {
requestLog = new CustomRequestLog(requestLogWriter, CustomRequestLog.EXTENDED_NCSA_FORMAT);
} else {
requestLog = new CustomRequestLog(requestLogWriter, CustomRequestLog.NCSA_FORMAT);
}
if (webServerConfig.requestLog.ignorePaths != null && webServerConfig.requestLog.ignorePaths.length() > 0) {
String[] split = webServerConfig.requestLog.ignorePaths.split(",");
String[] ignorePaths = new String[split.length];
for (int i = 0; i < ignorePaths.length; i++) {
ignorePaths[i] = split[i].trim();
}
requestLog.setIgnorePaths(ignorePaths);
}
RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog(requestLog);
return requestLogHandler;
}
@Override
public void start() throws Exception {
if (isStarted()) {
return;
}
cleanupTmp();
server.start();
String bindings = webServerConfig.getBindings()
.stream()
.map(binding -> binding.uri)
.collect(Collectors.joining(", "));
ActiveMQWebLogger.LOGGER.webserverStarted(bindings);
ActiveMQWebLogger.LOGGER.jolokiaAvailable(String.join(", ", jolokiaUrls));
ActiveMQWebLogger.LOGGER.consoleAvailable(String.join(", ", consoleUrls));
}
public void internalStop() throws Exception {
server.stop();
if (webContexts != null) {
cleanupWebTemporaryFiles(webContexts);
webContexts.clear();
}
}
private File getLibFolder() {
Path lib = artemisHomePath.resolve("lib");
File libFolder = new File(lib.toUri());
return libFolder;
}
private void cleanupTmp() {
if (webContexts == null || webContexts.size() == 0) {
//there is no webapp to be deployed (as in some tests)
return;
}
try {
List<File> temporaryFiles = new ArrayList<>();
Files.newDirectoryStream(temporaryWarDir).forEach(path -> temporaryFiles.add(path.toFile()));
if (temporaryFiles.size() > 0) {
WebTmpCleaner.cleanupTmpFiles(getLibFolder(), temporaryFiles, true);
}
} catch (Exception e) {
logger.warn("Failed to get base dir for tmp web files", e);
}
}
public void cleanupWebTemporaryFiles(List<WebAppContext> webContexts) throws Exception {
List<File> temporaryFiles = new ArrayList<>();
for (WebAppContext context : webContexts) {
File tmpdir = context.getTempDirectory();
temporaryFiles.add(tmpdir);
}
if (!temporaryFiles.isEmpty()) {
WebTmpCleaner.cleanupTmpFiles(getLibFolder(), temporaryFiles);
}
}
@Override
public boolean isStarted() {
return server != null && server.isStarted();
}
/**
* @return started server's port number; useful if it was specified as 0 (to use a random port)
*/
@Deprecated
public int getPort() {
return getPort(0);
}
public int getPort(int connectorIndex) {
if (connectorIndex < connectors.length) {
return connectors[connectorIndex].getLocalPort();
}
return -1;
}
private WebAppContext deployWar(String url, String warFile, Path warDirectory, String virtualHost) {
WebAppContext webapp = new WebAppContext();
if (url.startsWith("/")) {
webapp.setContextPath(url);
} else {
webapp.setContextPath("/" + url);
}
//add the filters needed for audit logging
webapp.addFilter(new FilterHolder(JolokiaFilter.class), "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
webapp.addFilter(new FilterHolder(AuthenticationFilter.class), "/auth/login/*", EnumSet.of(DispatcherType.REQUEST));
webapp.setWar(warDirectory.resolve(warFile).toString());
webapp.setAttribute("org.eclipse.jetty.webapp.basetempdir", temporaryWarDir.toFile().getAbsolutePath());
// Set the default authenticator factory to avoid NPE due to the following commit:
// https://github.com/eclipse/jetty.project/commit/7e91d34177a880ecbe70009e8f200d02e3a0c5dd
webapp.getSecurityHandler().setAuthenticatorFactory(new DefaultAuthenticatorFactory());
webapp.setVirtualHosts(new String[]{virtualHost});
handlers.addHandler(webapp);
return webapp;
}
@Override
public void stop() throws Exception {
stop(false);
}
@Override
public void stop(boolean isShutdown) throws Exception {
if (isShutdown) {
internalStop();
}
}
public List<WebAppContext> getWebContexts() {
return this.webContexts;
}
}
| |
// Copyright 2010 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.testing.junit.runner.model;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import com.google.testing.junit.junit4.runner.DynamicTestException;
import com.google.testing.junit.runner.sharding.ShardingEnvironment;
import com.google.testing.junit.runner.sharding.ShardingFilters;
import com.google.testing.junit.runner.util.TestIntegrationsRunnerIntegration;
import com.google.testing.junit.runner.util.TestPropertyRunnerIntegration;
import com.google.testing.junit.runner.util.Ticker;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import javax.inject.Inject;
import org.junit.runner.Description;
import org.junit.runner.manipulation.Filter;
/**
* Model of the tests that will be run. The model is agnostic of the particular
* type of test run (JUnit3 or JUnit4). The test runner uses this class to build
* the model, and then updates the model during the test run.
*
* <p>The leaf nodes in the model are test cases; the other nodes are test suites.
*/
public class TestSuiteModel {
private final TestSuiteNode rootNode;
private final Map<Description, TestCaseNode> testCaseMap;
private final Map<Description, TestNode> testsMap;
private final Ticker ticker;
private final AtomicBoolean wroteXml = new AtomicBoolean(false);
private final XmlResultWriter xmlResultWriter;
@Nullable private final Filter shardingFilter;
private TestSuiteModel(Builder builder) {
rootNode = builder.rootNode;
testsMap = builder.testsMap;
testCaseMap = filterTestCases(builder.testsMap);
ticker = builder.ticker;
shardingFilter = builder.shardingFilter;
xmlResultWriter = builder.xmlResultWriter;
}
// VisibleForTesting
public List<TestNode> getTopLevelTestSuites() {
return rootNode.getChildren();
}
// VisibleForTesting
Description getTopLevelDescription() {
return rootNode.getDescription();
}
/**
* Gets the sharding filter to use; {@link Filter#ALL} if not sharding.
*/
public Filter getShardingFilter() {
return shardingFilter;
}
/**
* Returns the test case node with the given test description.<p>
*
* Note that in theory this should never return {@code null}, but
* if it did we would not want to throw a {@code NullPointerException}
* because JUnit4 would catch the exception and remove our test
* listener!
*/
private TestCaseNode getTestCase(Description description) {
// The description shouldn't be null, but in the test runner code we avoid throwing exceptions.
return description == null ? null : testCaseMap.get(description);
}
private TestNode getTest(Description description) {
// The description shouldn't be null, but in the test runner code we avoid throwing exceptions.
return description == null ? null : testsMap.get(description);
}
// VisibleForTesting
public int getNumTestCases() {
return testCaseMap.size();
}
/**
* Indicate that the test run has started. This should be called after all
* filtering has been completed.
*
* @param topLevelDescription the root {@link Description} node.
*/
public void testRunStarted(Description topLevelDescription) {
markChildrenAsPending(topLevelDescription);
}
private void markChildrenAsPending(Description node) {
if (node.isTest()) {
testPending(node);
} else {
for (Description child : node.getChildren()) {
markChildrenAsPending(child);
}
}
}
/**
* Indicate that the test case with the given key is scheduled to start.
*
* @param description key for a test case
*/
private void testPending(Description description) {
TestCaseNode testCase = getTestCase(description);
if (testCase != null) {
testCase.pending();
}
}
/**
* Indicate that the test case with the given key has started.
*
* @param description key for a test case
*/
public void testStarted(Description description) {
TestCaseNode testCase = getTestCase(description);
if (testCase != null) {
testCase.started(currentMillis());
TestPropertyRunnerIntegration.setTestCaseForThread(testCase);
TestIntegrationsRunnerIntegration.setTestCaseForThread(testCase);
}
}
/**
* Indicate that the entire test run was interrupted.
*/
public void testRunInterrupted() {
rootNode.testInterrupted(currentMillis());
}
/**
* Indicate that the test case with the given key has requested that
* a property be written in the XML.<p>
*
* @param description key for a test case
* @param name The property name.
* @param value The property value.
*/
public void testEmittedProperty(Description description, String name, String value) {
TestCaseNode testCase = getTestCase(description);
if (testCase != null) {
testCase.exportProperty(name, value);
}
}
/**
* Adds a failure to the test with the given key. If the specified test is suite, the failure
* will be added to all its children.
*
* @param description key for a test case
*/
public void testFailure(Description description, Throwable throwable) {
TestNode test = getTest(description);
if (test != null) {
if (throwable instanceof DynamicTestException) {
DynamicTestException dynamicFailure = (DynamicTestException) throwable;
test.dynamicTestFailure(
dynamicFailure.getTest(), dynamicFailure.getCause(), currentMillis());
} else {
test.testFailure(throwable, currentMillis());
}
}
}
/**
* Indicates that the test case with the given key was skipped
*
* @param description key for a test case
*/
public void testSkipped(Description description) {
TestNode test = getTest(description);
if (test != null) {
test.testSkipped(currentMillis());
}
}
/**
* Indicates that the test case with the given key was ignored or suppressed
*
* @param description key for a test case
*/
public void testSuppressed(Description description) {
TestNode test = getTest(description);
if (test != null) {
test.testSuppressed(currentMillis());
}
}
/**
* Indicate that the test case with the given description has finished.
*/
public void testFinished(Description description) {
TestCaseNode testCase = getTestCase(description);
if (testCase != null) {
testCase.finished(currentMillis());
}
/*
* Note: we don't call TestPropertyExporter, so if any properties are
* exported before the next test runs, they will be associated with the
* current test.
*/
}
private long currentMillis() {
return NANOSECONDS.toMillis(ticker.read());
}
/**
* Writes the model to XML
*
* @param outputStream stream to output to
* @throws IOException if the underlying writer throws an exception
*/
public void writeAsXml(OutputStream outputStream) throws IOException {
write(new XmlWriter(outputStream));
}
// VisibleForTesting
void write(XmlWriter writer) throws IOException {
if (wroteXml.compareAndSet(false, true)) {
xmlResultWriter.writeTestSuites(writer, rootNode.getResult());
}
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof TestSuiteModel)) {
return false;
}
TestSuiteModel that = (TestSuiteModel) obj;
// We only use this for testing, so using toString() is good enough
return this.toString().equals(that.toString());
}
@Override
public String toString() {
try {
StringWriter stringWriter = new StringWriter();
write(XmlWriter.createForTesting(stringWriter));
return stringWriter.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* A builder for creating a model of a test suite.
*/
public static class Builder {
private final Ticker ticker;
private final Map<Description, TestNode> testsMap = new ConcurrentHashMap<>();
private final ShardingEnvironment shardingEnvironment;
private final ShardingFilters shardingFilters;
private final XmlResultWriter xmlResultWriter;
private TestSuiteNode rootNode;
private Filter shardingFilter = Filter.ALL;
private boolean buildWasCalled = false;
@Inject
public Builder(Ticker ticker, ShardingFilters shardingFilters,
ShardingEnvironment shardingEnvironment, XmlResultWriter xmlResultWriter) {
this.ticker = ticker;
this.shardingFilters = shardingFilters;
this.shardingEnvironment = shardingEnvironment;
this.xmlResultWriter = xmlResultWriter;
}
/**
* Build a model with the given name, including the given suites. This method
* should be called before any command line filters are applied.
*/
public TestSuiteModel build(String suiteName, Description... topLevelSuites) {
if (buildWasCalled) {
throw new IllegalStateException("Builder.build() was already called");
}
buildWasCalled = true;
if (shardingEnvironment.isShardingEnabled()) {
shardingFilter = getShardingFilter(topLevelSuites);
}
rootNode = new TestSuiteNode(Description.createSuiteDescription(suiteName));
for (Description topLevelSuite : topLevelSuites) {
addTestSuite(rootNode, topLevelSuite);
rootNode.getDescription().addChild(topLevelSuite);
}
return new TestSuiteModel(this);
}
private Filter getShardingFilter(Description... topLevelSuites) {
Collection<Description> tests = new LinkedList<>();
for (Description suite : topLevelSuites) {
collectTests(suite, tests);
}
shardingEnvironment.touchShardFile();
return shardingFilters.createShardingFilter(tests);
}
private static void collectTests(Description desc, Collection<Description> tests) {
if (desc.isTest()) {
tests.add(desc);
} else {
for (Description child : desc.getChildren()) {
collectTests(child, tests);
}
}
}
private void addTestSuite(TestSuiteNode parentSuite, Description suiteDescription) {
TestSuiteNode suite = new TestSuiteNode(suiteDescription);
for (Description childDesc : suiteDescription.getChildren()) {
if (childDesc.isTest()) {
addTestCase(suite, childDesc);
} else {
addTestSuite(suite, childDesc);
}
}
// Empty suites are pruned when sharding.
if (shardingFilter == Filter.ALL || !suite.getChildren().isEmpty()) {
parentSuite.addTestSuite(suite);
testsMap.put(suiteDescription, suite);
}
}
private void addTestCase(TestSuiteNode parentSuite, Description testCaseDesc) {
if (!testCaseDesc.isTest()) {
throw new IllegalArgumentException();
}
if (!shardingFilter.shouldRun(testCaseDesc)) {
return;
}
TestCaseNode testCase = new TestCaseNode(testCaseDesc, parentSuite);
testsMap.put(testCaseDesc, testCase);
parentSuite.addTestCase(testCase);
}
}
/**
* Converts the values of the Map from {@link TestNode} to {@link TestCaseNode} filtering out null
* values.
*/
private static Map<Description, TestCaseNode> filterTestCases(Map<Description, TestNode> tests) {
Map<Description, TestCaseNode> filteredAndConvertedTests = new HashMap<>();
for (Description key : tests.keySet()) {
TestNode testNode = tests.get(key);
if (testNode instanceof TestCaseNode) {
filteredAndConvertedTests.put(key, (TestCaseNode) testNode);
}
}
return filteredAndConvertedTests;
}
}
| |
package com.example.SaveChameleon;
import android.app.*;
import android.content.DialogInterface;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import com.akexorcist.roundcornerprogressbar.RoundCornerProgressBar;
import com.example.SaveChameleon.fragment.FourButtonFragment;
import com.example.SaveChameleon.fragment.NineButtonFragment;
import com.example.SaveChameleon.fragment.SixButtonFragment;
import com.example.SaveChameleon.view.AnimationView;
import java.util.*;
public class MainActivity extends Activity {
public AnimationView animationView;
LinearLayout backgroundLayout;
List<Integer> colors;
FragmentManager fragmentManager;
public List<Button> buttons;
int buttonNum = 4;
//generate random color algorithm parameter
int randomColorGap,randomColorRange;
int rightButton;
public int choosedButton;
//indicate which button's color is same with background
int whichButton;
public Timer timer;
public TimerTask timeOutTask,timeBarTask,frogDisappearTask,rightChoiceTask,wrongChoiceTask;
float actionBarValue;
//indicate if the timeBar is moving
public boolean isRun = true;
//to get the selected button color
public ColorDrawable frogColorDrawable;
public int frogColor;
public int timeOutNum = 0;
int selectRightNum = 0;
public static final int TIMEOUT = 0;
public static final int TIMEBARMOVE = 1;
public static final int FROGDISAPPEAR = 2;
public static final int RIGHTCHOICE = 3;
public static final int WRONGCHOICE = 4;
private RoundCornerProgressBar timeBar;
//to mark the time when pause button be click
long pauseRestTime = 0;
long lastExecuteTime;
Point point;
Handler handler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
timer = new Timer();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case TIMEOUT:
timeBarReset();
changeUIColor();
animationView.startAnimation();
timeOutNum++;
if (timeOutNum == 5){
timeOutTask.cancel();
timeBarTask.cancel();
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setIcon(R.drawable.frog);
dialog.setTitle("FUNK ONE MORE TIME");
dialog.setCancelable(false);
dialog.setNegativeButton("YEAH", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
animationView.initView(point.x);
timeOutNum = 0;
selectRightNum = 0;
changeFragment(4);
timeOutTask = new TimeOutTask();
timeBarTask = new TimeBarMoveTask();
timer.schedule(timeOutTask,0,5000);
timer.schedule(timeBarTask,0,50);
}
});
dialog.setPositiveButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
onDestroy();
onBackPressed();
}
});
dialog.show();
}
break;
case TIMEBARMOVE:
timeBarMove();
break;
case FROGDISAPPEAR:
animationView.decreaseAlpha();
break;
case RIGHTCHOICE:
selectRightNum++;
newRound(true);
break;
case WRONGCHOICE:
newRound(false);
break;
}
}
};
timeOutTask = new TimeOutTask();
timeBarTask = new TimeBarMoveTask();
fragmentManager = getFragmentManager();
colors = new ArrayList<>();
point = new Point();
getWindowManager().getDefaultDisplay().getSize(point);
animationView = new AnimationView(this,point.x);
setContentView(R.layout.main);
backgroundLayout = (LinearLayout)findViewById(R.id.animation_layout);
backgroundLayout.addView(animationView);
timeBar = (RoundCornerProgressBar)findViewById(R.id.time_bar);
Button pauseButton = (Button)findViewById(R.id.pause_button);
buttons = new ArrayList<>();
changeFragment(4);
randomColorGap = 30;
randomColorRange = 8;
timer.schedule(timeOutTask,0,5000);
timer.schedule(timeBarTask,0,50);
pauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionBarValue = timeBar.getProgress();
long currentTime = System.currentTimeMillis();
pauseRestTime =pauseRestTime + currentTime-lastExecuteTime;
timeOutTask.cancel();
timeBarTask.cancel();
timeOutTask = new TimeOutTask();
timeBarTask = new TimeBarMoveTask();
if (!isRun) {
if (choosedButton == rightButton) {
rightChoiceTask.cancel();
} else {
wrongChoiceTask.cancel();
}
}
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setIcon(R.drawable.frog);
dialog.setTitle("CONTINUE");
dialog.setCancelable(false);
dialog.setNegativeButton("YEAH", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
lastExecuteTime = System.currentTimeMillis();
if (isRun){
timeBar.setProgress(actionBarValue);
timer.schedule(timeBarTask,0,50);
timer.schedule(timeOutTask,(long)5000-pauseRestTime);
}else {
if (choosedButton == rightButton) {
rightChoiceTask = new RightChoiceTask();
timer.schedule(rightChoiceTask, 0);
} else {
wrongChoiceTask = new WrongChoiceTask();
timer.schedule(wrongChoiceTask, 0);
}
}
}
});
dialog.show();
}
});
}
private void genRandomColor(int num){
colors.clear();
int red = (int)(30 + Math.random() * 190);
int green = (int)(30 + Math.random() * 190);
int blue = (int)(30 + Math.random() * 190);
int baseColor = 0xff000000 | red << 16 | green << 8 | blue;
colors.add(baseColor);
int temporaryR,temporaryG,temporaryB,temporaryColor;
for (int i = 1;i<num;i++){
temporaryR = red + (int)(Math.random()*2*randomColorGap - randomColorGap);
temporaryG = green + (int)(Math.random()*2*randomColorGap - randomColorGap);
temporaryB = blue + (int)(Math.random()*2*randomColorGap - randomColorGap);
temporaryColor = 0xff000000 | temporaryR << 16 | temporaryG << 8 | temporaryB;
// temporaryR = red + (int)(Math.random()*(randomColorGap) + randomColorRange);
// red = temporaryR;
// temporaryG = green + (int)(Math.random()*(randomColorGap) + randomColorRange);
// green = temporaryG;
// temporaryB = blue + (int)(Math.random()*(randomColorGap) + randomColorRange);
// blue = temporaryB;
// temporaryColor = 0xff000000 | temporaryR << 16 | temporaryG << 8 | temporaryB;
colors.add(temporaryColor);
}
}
public void judge(){
if (timeOutNum<5 && isRun) {
timeBarTask.cancel();
timeBarTask = new TimeBarMoveTask();
timeOutTask.cancel();
timeOutTask = new TimeOutTask();
isRun = false;
if (choosedButton == rightButton) {
frogDisappearTask = new FrogDisappearTask();
timer.schedule(frogDisappearTask, 0, 10);
rightChoiceTask = new RightChoiceTask();
timer.schedule(rightChoiceTask, 2000);
} else {
animationView.changFrogColor(frogColor);
wrongChoiceTask = new WrongChoiceTask();
timer.schedule(wrongChoiceTask, 2000);
}
}
}
private void changeUIColor(){
genRandomColor(buttonNum);
backgroundLayout.setBackgroundColor(colors.get(0));
whichButton = (int)(Math.random() * colors.size());
rightButton = whichButton;
for (int i = 0;i<colors.size();i++){
buttons.get(whichButton%(colors.size())).setBackgroundColor(colors.get(i));
whichButton++;
}
}
private void newRound(boolean isRight){
timer.schedule(timeBarTask,0,50);
lastExecuteTime = System.currentTimeMillis();
isRun = true;
if (isRight) {
if (selectRightNum == 4){
changeFragment(6);
}
if (selectRightNum == 8){
changeFragment(9);
}
pauseRestTime = 0;
timeBarReset();
frogDisappearTask.cancel();
changeUIColor();
animationView.changFrogColor(frogColor);
timer.schedule(timeOutTask, 5000, 5000);
}else {
timer.schedule(timeOutTask, 0, 5000);
}
}
private void timeBarMove(){
timeBar.setProgress(timeBar.getProgress() + 1);
}
private void timeBarReset(){
timeBar.setProgress(0);
}
// public void setButtonListen(){
// for (Button b: buttons){
// b.setOnClickListener(this);
// }
// }
private void changeFragment(int i){
switch (i){
case 4:
FourButtonFragment fourButtonFragment = new FourButtonFragment();
FragmentTransaction transaction4 = fragmentManager.beginTransaction();
transaction4.replace(R.id.button_layout,fourButtonFragment);
transaction4.commit();
fragmentManager.executePendingTransactions();
buttonNum = 4;
break;
case 6:
SixButtonFragment sixButtonFragment = new SixButtonFragment();
FragmentTransaction transaction6 = fragmentManager.beginTransaction();
transaction6.replace(R.id.button_layout,sixButtonFragment);
transaction6.commit();
fragmentManager.executePendingTransactions();
buttonNum = 6;
randomColorGap = 20;
randomColorRange = 6;
break;
case 9:
NineButtonFragment nineButtonFragment = new NineButtonFragment();
FragmentTransaction transaction9 = fragmentManager.beginTransaction();
transaction9.replace(R.id.button_layout,nineButtonFragment);
transaction9.commit();
fragmentManager.executePendingTransactions();
buttonNum = 9;
randomColorGap = 10;
randomColorRange = 2;
break;
}
}
class TimeOutTask extends TimerTask{
@Override
public void run() {
Message message = new Message();
message.what = TIMEOUT;
handler.sendMessage(message);
lastExecuteTime = scheduledExecutionTime();
pauseRestTime = 0;
}
}
class TimeBarMoveTask extends TimerTask{
@Override
public void run() {
Message message = new Message();
message.what = TIMEBARMOVE;
handler.sendMessage(message);
}
}
class FrogDisappearTask extends TimerTask{
@Override
public void run() {
Message message = new Message();
message.what = FROGDISAPPEAR;
handler.sendMessage(message);
}
}
class RightChoiceTask extends TimerTask{
@Override
public void run() {
Message message = new Message();
message.what = RIGHTCHOICE;
handler.sendMessage(message);
}
}
class WrongChoiceTask extends TimerTask{
@Override
public void run() {
Message message = new Message();
message.what = WRONGCHOICE;
handler.sendMessage(message);
}
}
@Override
protected void onDestroy() {
timer.cancel();
super.onDestroy();
}
}
| |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eas.designer.application.query.result;
import com.eas.client.DatabasesClient;
import com.eas.client.SQLUtils;
import com.eas.client.SqlQuery;
import com.eas.client.StoredQueryFactory;
import com.eas.client.changes.Change;
import com.eas.client.changes.ChangeValue;
import com.eas.client.changes.Delete;
import com.eas.client.changes.Insert;
import com.eas.client.changes.Update;
import com.eas.client.dataflow.FlowProvider;
import com.eas.client.dataflow.FlowProviderNotPagedException;
import com.eas.client.forms.components.model.ModelCheckBox;
import com.eas.client.forms.components.model.ModelDate;
import com.eas.client.forms.components.model.ModelFormattedField;
import com.eas.client.forms.components.model.ModelSpin;
import com.eas.client.forms.components.model.grid.ModelGrid;
import com.eas.client.forms.components.model.grid.columns.ModelColumn;
import com.eas.client.forms.components.model.grid.header.ModelGridColumn;
import com.eas.client.forms.components.model.grid.header.ServiceGridColumn;
import com.eas.client.metadata.DataTypeInfo;
import com.eas.client.metadata.Field;
import com.eas.client.metadata.Fields;
import com.eas.client.metadata.Parameter;
import com.eas.client.metadata.Parameters;
import com.eas.client.queries.LocalQueriesProxy;
import com.eas.client.queries.ScriptedQueryFactory;
import com.eas.client.scripts.JSObjectFacade;
import com.eas.designer.application.indexer.IndexerQuery;
import com.eas.designer.application.query.PlatypusQueryDataObject;
import com.eas.designer.application.query.editing.SqlTextEditsComplementor;
import com.eas.designer.explorer.project.PlatypusProjectImpl;
import com.eas.script.Scripts;
import com.eas.util.IDGenerator;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import jdk.nashorn.api.scripting.AbstractJSObject;
import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.internal.runtime.JSType;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.NamedParameter;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.Statement;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
import org.openide.util.RequestProcessor;
/**
*
* @author vv
*/
public class QueryResultsView extends javax.swing.JPanel {
private QuerySetupView querySetupView;
private ModelGrid grid;
private final DatabasesClient basesProxy;
private String queryText;
private Parameters parameters;
private SqlQuery query;
private FlowProvider flow;
private List<Change> changeLog;
private Insert lastInsert;
private JSObject lastInserted;
private static int queryIndex;
private static CCJSqlParserManager parserManager = new CCJSqlParserManager();
private static final String DEFAULT_TEXT_COLOR_KEY = "textText"; //NOI18N
private static final String VALUE_PREF_KEY = "value"; //NOI18N
private static final Logger logger = Logger.getLogger(QueryResultsView.class.getName());
private static final int[] pageSizes = {100, 200, 500, 1000};
private PageSizeItem[] pageSizeItems;
private int pageSize;
private String datasourceName;
private String queryName;
public QueryResultsView(DatabasesClient aBasesProxy, String aDatasourceName, String aSchemaName, String aTableName) throws Exception {
this(aBasesProxy, aDatasourceName, String.format(SQLUtils.TABLE_NAME_2_SQL, getTableName(aSchemaName, aTableName)));
setName(aTableName);
}
public QueryResultsView(PlatypusQueryDataObject aQueryDataObject) throws Exception {
this(aQueryDataObject.getBasesProxy(), aQueryDataObject.getDatasourceName(), extractText(aQueryDataObject));
for (Field sourceParam : aQueryDataObject.getModel().getParameters().toCollection()) {
Parameter p = parameters.get(sourceParam.getName());
if (p != null) {
p.setTypeInfo(sourceParam.getTypeInfo());
p.setMode(((Parameter) sourceParam).getMode());
}
}
setName(aQueryDataObject.getName());
queryName = IndexerQuery.file2AppElementId(aQueryDataObject.getPrimaryFile());
if (queryName != null && !queryName.isEmpty()) {
loadParametersValues();
}
}
public QueryResultsView(DatabasesClient aBasesProxy, String aDatasourceName, String aQueryText) throws Exception {
initComponents();
initPageSizes();
initCopyMessage();
basesProxy = aBasesProxy;
datasourceName = aDatasourceName;
queryText = aQueryText;
parseParameters();
setName(getGeneratedTitle());
}
protected static String extractText(PlatypusQueryDataObject aQueryDataObject) throws Exception {
String storedQueryText = aQueryDataObject.getSqlTextDocument().getText(0, aQueryDataObject.getSqlTextDocument().getLength());
String storedDialectQueryText = aQueryDataObject.getSqlFullTextDocument().getText(0, aQueryDataObject.getSqlFullTextDocument().getLength());
StoredQueryFactory factory = new ScriptedQueryFactory(aQueryDataObject.getBasesProxy(), aQueryDataObject.getProject().getQueries(), aQueryDataObject.getProject().getIndexer());
return factory.compileSubqueries(storedDialectQueryText != null && !storedDialectQueryText.isEmpty() ? storedDialectQueryText : storedQueryText, aQueryDataObject.getModel());
}
public void setPageSize(int aValue) {
pageSize = aValue;
}
public PageSizeItem[] getPageSizeItems() {
return pageSizeItems;
}
private static String getTableName(String aTableSchemaName, String aTableName) {
if (aTableName == null || aTableName.isEmpty()) {
throw new IllegalArgumentException("Table name is null or empty."); //NOI18N
}
return aTableSchemaName != null && !aTableSchemaName.isEmpty() ? String.format("%s.%s", aTableSchemaName, aTableName) : aTableName; //NOI18N
}
/**
*
* @return True if underlying suery is a select, false if it a insert,
* delete, update or stored procedure call
* @throws Exception
*/
private void initModel() throws Exception {
query = new SqlQuery(basesProxy, queryText);
query.setDatasourceName(datasourceName);
query.setPageSize(pageSize);
parameters.toCollection().stream().forEach((p) -> {
query.getParameters().add(p.copy());
});
try {
StoredQueryFactory factory = new StoredQueryFactory(basesProxy, null, null, false);
query.setCommand(!factory.putTableFieldsMetadata(query));
flow = query.compile().getFlowProvider();
changeLog = new ArrayList<>();
commitButton.setEnabled(!query.isCommand());
nextPageButton.setEnabled(!query.isCommand());
addButton.setEnabled(!query.isCommand());
deleteButton.setEnabled(!query.isCommand());
commitButton.setToolTipText(NbBundle.getMessage(QueryResultsView.class, "HINT_Commit"));
} catch (Exception ex) {
query.setFields(null);// We have to accept database's fields here.
commitButton.setEnabled(false);
nextPageButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
commitButton.setToolTipText(NbBundle.getMessage(QueryResultsView.class, "HINT_Uncommitable"));
}
refreshButton.setEnabled(true);
}
public String getQueryText() {
return queryText;
}
public void setQueryText(String aQueryText) {
queryText = aQueryText;
}
private String getGeneratedTitle() {
return String.format("%s %d", NbBundle.getMessage(QuerySetupView.class, "QueryResultsView.queryName"), ++queryIndex); //NOI18N
}
private void resetMessage() {
showInfo(""); // NOI18N
}
private void showInfo(final String aText) {
SwingUtilities.invokeLater(() -> {
messageLabel.setForeground(UIManager.getColor(DEFAULT_TEXT_COLOR_KEY));
messageLabel.setText(aText);
messageLabel.setCaretPosition(0);
});
}
private void showWarning(final String aText) {
SwingUtilities.invokeLater(() -> {
messageLabel.setForeground(Color.RED.darker());
messageLabel.setText(aText);
messageLabel.setCaretPosition(0);
});
}
private void showQueryResultsMessage() {
if (query.getFields() != null && grid.getData() != null) {
String message = String.format(NbBundle.getMessage(QuerySetupView.class, "QueryResultsView.resultMessage"), JSType.toInteger(grid.getData().getMember("length")));
List<Field> pks = query.getFields().getPrimaryKeys();
if (pks == null || pks.isEmpty()) {
message += "\n " + String.format(NbBundle.getMessage(QuerySetupView.class, "QueryResultsView.noKeysMessage"), query.getEntityName());
}
showInfo(message);
}
}
public void logParameters() throws Exception {
if (logger.isLoggable(Level.FINEST)) {
for (int i = 1; i <= parameters.getParametersCount(); i++) {
Parameter p = parameters.get(i);
logger.log(Level.FINEST, "Parameter {0} of type {1} is assigned with value: {2}", new Object[]{p.getName(), p.getTypeInfo().getSqlTypeName(), p.getValue()});
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
toolBar = new javax.swing.JToolBar();
refreshButton = new javax.swing.JButton();
nextPageButton = new javax.swing.JButton();
addButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
commitButton = new javax.swing.JButton();
runButton = new javax.swing.JButton();
verticalFiller = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 32767));
resultsPanel = new javax.swing.JPanel();
gridPanel = new javax.swing.JPanel();
footerPanel = new javax.swing.JPanel();
messageLabel = new javax.swing.JTextField();
setLayout(new java.awt.BorderLayout());
toolBar.setFloatable(false);
toolBar.setOrientation(javax.swing.SwingConstants.VERTICAL);
toolBar.setRollover(true);
refreshButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/eas/designer/application/query/result/refresh-records-btn.png"))); // NOI18N
refreshButton.setText(org.openide.util.NbBundle.getMessage(QueryResultsView.class, "QueryResultsView.refreshButton.text")); // NOI18N
refreshButton.setToolTipText(org.openide.util.NbBundle.getMessage(QueryResultsView.class, "refreshButton.Tooltip")); // NOI18N
refreshButton.setFocusable(false);
refreshButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
refreshButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
refreshButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshButtonActionPerformed(evt);
}
});
toolBar.add(refreshButton);
nextPageButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/eas/designer/application/query/result/next.png"))); // NOI18N
nextPageButton.setText(org.openide.util.NbBundle.getMessage(QueryResultsView.class, "QueryResultsView.nextPageButton.text")); // NOI18N
nextPageButton.setToolTipText(org.openide.util.NbBundle.getMessage(QueryResultsView.class, "nextPageButton.Tooltip")); // NOI18N
nextPageButton.setFocusable(false);
nextPageButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
nextPageButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
nextPageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextPageButtonActionPerformed(evt);
}
});
toolBar.add(nextPageButton);
addButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/eas/designer/application/query/result/new.png"))); // NOI18N
addButton.setToolTipText(org.openide.util.NbBundle.getMessage(QueryResultsView.class, "QueryResultsView.addButton.toolTipText")); // NOI18N
addButton.setFocusable(false);
addButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
addButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
addButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
toolBar.add(addButton);
deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/eas/designer/application/query/result/delete.png"))); // NOI18N
deleteButton.setToolTipText(org.openide.util.NbBundle.getMessage(QueryResultsView.class, "QueryResultsView.deleteButton.toolTipText")); // NOI18N
deleteButton.setFocusable(false);
deleteButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
deleteButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
toolBar.add(deleteButton);
commitButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/eas/designer/application/query/result/commit-record-btn.png"))); // NOI18N
commitButton.setText(org.openide.util.NbBundle.getMessage(QueryResultsView.class, "QueryResultsView.commitButton.text")); // NOI18N
commitButton.setFocusable(false);
commitButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
commitButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
commitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commitButtonActionPerformed(evt);
}
});
toolBar.add(commitButton);
runButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/eas/designer/application/query/result/runsql.png"))); // NOI18N
runButton.setText(org.openide.util.NbBundle.getMessage(QueryResultsView.class, "QueryResultsView.runButton.text")); // NOI18N
runButton.setToolTipText(org.openide.util.NbBundle.getMessage(QueryResultsView.class, "runButton.Tooltip")); // NOI18N
runButton.setFocusable(false);
runButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
runButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
runButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runButtonActionPerformed(evt);
}
});
toolBar.add(runButton);
toolBar.add(verticalFiller);
add(toolBar, java.awt.BorderLayout.WEST);
resultsPanel.setLayout(new java.awt.BorderLayout());
gridPanel.setLayout(new java.awt.BorderLayout());
resultsPanel.add(gridPanel, java.awt.BorderLayout.CENTER);
footerPanel.setPreferredSize(new java.awt.Dimension(10, 22));
footerPanel.setLayout(new java.awt.BorderLayout());
messageLabel.setEditable(false);
messageLabel.setBorder(null);
messageLabel.setOpaque(false);
footerPanel.add(messageLabel, java.awt.BorderLayout.CENTER);
resultsPanel.add(footerPanel, java.awt.BorderLayout.SOUTH);
add(resultsPanel, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runButtonActionPerformed
try {
showQuerySetupDialog();
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}//GEN-LAST:event_runButtonActionPerformed
private Runnable disableButtons() {
boolean rEnabled = refreshButton.isEnabled();
boolean nEnabled = nextPageButton.isEnabled();
boolean aEnabled = addButton.isEnabled();
boolean dEnabled = deleteButton.isEnabled();
boolean cEnabled = commitButton.isEnabled();
boolean rrEnabled = runButton.isEnabled();
refreshButton.setEnabled(false);
nextPageButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
commitButton.setEnabled(false);
runButton.setEnabled(false);
boolean gInsertable = grid != null ? grid.isInsertable() : false;
boolean gEditable = grid != null ? grid.isEditable() : false;
boolean gDeletable = grid != null ? grid.isDeletable() : false;
if (grid != null) {
grid.setInsertable(false);
grid.setEditable(false);
grid.setDeletable(false);
}
return () -> {
refreshButton.setEnabled(rEnabled);
nextPageButton.setEnabled(nEnabled);
addButton.setEnabled(aEnabled);
deleteButton.setEnabled(dEnabled);
commitButton.setEnabled(cEnabled);
runButton.setEnabled(rrEnabled);
if (grid != null) {
grid.setInsertable(gInsertable);
grid.setEditable(gEditable);
grid.setDeletable(gDeletable);
}
};
}
private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
if (query != null) {
final Runnable reEnableButtons = disableButtons();
RequestProcessor.getDefault().execute(() -> {
final ProgressHandle ph = ProgressHandleFactory.createHandle(getName());
ph.start();
try {
if (query.isCommand()) {
int rowsAffected = basesProxy.executeUpdate(query.compile(), null, null);
showInfo(NbBundle.getMessage(QuerySetupView.class, "QueryResultsView.affectedRowsMessage", rowsAffected));
EventQueue.invokeLater(() -> {
reEnableButtons.run();
gridPanel.revalidate();
gridPanel.repaint();
});
} else {
changeLog = new ArrayList<>();
if (flow != null) {
Collection<Map<String, Object>> fetched = flow.refresh(query.compile().getParameters(), null, null);
EventQueue.invokeLater(() -> {
Scripts.Space space = PlatypusProjectImpl.getJsSpace();
JSObject jsFetched = space.readJsArray(fetched);
JSObject processed = processData(jsFetched, space);
grid.setData(processed);
showQueryResultsMessage();
EventQueue.invokeLater(() -> {
reEnableButtons.run();
nextPageButton.setEnabled(true);
gridPanel.revalidate();
gridPanel.repaint();
});
});
}
}
} catch (Exception ex) {
showWarning(ex.getMessage() != null ? ex.getMessage() : ex.toString()); //NO1I18N
runButton.setEnabled(true);
} finally {
ph.finish();
}
});
}
}//GEN-LAST:event_refreshButtonActionPerformed
protected void generateChangeLogKeys(List<ChangeValue> aKeys, JSObject aSubject, String propName, Object oldValue) {
if (query != null) {
Fields fields = query.getFields();
for (int i = 1; i <= fields.getFieldsCount(); i++) {
Field field = fields.get(i);
if (field.isPk()) {
String fieldName = field.getName();
Object value = aSubject.getMember(fieldName);
// Some tricky processing of primary keys modification case ...
if (fieldName.equalsIgnoreCase(propName)) {
value = oldValue;
}
aKeys.add(new ChangeValue(fieldName, value, field.getTypeInfo()));
}
}
}
}
protected void generateChangeLogData(List<ChangeValue> aData, JSObject aSubject) {
if (query != null) {
Fields fields = query.getFields();
for (int i = 1; i <= fields.getFieldsCount(); i++) {
Field field = fields.get(i);
String fieldName = field.getName();
Object value = aSubject.getMember(fieldName);
if (JSType.nullOrUndefined(value) && field.isPk() && !field.isFk()) {
value = field.getTypeInfo().generateValue();
aSubject.setMember(fieldName, value);
}
if (!JSType.nullOrUndefined(value)) {
aData.add(new ChangeValue(fieldName, value, field.getTypeInfo()));
}
}
}
}
protected class JSWrapper extends JSObjectFacade {
public JSWrapper(JSObject aDelegate) {
super(aDelegate);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof JSObjectFacade) {
obj = ((JSObjectFacade) obj).getDelegate();
}
return getDelegate().equals(obj);
}
@Override
public int hashCode() {
return getDelegate().hashCode();
}
@Override
public void setMember(String name, Object value) {
Field field = query.getFields().get(name);
if (field != null) {
Object oldValue = super.getMember(name);
super.setMember(name, value);
boolean complemented = false;
if (!field.isNullable() && lastInsert != null && lastInserted.equals(this)) {
boolean met = false;
for (int d = 0; d < lastInsert.getData().size(); d++) {
ChangeValue chv = lastInsert.getData().get(d);
if (chv.getName().equalsIgnoreCase(name)) {
met = true;
break;
}
}
if (!met) {
lastInsert.getData().add(new ChangeValue(name, value, field.getTypeInfo()));
complemented = true;
}
}
if (!complemented) {
Update update = new Update("");
generateChangeLogKeys(update.getKeys(), getDelegate(), name, oldValue);
update.getData().add(new ChangeValue(name, value, field.getTypeInfo()));
changeLog.add(update);
}
}
}
}
protected JSObject processData(JSObject aSubject, Scripts.Space aSpace) {
JSObject processed = new JSObjectFacade(aSubject) {
@Override
public Object getMember(String name) {
if ("splice".equals(name)) {
JSObject jsSplice = (JSObject) super.getMember(name);
return new JSObjectFacade(jsSplice) {
@Override
public Object call(Object thiz, Object... args) {
Object res = super.call(thiz instanceof JSObjectFacade ? ((JSObjectFacade) thiz).getDelegate() : thiz, args);
if (res instanceof JSObject) {
JSObject jsDeleted = (JSObject) res;
int deletedLength = JSType.toInteger(jsDeleted.getMember("length"));
for (int i = 0; i < deletedLength; i++) {
JSObject jsDeletedItem = (JSObject) jsDeleted.getSlot(i);
Delete delete = new Delete("");
generateChangeLogKeys(delete.getKeys(), jsDeletedItem, null, null);
changeLog.add(delete);
}
}
for (int i = 2; i < args.length; i++) {
Insert insert = new Insert("");
JSObject jsSubject = (JSObject) args[i];
if (jsSubject instanceof JSWrapper) {
jsSubject = ((JSWrapper) jsSubject).getDelegate();
}
generateChangeLogData(insert.getData(), jsSubject);
changeLog.add(insert);
lastInsert = insert;
lastInserted = (JSObject) args[i];
}
return res;
}
};
} else {
return super.getMember(name);
}
}
@Override
public Object getSlot(int index) {
Object slot = super.getSlot(index);
return JSType.nullOrUndefined(slot) || slot instanceof JSObjectFacade ? slot : new JSWrapper((JSObject) slot);
}
};
int length = JSType.toInteger(processed.getMember("length"));
processed.setMember(CURSOR_PROP_NAME, length > 0 ? processed.getSlot(0) : null);
processed.setMember("elementClass", new AbstractJSObject() {
@Override
public boolean isFunction() {
return true;
}
@Override
public Object newObject(Object... args) {
return new JSWrapper(aSpace.makeObj());
}
});
return processed;
}
private void commitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commitButtonActionPerformed
try {
if (query != null && !changeLog.isEmpty()) {
final Runnable reEnableButtons = disableButtons();
final String entityName = IDGenerator.genID() + "";
query.setEntityName(entityName);
changeLog.forEach((Change aChange) -> {
aChange.entityName = entityName;
});
((LocalQueriesProxy) basesProxy.getQueries()).putCachedQuery(entityName, query);
RequestProcessor.getDefault().execute(() -> {
final ProgressHandle ph = ProgressHandleFactory.createHandle(getName());
ph.start();
try {
int rowsAffected = basesProxy.commit(Collections.singletonMap(query.getDatasourceName(), changeLog), null, null);
showInfo(NbBundle.getMessage(QueryResultsView.class, "DataSaved") + ". " + NbBundle.getMessage(QueryResultsView.class, "QueryResultsView.affectedRowsMessage", rowsAffected));
} catch (Exception ex) {
showInfo(ex.getMessage()); //NO1I18N
} finally {
ph.finish();
EventQueue.invokeLater(() -> {
((LocalQueriesProxy) basesProxy.getQueries()).clearCachedQuery(entityName);
changeLog = new ArrayList<>();
reEnableButtons.run();
});
}
});
} else {
resetMessage();
}
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_commitButtonActionPerformed
private void nextPageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextPageButtonActionPerformed
if (flow != null) {
final Runnable reEnableButtons = disableButtons();
RequestProcessor.getDefault().execute(() -> {
try {
Collection<Map<String, Object>> fetched = flow.nextPage(null, null);
EventQueue.invokeLater(() -> {
Scripts.Space space = PlatypusProjectImpl.getJsSpace();
JSObject jsFetched = space.readJsArray(fetched);
int length = JSType.toInteger(jsFetched.getMember("length"));
if (length > 0) {
JSObject processed = processData(jsFetched, space);
grid.setData(processed);
showQueryResultsMessage();
}
reEnableButtons.run();
gridPanel.revalidate();
gridPanel.repaint();
});
} catch (Exception ex) {
EventQueue.invokeLater(() -> {
reEnableButtons.run();
nextPageButton.setEnabled(false);
gridPanel.revalidate();
gridPanel.repaint();
});
if (!(ex instanceof FlowProviderNotPagedException)) {
Exceptions.printStackTrace(ex);
}
}
});
}
}//GEN-LAST:event_nextPageButtonActionPerformed
protected static final String CURSOR_PROP_NAME = "cursor";
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
grid.insertElementAtCursor();
}//GEN-LAST:event_addButtonActionPerformed
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
grid.deleteSelectedElements();
}//GEN-LAST:event_deleteButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addButton;
private javax.swing.JButton commitButton;
private javax.swing.JButton deleteButton;
private javax.swing.JPanel footerPanel;
private javax.swing.JPanel gridPanel;
private javax.swing.JTextField messageLabel;
private javax.swing.JButton nextPageButton;
private javax.swing.JButton refreshButton;
private javax.swing.JPanel resultsPanel;
private javax.swing.JButton runButton;
private javax.swing.JToolBar toolBar;
private javax.swing.Box.Filler verticalFiller;
// End of variables declaration//GEN-END:variables
public void runQuery() throws Exception {
assert parameters != null : "Parameters must be initialized."; //NOI18N
if (!parameters.isEmpty()) {
showQuerySetupDialog();
} else {
requestExecuteQuery();
}
}
private void showQuerySetupDialog() {
try {
if (querySetupView == null) {
querySetupView = new QuerySetupView(this);
}
DialogDescriptor nd = new DialogDescriptor(querySetupView, getName());
Dialog dlg = DialogDisplayer.getDefault().createDialog(nd);
dlg.setModal(true);
querySetupView.setDialog(dlg, nd);
dlg.setVisible(true);
if (DialogDescriptor.OK_OPTION.equals(nd.getValue())) {
queryText = querySetupView.getSqlText();
parameters = querySetupView.acceptParametersValues();
logParameters();
if (queryName != null && !queryName.isEmpty() && querySetupView.isSaveParamsValuesEnabled()) {
saveParametersValues();
}
requestExecuteQuery();
}
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
private void requestExecuteQuery() throws Exception {
resetMessage();
refresh();
}
/**
*
* @return True if results grid is initialized and false if dml query has
* been executed
* @throws Exception
*/
private void refresh() throws Exception {
initModel();
gridPanel.removeAll();
if (!query.isCommand()) {
initModelGrid();
}
refreshButtonActionPerformed(null);
}
private void initModelGrid() throws Exception {
grid = new ModelGrid();
grid.setAutoRefreshHeader(false);
gridPanel.add(grid);
Fields fields = query.getFields();
if (fields != null) {
for (int i = 1; i <= fields.getFieldsCount(); i++) {
Field columnField = fields.get(i);
ModelGridColumn columnNode = new ModelGridColumn();
grid.addColumnNode(columnNode);
ModelColumn column = (ModelColumn) columnNode.getTableColumn();
int lwidth = 80;
if (lwidth >= columnNode.getWidth()) {
columnNode.setWidth(lwidth);
}
String description = columnField.getDescription();
if (description != null && !description.isEmpty()) {
columnNode.setTitle(description);
} else {
columnNode.setTitle(columnField.getName());
}
columnNode.setField(columnField.getName());
switch (columnField.getTypeInfo().getSqlType()) {
// Numbers
case java.sql.Types.NUMERIC:
case java.sql.Types.BIGINT:
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.INTEGER:
case java.sql.Types.REAL:
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT: {
ModelSpin editor = new ModelSpin();
editor.setMin(-Double.MAX_VALUE);
editor.setMax(Double.MAX_VALUE);
ModelSpin view = new ModelSpin();
view.setMin(-Double.MAX_VALUE);
view.setMax(Double.MAX_VALUE);
column.setEditor(editor);
column.setView(view);
break;
}
// Logical
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
column.setEditor(new ModelCheckBox());
column.setView(new ModelCheckBox());
break;
// Date and time
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP: {
ModelDate editor = new ModelDate();
editor.setDateFormat("dd.MM.yyyy HH:mm:ss.SSS");
ModelDate view = new ModelDate();
view.setDateFormat("dd.MM.yyyy HH:mm:ss.SSS");
column.setEditor(editor);
column.setView(view);
break;
}
default:
column.setEditor(new ModelFormattedField());
column.setView(new ModelFormattedField());
break;
}
column.getEditor().setNullable(columnField.isNullable());
}
List<Field> pks = query.getFields().getPrimaryKeys();
grid.setEditable(pks != null && !pks.isEmpty());
grid.setDeletable(pks != null && !pks.isEmpty());
deleteButton.setEnabled(pks != null && !pks.isEmpty());
if (!deleteButton.isEnabled()) {
showInfo(String.format(NbBundle.getMessage(QuerySetupView.class, "QueryResultsView.noKeysMessage"), query.getEntityName()));
}
}
grid.setAutoRefreshHeader(true);
grid.insertColumnNode(0, new ServiceGridColumn());
}
public Parameters getParameters() {
return parameters;
}
private void parseParameters() throws JSQLParserException {
Statement statement = parserManager.parse(new StringReader(queryText));
parameters = new Parameters();
Set<NamedParameter> parsedParameters = SqlTextEditsComplementor.extractParameters(statement);
parsedParameters.stream().forEach((NamedParameter parsedParameter) -> {
Parameter newParameter = new Parameter(parsedParameter.getName());
newParameter.setMode(1);
newParameter.setTypeInfo(DataTypeInfo.VARCHAR);
newParameter.setValue("");
parameters.add(newParameter);
});
}
private void initPageSizes() {
pageSizeItems = new PageSizeItem[pageSizes.length];
for (int i = 0; i < pageSizeItems.length; i++) {
pageSizeItems[i] = new PageSizeItem(pageSizes[i]);
}
pageSize = pageSizes[0];
}
private void initCopyMessage() {
final JPopupMenu menu = new JPopupMenu();
final JMenuItem copyItem = new JMenuItem(NbBundle.getMessage(QuerySetupView.class, "QueryResultsView.copyMessage")); //NOI18N
copyItem.addActionListener((ActionEvent e) -> {
StringSelection stringSelection = new StringSelection(messageLabel.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
});
menu.add(copyItem);
messageLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
}
private void loadParametersValues() {
Preferences modulePreferences = NbPreferences.forModule(QueryResultsView.class);
Preferences paramsPreferences = modulePreferences.node(queryName);
for (Field pField : parameters.toCollection()) {
Parameter parameter = (Parameter) pField;
Preferences paramNode = paramsPreferences.node(parameter.getName());
try {
int sqlType = parameter.getTypeInfo().getSqlType();
if (sqlType == java.sql.Types.DATE || sqlType == java.sql.Types.TIME || sqlType == java.sql.Types.TIME_WITH_TIMEZONE || sqlType == java.sql.Types.TIMESTAMP
|| sqlType == java.sql.Types.TIMESTAMP_WITH_TIMEZONE) {
long lValue = paramNode.getLong(VALUE_PREF_KEY, -1);
if (lValue != -1) {
parameter.setValue(new Date(lValue));
}
} else if (SQLUtils.getTypeGroup(sqlType) == SQLUtils.TypesGroup.LOGICAL) {
paramNode.getBoolean(VALUE_PREF_KEY, false);
} else if (SQLUtils.getTypeGroup(sqlType) == SQLUtils.TypesGroup.NUMBERS) {
paramNode.getDouble(VALUE_PREF_KEY, 0d);
} else {
Object val = paramNode.get(VALUE_PREF_KEY, ""); //NOI18N
if (val != null) {
((Parameter) parameter).setValue(val);
}
}
} catch (Exception ex) {
//no-op
}
}
}
private void saveParametersValues() {
Preferences modulePreferences = NbPreferences.forModule(QueryResultsView.class);
Preferences paramsPreferences = modulePreferences.node(queryName);
parameters.toCollection().stream().forEach((pField) -> {
try {
Parameter parameter = (Parameter) pField;
Preferences paramNode = paramsPreferences.node(parameter.getName());
if (parameter.getValue() != null) {
if (parameter.getValue() instanceof Date) {
paramNode.putLong(VALUE_PREF_KEY, ((Date) parameter.getValue()).getTime());
} else if (SQLUtils.getTypeGroup(parameter.getTypeInfo().getSqlType()) == SQLUtils.TypesGroup.NUMBERS) {
paramNode.putDouble(VALUE_PREF_KEY, ((Number) parameter.getValue()).doubleValue());
} else if (SQLUtils.getTypeGroup(parameter.getTypeInfo().getSqlType()) == SQLUtils.TypesGroup.LOGICAL) {
paramNode.putBoolean(VALUE_PREF_KEY, (Boolean) parameter.getValue());
} else {
String sVal = SQLUtils.sqlObject2stringRepresentation(parameter.getTypeInfo().getSqlType(), parameter.getValue());
paramNode.put(VALUE_PREF_KEY, sVal);
}
} else {
paramNode.remove(VALUE_PREF_KEY);
}
} catch (Exception ex) {
//no-op
}
});
}
public void close() throws Exception {
if (flow != null) {
flow.close();
flow = null;
}
}
public static class PageSizeItem {
private final Integer pageSize;
public PageSizeItem(int aPageSize) {
pageSize = aPageSize;
}
public int getValue() {
return pageSize;
}
@Override
public String toString() {
return String.format(NbBundle.getMessage(QuerySetupView.class, "QueryResultsView.pageSizeStr"), pageSize); //NOI18N
}
}
}
| |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ecs.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
*/
public class DescribeContainerInstancesRequest extends AmazonWebServiceRequest
implements Serializable, Cloneable {
/**
* <p>
* The short name or full Amazon Resource Name (ARN) of the cluster that
* hosts the container instances to describe. If you do not specify a
* cluster, the default cluster is assumed.
* </p>
*/
private String cluster;
/**
* <p>
* A space-separated list of container instance IDs or full Amazon Resource
* Name (ARN) entries.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> containerInstances;
/**
* <p>
* The short name or full Amazon Resource Name (ARN) of the cluster that
* hosts the container instances to describe. If you do not specify a
* cluster, the default cluster is assumed.
* </p>
*
* @param cluster
* The short name or full Amazon Resource Name (ARN) of the cluster
* that hosts the container instances to describe. If you do not
* specify a cluster, the default cluster is assumed.
*/
public void setCluster(String cluster) {
this.cluster = cluster;
}
/**
* <p>
* The short name or full Amazon Resource Name (ARN) of the cluster that
* hosts the container instances to describe. If you do not specify a
* cluster, the default cluster is assumed.
* </p>
*
* @return The short name or full Amazon Resource Name (ARN) of the cluster
* that hosts the container instances to describe. If you do not
* specify a cluster, the default cluster is assumed.
*/
public String getCluster() {
return this.cluster;
}
/**
* <p>
* The short name or full Amazon Resource Name (ARN) of the cluster that
* hosts the container instances to describe. If you do not specify a
* cluster, the default cluster is assumed.
* </p>
*
* @param cluster
* The short name or full Amazon Resource Name (ARN) of the cluster
* that hosts the container instances to describe. If you do not
* specify a cluster, the default cluster is assumed.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeContainerInstancesRequest withCluster(String cluster) {
setCluster(cluster);
return this;
}
/**
* <p>
* A space-separated list of container instance IDs or full Amazon Resource
* Name (ARN) entries.
* </p>
*
* @return A space-separated list of container instance IDs or full Amazon
* Resource Name (ARN) entries.
*/
public java.util.List<String> getContainerInstances() {
if (containerInstances == null) {
containerInstances = new com.amazonaws.internal.SdkInternalList<String>();
}
return containerInstances;
}
/**
* <p>
* A space-separated list of container instance IDs or full Amazon Resource
* Name (ARN) entries.
* </p>
*
* @param containerInstances
* A space-separated list of container instance IDs or full Amazon
* Resource Name (ARN) entries.
*/
public void setContainerInstances(
java.util.Collection<String> containerInstances) {
if (containerInstances == null) {
this.containerInstances = null;
return;
}
this.containerInstances = new com.amazonaws.internal.SdkInternalList<String>(
containerInstances);
}
/**
* <p>
* A space-separated list of container instance IDs or full Amazon Resource
* Name (ARN) entries.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setContainerInstances(java.util.Collection)} or
* {@link #withContainerInstances(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param containerInstances
* A space-separated list of container instance IDs or full Amazon
* Resource Name (ARN) entries.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeContainerInstancesRequest withContainerInstances(
String... containerInstances) {
if (this.containerInstances == null) {
setContainerInstances(new com.amazonaws.internal.SdkInternalList<String>(
containerInstances.length));
}
for (String ele : containerInstances) {
this.containerInstances.add(ele);
}
return this;
}
/**
* <p>
* A space-separated list of container instance IDs or full Amazon Resource
* Name (ARN) entries.
* </p>
*
* @param containerInstances
* A space-separated list of container instance IDs or full Amazon
* Resource Name (ARN) entries.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public DescribeContainerInstancesRequest withContainerInstances(
java.util.Collection<String> containerInstances) {
setContainerInstances(containerInstances);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCluster() != null)
sb.append("Cluster: " + getCluster() + ",");
if (getContainerInstances() != null)
sb.append("ContainerInstances: " + getContainerInstances());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeContainerInstancesRequest == false)
return false;
DescribeContainerInstancesRequest other = (DescribeContainerInstancesRequest) obj;
if (other.getCluster() == null ^ this.getCluster() == null)
return false;
if (other.getCluster() != null
&& other.getCluster().equals(this.getCluster()) == false)
return false;
if (other.getContainerInstances() == null
^ this.getContainerInstances() == null)
return false;
if (other.getContainerInstances() != null
&& other.getContainerInstances().equals(
this.getContainerInstances()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getCluster() == null) ? 0 : getCluster().hashCode());
hashCode = prime
* hashCode
+ ((getContainerInstances() == null) ? 0
: getContainerInstances().hashCode());
return hashCode;
}
@Override
public DescribeContainerInstancesRequest clone() {
return (DescribeContainerInstancesRequest) super.clone();
}
}
| |
package net.community.chest.util.map;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeSet;
import net.community.chest.util.compare.BooleansComparator;
import net.community.chest.util.map.entries.BooleansMapEntry;
/**
* Copyright 2007 as per GPLv2
*
* Implements a {@link java.util.Map} whose key(s) are {@link Boolean}-s (or the
* equivalent atomic type). The map has special handling for <I>null></I>
* keys - they may be allowed or not - depending on the specification in the
* constructor. In other words, the map can either contain at most 2 keys (if
* <I>null></I>-s are not allowed) or 3 keys (if <I>null></I> are allowed)
*
* @param <V> Type of contained values(s)
* @author Lyor G.
* @since Jun 21, 2007 1:41:14 PM
*/
public class BooleansMap<V> extends AbstractSortedMap<Boolean,V> {
private final boolean _allowNullKey;
public final /* no cheating */ boolean isNullKeyAllowed ()
{
return _allowNullKey;
}
/**
* @param key The {@link Boolean} key
* @return The zero based index of the key in the {@link #_values}
* array - negative if <code>null</code> key and {@link #isNullKeyAllowed()}
* returns <code>false</code>
*/
protected int getKeyIndex (final Boolean key)
{
final boolean allowNullKey=isNullKeyAllowed();
if (null == key)
{
if (allowNullKey)
return 0;
else
return (-1);
}
else
{
final int offset=key.booleanValue() ? 1 : 0;
if (allowNullKey)
return (1 + offset);
else
return offset;
}
}
private final V[] _values;
protected final V[] getObjects ()
{
return _values;
}
private final boolean[] _keys; // TRUE means that the value has been set
protected final boolean[] getKeyFlags ()
{
return _keys;
}
public BooleansMap (Class<V> objClass, final boolean allowNullKey)
{
super(Boolean.class, objClass);
_allowNullKey = allowNullKey;
final int vSize=getKeyIndex(Boolean.TRUE) + 1;
_values = allocateValuesArray(vSize); // all null...
_keys = new boolean[vSize]; // all FALSE...
}
/*
* @see java.util.Map#clear()
*/
@Override
public void clear ()
{
final V[] ov=getObjects();
for (int vIndex=0; vIndex < ov.length; vIndex++)
ov[vIndex] = null;
final boolean[] kf=getKeyFlags();
for (int kIndex=0; kIndex < kf.length; kIndex++)
kf[kIndex] = false;
}
/*
* @see java.util.Map#size()
*/
@Override
public int size ()
{
int sz=0;
// simply count number of valid keys
final boolean[] kf=getKeyFlags();
for (final boolean k : kf)
{
if (k)
sz++;
}
return sz;
}
/*
* @see java.util.SortedMap#comparator()
*/
@Override
public Comparator<? super Boolean> comparator ()
{
return BooleansComparator.ASCENDING;
}
/*
* @see java.util.Map#get(java.lang.Object)
*/
@Override
public V get (final Object key)
{
final int kIndex;
if ((null == key) || (key instanceof Boolean))
kIndex = getKeyIndex((Boolean) key);
else
kIndex = Integer.MIN_VALUE;
final boolean[] kf=getKeyFlags();
if ((kIndex < 0) || (kIndex >= kf.length) || (!kf[kIndex]))
return null;
return getObjects()[kIndex];
}
public V get (final boolean key)
{
return get(Boolean.valueOf(key));
}
/*
* @see java.util.Map#put(java.lang.Object, java.lang.Object)
*/
@Override
public V put (Boolean key, V value)
{
final int kIndex=getKeyIndex(key);
if (kIndex < 0)
throw new IllegalArgumentException(getExceptionLocation("put") + "[" + key + "] invalid key for value=" + value);
final boolean[] kf=getKeyFlags();
final V[] ov=getObjects();
final boolean prevExists=kf[kIndex];
final V prev=prevExists ? ov[kIndex] : null;
if (!prevExists) // debug breakpoint
kf[kIndex] = true; // mark as valid key
ov[kIndex] = value;
return prev;
}
public V put (boolean key, V value)
{
return put(Boolean.valueOf(key), value);
}
/*
* @see java.util.Map#remove(java.lang.Object)
*/
@Override
public V remove (final Object key)
{
final int kIndex;
if ((null == key) || (key instanceof Boolean))
kIndex = getKeyIndex((Boolean) key);
else
kIndex = Integer.MIN_VALUE;
final boolean[] kf=getKeyFlags();
if ((kIndex < 0) || (kIndex >= kf.length) || (!kf[kIndex]))
return null;
final V[] ov=getObjects();
final V prev=ov[kIndex];
kf[kIndex] = false; // mark as invalid
ov[kIndex] = null;
return prev;
}
public V remove (boolean key)
{
return remove(Boolean.valueOf(key));
}
/**
* @param kIndex Key index in the {@link #_values} array
* @return The matching {@link Boolean} key - <code>null</code>
* if no match found.
*/
protected Boolean fromKeyIndex (final int kIndex)
{
final boolean allowNullKey=isNullKeyAllowed();
if (allowNullKey)
{
if (0 == kIndex)
return null;
else
return Boolean.valueOf(kIndex > 1);
}
return Boolean.valueOf(kIndex > 0);
}
/*
* @see java.util.SortedMap#firstKey()
*/
@Override
public Boolean firstKey ()
{
final boolean[] kf=getKeyFlags();
for (int kIndex=0; kIndex < kf.length; kIndex++)
{
if (kf[kIndex])
return fromKeyIndex(kIndex);
}
throw new NoSuchElementException(getExceptionLocation("firstKey") + " no match found");
}
/*
* @see java.util.SortedMap#lastKey()
*/
@Override
public Boolean lastKey ()
{
final boolean[] kf=getKeyFlags();
for (int kIndex=kf.length-1; kIndex >= 0; kIndex--)
{
if (kf[kIndex])
return fromKeyIndex(kIndex);
}
throw new NoSuchElementException(getExceptionLocation("lastKey") + " no match found");
}
/*
* @see java.util.Map#values()
*/
@Override
public Collection<V> values ()
{
final boolean[] kf=getKeyFlags();
final V[] ov=getObjects();
Collection<V> vals=null;
for (int kIndex=0; kIndex < kf.length; kIndex++)
{
if (kf[kIndex])
{
if (null == vals)
vals = new LinkedList<V>();
vals.add(ov[kIndex]);
}
}
return vals;
}
/*
* @see java.util.Map#keySet()
*/
@Override
public Set<Boolean> keySet ()
{
final boolean[] kf=getKeyFlags();
Set<Boolean> keys=null;
for (int kIndex=0; kIndex < kf.length; kIndex++)
{
if (kf[kIndex])
{
if (null == keys)
keys = new TreeSet<Boolean>(comparator());
keys.add(fromKeyIndex(kIndex));
}
}
return keys;
}
/**
* Copyright 2007 as per GPLv2
*
* Compares 2 entries based on their key
* @param <V> Type of value being compared
* @author Lyor G.
* @since Jun 21, 2007 14:28:51
*/
protected static final class EntriesComparator<V> implements Comparator<Entry<Boolean,V>>, Serializable {
/**
*
*/
private static final long serialVersionUID = -2827350353807091431L;
protected EntriesComparator ()
{
super();
}
/*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare (final Entry<Boolean, V> o1, final Entry<Boolean, V> o2)
{
return BooleansComparator.ASCENDING.compare((null == o1) ? null : o1.getKey(), (null == o2) ? null : o2.getKey());
}
}
/*
* @see java.util.Map#entrySet()
*/
@Override
public Set<Entry<Boolean, V>> entrySet ()
{
final boolean[] kf=getKeyFlags();
final V[] ov=getObjects();
Set<Entry<Boolean, V>> s=null;
for (int kIndex=0; kIndex < kf.length; kIndex++)
{
if (kf[kIndex])
{
if (null == s)
s = new TreeSet<Entry<Boolean,V>>(new EntriesComparator<V>());
s.add(new BooleansMapEntry<V>(fromKeyIndex(kIndex), ov[kIndex]));
}
}
return s;
}
/*
* @see java.util.SortedMap#subMap(java.lang.Object, java.lang.Object)
*/
@Override
public SortedMap<Boolean, V> subMap (final Boolean fromKey, final Boolean toKey)
{
if (null == toKey)
{
if (fromKey != null)
throw new IllegalArgumentException(getExceptionLocation("subMap") + " inverted range: null - " + toKey);
}
else if (fromKey != null)
{
if (fromKey.compareTo(toKey) > 0)
throw new IllegalArgumentException(getExceptionLocation("subMap") + " inverted range: " + fromKey + " - " + toKey);
}
BooleansMap<V> res=null;
final boolean[] kf=getKeyFlags();
final V[] ov=getObjects();
for (int kIndex=0; kIndex < kf.length; kIndex++)
{
if (kf[kIndex])
{
final Boolean key=fromKeyIndex(kIndex);
if (fromKey != null)
{
if ((null == key) || (fromKey.compareTo(key) > 0))
continue;
}
if (toKey != null)
{
if ((key != null) && (toKey.compareTo(key) < 0))
break;
}
if (null == res)
res = new BooleansMap<V>(getValuesClass(), isNullKeyAllowed());
res.put(key, ov[kIndex]);
}
}
return res;
}
/*
* @see java.util.SortedMap#headMap(java.lang.Object)
*/
@Override
public SortedMap<Boolean, V> headMap (final Boolean toKey)
{
return subMap(null, toKey);
}
/*
* @see java.util.SortedMap#tailMap(java.lang.Object)
*/
@Override
public SortedMap<Boolean, V> tailMap (final Boolean fromKey)
{
return subMap(fromKey, Boolean.TRUE);
}
}
| |
package se.scrier.plugin.test.junit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* <xs:element name="testsuites">
* <xs:complexType>
* <xs:sequence>
* <xs:element ref="testsuite" minOccurs="0" maxOccurs="unbounded"/>
* </xs:sequence>
* <xs:attribute name="name" type="xs:string" use="optional"/>
* <xs:attribute name="time" type="xs:string" use="optional"/>
* <xs:attribute name="tests" type="xs:string" use="optional"/>
* <xs:attribute name="failures" type="xs:string" use="optional"/>
* <xs:attribute name="disabled" type="xs:string" use="optional"/>
* <xs:attribute name="errors" type="xs:string" use="optional"/>
* </xs:complexType>
* </xs:element>
*/
public class TestSuites extends XmlElement {
private static Logger log = Logger.getLogger(TestSuites.class);
// Elements
private List<TestSuite> testsuite;
// Attributes
private String name;
private double time;
private int tests;
private int failures;
private int disabled;
private int errors;
// Strings
transient private final String ELEMENT = "testsuites";
transient private final String NAME_ATTRIBUTE = "name";
transient private final String TIME_ATTRIBUTE = "time";
transient private final String TESTS_ATTRIBUTE = "tests";
transient private final String FAILURES_ATTRIBUTE = "failures";
transient private final String DISABLED_ATTRIBUTE = "disabled";
transient private final String ERRORS_ATTRIBUTE = "errors";
// Modified
transient protected final long NAME_MODIFIED = 0x0000000000000001L;
transient protected final long TIME_MODIFIED = 0x0000000000000002L;
transient protected final long TESTS_MODIFIED = 0x0000000000000004L;
transient protected final long FAILURES_MODIFIED = 0x0000000000000008L;
transient protected final long DISABLED_MODIFIED = 0x0000000000000010L;
transient protected final long ERRORS_MODIFIED = 0x0000000000000020L;
/**
* Constructor
*/
public TestSuites() {
log.trace("TestSuites()");
setTestsuite(new ArrayList<TestSuite>());
setName("");
setTime(0);
setTests(0);
setFailures(0);
setDisabled(0);
setErrors(0);
resetValuesModified();
}
@Override
public void write(Document doc, Element parent) throws RequiredAttributeException {
if ( null == doc ) {
throw new NullPointerException("Document is not allowed to be null in TestSuites::write(Document doc, Element parent) method.");
} else {
Element element = doc.createElement(ELEMENT);
if( true == isValueModified(NAME_MODIFIED) ) {
element.setAttribute(NAME_ATTRIBUTE, getName());
}
if( true == isValueModified(TIME_MODIFIED) ) {
element.setAttribute(TIME_ATTRIBUTE, String.format("%.4f", getTime()));
}
if( true == isValueModified(TESTS_MODIFIED) ) {
element.setAttribute(TESTS_ATTRIBUTE, String.valueOf(getTests()));
}
if( true == isValueModified(FAILURES_MODIFIED) ) {
element.setAttribute(FAILURES_ATTRIBUTE, String.valueOf(getFailures()));
}
if( true == isValueModified(DISABLED_MODIFIED) ) {
element.setAttribute(DISABLED_ATTRIBUTE, String.valueOf(getDisabled()));
}
if( true == isValueModified(ERRORS_MODIFIED) ) {
element.setAttribute(ERRORS_ATTRIBUTE, String.valueOf(getErrors()));
}
for( TestSuite suite : getTestsuite() ) {
suite.write(doc, element);
}
if( null == parent ) {
doc.appendChild(element);
} else {
parent.appendChild(element);
}
}
}
@Override
public void autoComplete() {
for( TestSuite suite : getTestsuite() ) {
suite.autoComplete();
}
int pFailures = -1;
int pDisabled = -1;
int pErrors = -1;
if( true != isValueModified(FAILURES_MODIFIED) ) {
pFailures = 0;
}
if( true != isValueModified(DISABLED_MODIFIED) ) {
pDisabled = 0;
}
if( true != isValueModified(ERRORS_MODIFIED) ) {
pErrors = 0;
}
if( true != isValueModified(TESTS_MODIFIED) ) {
setTests(getTestsuite().size());
}
for( TestSuite suite : getTestsuite() ) {
if( suite.isDisabled() ) {
pDisabled++;
} else if( -1 != pErrors && 0 < suite.getErrors() ) {
pErrors++;
} else if ( -1 != pFailures && 0 < suite.getFailures() ) {
pFailures++;
}
}
if( -1 != pDisabled ) {
setDisabled(pDisabled);
}
if( -1 != pErrors ) {
setErrors(pErrors);
}
if( -1 != pFailures ) {
setFailures(pFailures);
}
}
/**
* Method to sort TestSuite objects.
*/
public void sortTestSuite() {
Collections.sort(getTestsuite());
for( TestSuite suite : getTestsuite() ) {
suite.sortTestCase();
}
}
/**
* @return the testsuite
*/
public List<TestSuite> getTestsuite() {
return testsuite;
}
/**
* @param testsuite the testsuite to set
*/
public void setTestsuite(List<TestSuite> testsuite) {
this.testsuite = testsuite;
}
/**
* @param testsuite the testsuite to add
*/
public void addTestsuite(TestSuite testsuite) {
this.testsuite.add(testsuite);
}
/**
* @param testsuite the testsuite to add
*/
public boolean containsTestsuite(TestSuite testsuite) {
boolean retValue = containsTestsuite(testsuite.getName());
return retValue;
}
/**
* Method to check if the testSuite exists by name.
* @param name String
*/
public boolean containsTestsuite(String name) {
boolean retValue = false;
for( TestSuite suite : getTestsuite() ) {
if( name.equals(suite.getName()) ) {
retValue = true;
break;
}
}
return retValue;
}
/**
* @param name the name of the testsuite.
*/
public TestSuite getTestsuite(String name) {
TestSuite retValue = null;
for( TestSuite suite : getTestsuite() ) {
if( name.equals(suite.getName()) ) {
retValue = suite;
break;
}
}
return retValue;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
if( this.name != name ) {
this.name = name;
addValuesModified(NAME_MODIFIED);
}
}
/**
* @return the time
*/
public double getTime() {
return time;
}
/**
* @param time the time to set
*/
public void setTime(double time) {
if( this.time != time ) {
this.time = time;
addValuesModified(TIME_MODIFIED);
}
}
/**
* @return the tests
*/
public int getTests() {
return tests;
}
/**
* @param tests the tests to set
*/
public void setTests(int tests) {
if( this.tests != tests ) {
this.tests = tests;
addValuesModified(TESTS_MODIFIED);
}
}
/**
* @return the failures
*/
public int getFailures() {
return failures;
}
/**
* @param failures the failures to set
*/
public void setFailures(int failures) {
if( this.failures != failures ) {
this.failures = failures;
addValuesModified(FAILURES_MODIFIED);
}
}
/**
* @return the disabled
*/
public int getDisabled() {
return disabled;
}
/**
* @param disabled the disabled to set
*/
public void setDisabled(int disabled) {
if( this.disabled != disabled ) {
this.disabled = disabled;
addValuesModified(DISABLED_MODIFIED);
}
}
/**
* @return the errors
*/
public int getErrors() {
return errors;
}
/**
* @param errors the errors to set
*/
public void setErrors(int errors) {
if( this.errors != errors ) {
this.errors = errors;
addValuesModified(ERRORS_MODIFIED);
}
}
}
| |
/*
Copyright 2011-2016 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.security.zynamics.binnavi.Gui.MainWindow.Implementations;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.Database.Exceptions.CPartialLoadException;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntDeleteException;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException;
import com.google.security.zynamics.binnavi.Database.Exceptions.LoadCancelledException;
import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase;
import com.google.security.zynamics.binnavi.Gui.Loaders.CModuleLoader;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Updaters.ITreeUpdater;
import com.google.security.zynamics.binnavi.Gui.Progress.CDefaultProgressOperation;
import com.google.security.zynamics.binnavi.Gui.errordialog.NaviErrorDialog;
import com.google.security.zynamics.binnavi.Importers.CFailedImport;
import com.google.security.zynamics.binnavi.Importers.CImporterFactory;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.algorithms.CViewInserter;
import com.google.security.zynamics.binnavi.disassembly.views.CView;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.zylib.gui.CMessageBox;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTree;
/**
* Contains helper functions for working with modules.
*/
public final class CModuleFunctions {
/**
* You are not supposed to instantiate this class.
*/
private CModuleFunctions() {
}
/**
* Copies a view into a module view.
*
* @param parent Parent window used for dialogs.
* @param module Module where the copied view is stored.
* @param view The view to copy.
*/
public static void copyView(final JFrame parent, final INaviModule module, final INaviView view) {
Preconditions.checkNotNull(parent, "IE01832: Parent argument can not be null");
Preconditions.checkNotNull(module, "IE01833: Module argument can not be null");
Preconditions.checkNotNull(view, "IE01834: View argument can not be null");
if (module.getContent().getViewContainer().hasView(view)) {
if (!view.isLoaded()) {
try {
view.load();
} catch (final CouldntLoadDataException e) {
CUtilityFunctions.logException(e);
final String innerMessage = "E00133: View could not be copied";
final String innerDescription =
CUtilityFunctions.createDescription(String.format(
"The view '%s' could not be copied because it could not be loaded.",
view.getName()),
new String[] {"There was a problem with the database connection."},
new String[] {"The new view was not created."});
NaviErrorDialog.show(parent, innerMessage, innerDescription, e);
return;
} catch (CPartialLoadException | LoadCancelledException e) {
CUtilityFunctions.logException(e);
return;
}
}
final CView newView =
module.getContent().getViewContainer()
.createView(String.format("Copy of %s", view.getName()), null);
CViewInserter.insertView(view, newView);
}
}
/**
* Deletes a module from the database.
*
* @param parent Parent frame used for dialogs.
* @param database The database where the module is stored.
* @param modules The module to be deleted.
* @param updater Updates the project tree if deletion was successful.
*/
public static void deleteModules(final JFrame parent, final IDatabase database,
final INaviModule[] modules, final ITreeUpdater updater) {
if (CMessageBox.showYesNoQuestion(parent, String.format(
"Do you really want to delete the following modules from the database?\n\n%s",
CNameListGenerators.getNameList(modules))) == JOptionPane.YES_OPTION) {
for (final INaviModule module : modules) {
new Thread() {
@Override
public void run() {
final CDefaultProgressOperation operation =
new CDefaultProgressOperation("", true, false);
operation.getProgressPanel().setMaximum(1);
operation.getProgressPanel().setText(
"Deleting module" + ": " + module.getConfiguration().getName());
try {
database.getContent().delete(module);
operation.getProgressPanel().next();
updater.update();
} catch (final CouldntDeleteException e) {
CUtilityFunctions.logException(e);
final String message = "E00031: " + "Module could not be deleted";
final String description =
CUtilityFunctions
.createDescription(
String
.format(
"The module '%s' could not be deleted. Try to delete the module again. If the problem persists, disconnect from and reconnect to the database, restart com.google.security.zynamics.binnavi, or contact the BinNavi support.",
module.getConfiguration().getName()),
new String[] {"Database connection problems."},
new String[] {"The module still exists."});
NaviErrorDialog.show(parent, message, description, e);
} finally {
operation.stop();
}
}
}.start();
}
}
}
/**
* Imports a module into the database using IDA Pro.
*
* @param parent Parent frame used for dialogs.
* @param database The database where the imported project is stored.
*/
public static void importModule(final JFrame parent, final IDatabase database) {
new Thread() {
@Override
public void run() {
try {
final List<CFailedImport> failedImports = new ArrayList<CFailedImport>();
final boolean hasImportedModules =
CImporterFactory.importModules(parent, database, failedImports);
for (final CFailedImport failedImport : failedImports) {
final String message = "E00043: " + "IDB file could not be imported";
final String description =
CUtilityFunctions.createDescription(String.format(
"The IDB file '%s' could not be imported. Please check the stack "
+ "trace for more information.", failedImport.geFileName()), new String[] {
"Database connection problems.", "Bug in the IDB exporter."},
new String[] {"The IDB file was imported partially. A raw module in an "
+ "incosistent state was created. This raw module should be deleted."});
NaviErrorDialog.show(parent, message, description, failedImport.getImportException());
}
if (database.isConnected() && hasImportedModules) {
CDatabaseFunctions.refreshRawModules(parent, database);
}
} catch (final FileNotFoundException exception) {
CUtilityFunctions.logException(exception);
final String message = "E00034: " + "IDA Pro executable could not be found";
final String description =
CUtilityFunctions.createDescription(
"The selected IDB file could not be imported because the IDA Pro executable "
+ "file could not be found.",
new String[] {"Invalid IDA Pro executable file specified.",},
new String[] {"The IDB file was not imported."});
NaviErrorDialog.show(parent, message, description, exception);
} catch (final InterruptedException exception) {
CUtilityFunctions.logException(exception);
final String message = "Import of IDB files failed";
final String description =
CUtilityFunctions.createDescription(
"Importing failed because one of the background workers was interrupted.",
new String[] {"Background threads were interrupted.",},
new String[] {"One or more IDB files were not imported."});
NaviErrorDialog.show(parent, message, description, exception);
Thread.currentThread().interrupt();
} catch (final ExecutionException exception) {
CUtilityFunctions.logException(exception);
final String message = "Import of IDB files failed";
final String description =
CUtilityFunctions.createDescription(
"Importing failed because the background workers threw an exception.",
new String[] {"Background threads threw an exception.",},
new String[] {"One or more IDB files were not imported."});
NaviErrorDialog.show(parent, message, description, exception);
}
}
}.start();
}
/**
* Loads one or more modules.
*
* @param projectTree Project tree of the main window.
* @param modules The modules to load.
*/
public static void loadModules(final JTree projectTree, final INaviModule[] modules) {
for (final INaviModule module : modules) {
if (module.isInitialized()) {
CModuleLoader.loadModule(projectTree, module);
} else {
CModuleInitializationFunctions.initializeAndLoadModule(projectTree, module);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.